diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index f96bf9a4a7..37796f6816 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -16,6 +16,7 @@ on: - "crates/tiff/**" - "crates/heif/**" - "crates/cms/**" + - "crates/cdr/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/formats.yml" @@ -33,6 +34,7 @@ on: - "crates/tiff/**" - "crates/heif/**" - "crates/cms/**" + - "crates/cdr/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/formats.yml" @@ -67,6 +69,7 @@ jobs: - { crate: craft-tiff, features: "" } - { crate: craft-heif, features: "testdata" } - { crate: craft-cms, features: "" } + - { crate: craft-cdr, features: "synth" } # fmt, clippy with default and with all features, and the tests run in the Workspace gate on # every OS; this lints each feature alone and checks the web build. name: ${{ matrix.crate }} feature sets, WASM diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index b63d1a79ec..c583402a58 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -76,6 +76,10 @@ jobs: cache-workspace-crates: true cold-build: ${{ github.event.schedule == '17 0 * * *' }} lint-cache: false + # The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them. + unreached-rs-allow: | + **/fixtures/** + vendor/** timeout-minutes: &timeout 120 # Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml). tools: &tools cargo-nextest@0.9.150 diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 910f2bd710..3d1ef77494 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -183,3 +183,9 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. `crates/xfdf` extracts PDFCraft field reading from #5937 refresh `cb564fd827f572818e9ddb0ea5989a432b1f39fd` (MIT OR Apache-2.0). App-side annotation and form policy remains local; source history is retained in the original repository. Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnulfo, pkibiego and storybored379; module split by aiongg. Subsequent budget/integration work by Dylan M. Taylor. + +## Y4M range-backed playback + +`crates/media-source/src/y4m.rs` adapts the in-house [FilmCraft Y4mSource at 3f137a7e](https://github.com/storytold/filmcraft/blob/3f137a7ed420cac79b32145f5243b7f98b31f71c/crates/codecs/src/y4m.rs), MIT OR Apache-2.0. Original playback by Lloyd Nicholson ([FilmCraft #1303](https://github.com/storytold/filmcraft/pull/1303)); shared-parser integration by Dylan M. Taylor ([FilmCraft #4862](https://github.com/storytold/filmcraft/pull/4862)). The adaptation changes source/frame types and declines payloads above the shared media allocation ceiling before playback. The parser and its previous header-safety work remain in `craft-y4m` ([craft-libs #933](https://github.com/storytold/craft-libs/pull/933)). + +`crates/media-source/tests/it/y4m.rs` contains original repository-authored synthetic test data under MIT OR Apache-2.0: literal YUV samples and a sparse reader that reports only the length of an oversized frame. It does not use external media or decoder output. diff --git a/Cargo.lock b/Cargo.lock index 96a9f4e107..27b9e695a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -487,7 +487,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -518,7 +518,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -544,7 +544,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -1193,7 +1193,7 @@ dependencies = [ "io-lifetimes 3.0.1", "ipnet", "maybe-owned", - "rustix 1.1.5", + "rustix 1.1.6", "rustix-linux-procfs", "windows-sys 0.61.2", "winx", @@ -1208,7 +1208,7 @@ dependencies = [ "cap-primitives", "io-extras", "io-lifetimes 3.0.1", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -1742,6 +1742,7 @@ dependencies = [ "craft-affinity", "craft-ai", "craft-ai-core", + "craft-android-res", "craft-anicraft-format", "craft-assuan", "craft-atomic", @@ -1752,6 +1753,7 @@ dependencies = [ "craft-ber", "craft-browse", "craft-captions", + "craft-cdr", "craft-cfb", "craft-cloud", "craft-cloud-local", @@ -1876,6 +1878,7 @@ dependencies = [ "craft-platform", "craft-plist", "craft-plotter", + "craft-png", "craft-ppt-binary", "craft-pptx", "craft-prc", @@ -1932,6 +1935,7 @@ dependencies = [ "craft-vectordrawable", "craft-video", "craft-wasm", + "craft-wayland", "craft-web-api", "craft-web-host", "craft-webp", @@ -2012,6 +2016,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-android-res" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-anicraft-format" version = "0.1.0" @@ -2020,6 +2032,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-appkit" +version = "0.1.0" +dependencies = [ + "block2 0.6.2", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "craft-assuan" version = "0.1.0" @@ -2032,7 +2053,7 @@ dependencies = [ name = "craft-atomic" version = "0.1.0" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -2059,7 +2080,7 @@ version = "0.1.0" name = "craft-automation" version = "0.1.0" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "craft-behavior", "craft-control", "craft-host", @@ -2133,6 +2154,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-cdr" +version = "0.1.0" +dependencies = [ + "craft-cdr", + "crc32fast", + "flate2", + "proptest", +] + [[package]] name = "craft-cfb" version = "0.1.0" @@ -2330,8 +2361,11 @@ dependencies = [ name = "craft-develop" version = "0.1.0" dependencies = [ + "craft-color", "craft-color-transform", "craft-develop-model", + "craft-geom", + "craft-raw", "craft-render-parity", "proptest", "rayon", @@ -2711,6 +2745,7 @@ dependencies = [ "craft-font-catalog", "craft-font-manager", "craft-font-store", + "craft-fonts-build", "craft-host", "craft-i18n", "craft-theme", @@ -3260,6 +3295,7 @@ dependencies = [ "craft-frame", "craft-media", "craft-time", + "craft-y4m", "serde", "serde_json", "thiserror 2.0.21", @@ -3449,6 +3485,7 @@ dependencies = [ "egui", "kurbo", "serde", + "serde_json", ] [[package]] @@ -3618,6 +3655,7 @@ dependencies = [ "craft-atomic", "craft-docpath", "craft-host", + "craft-i18n", "craft-theme", "fmv-macos-events", "futures-lite", @@ -3657,6 +3695,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-png" +version = "0.1.0" +dependencies = [ + "png 0.18.1", + "thiserror 2.0.21", +] + [[package]] name = "craft-ppt-binary" version = "0.1.0" @@ -3723,6 +3769,7 @@ version = "0.1.0" dependencies = [ "craft-behavior", "craft-host", + "craft-theme", "craft-ui", "craft-winprint-gdi", "egui", @@ -3802,6 +3849,8 @@ dependencies = [ "egui", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "wasm-bindgen", + "web-sys", ] [[package]] @@ -3847,6 +3896,7 @@ dependencies = [ name = "craft-review" version = "0.1.0" dependencies = [ + "base64 0.23.1", "craft-behavior", "craft-host", "craft-i18n", @@ -4168,6 +4218,7 @@ dependencies = [ name = "craft-tga" version = "0.1.0" dependencies = [ + "image", "thiserror 2.0.21", ] @@ -4215,9 +4266,11 @@ dependencies = [ name = "craft-tiff" version = "0.1.0" dependencies = [ + "image", "proptest", "serde", "thiserror 2.0.21", + "tiff", ] [[package]] @@ -4346,6 +4399,7 @@ dependencies = [ "syn 2.0.119", "toml", "typeid", + "wasm-bindgen-futures", "web-time", ] @@ -4457,7 +4511,9 @@ dependencies = [ "craft-window", "eframe", "egui", + "raw-window-handle", "serde", + "serde_json", "web-time", ] @@ -4479,12 +4535,14 @@ dependencies = [ "craft-host", "craft-i18n", "craft-keymap", + "craft-svg", "craft-theme", "craft-ui-contract", "craft-ui-macros", "craft-ui-test-kit", "craft-ui-widgets", "egui", + "log", "serde", "smallvec", ] @@ -4503,7 +4561,7 @@ dependencies = [ "image", "log", "plist", - "rustix 1.1.5", + "rustix 1.1.6", "semver", "serde", "serde_json", @@ -4578,6 +4636,15 @@ dependencies = [ "wasmprinter", ] +[[package]] +name = "craft-wayland" +version = "0.1.0" +dependencies = [ + "raw-window-handle", + "wayland-backend", + "wayland-client", +] + [[package]] name = "craft-web-api" version = "0.1.0" @@ -4593,7 +4660,10 @@ dependencies = [ name = "craft-web-host" version = "0.1.0" dependencies = [ + "craft-host", + "craft-platform", "wasm-bindgen", + "wasm-bindgen-futures", "wasm-bindgen-test", "web-sys", ] @@ -4618,6 +4688,7 @@ dependencies = [ name = "craft-window" version = "0.1.0" dependencies = [ + "craft-appkit", "craft-atomic", "craft-behavior", "craft-host", @@ -4634,6 +4705,7 @@ dependencies = [ "tempfile", "wayland-client", "winsafe", + "x11rb", ] [[package]] @@ -5338,7 +5410,7 @@ dependencies = [ "drm-ffi", "drm-fourcc", "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -5348,7 +5420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" dependencies = [ "drm-sys", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -5450,7 +5522,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "emath", @@ -5506,7 +5578,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5541,7 +5613,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "accesskit", "ahash", @@ -5560,7 +5632,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5579,7 +5651,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5599,7 +5671,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "egui", @@ -5612,7 +5684,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "eframe", "egui", @@ -5689,7 +5761,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", ] @@ -5762,7 +5834,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5788,7 +5860,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[package]] name = "equator" @@ -5966,6 +6038,7 @@ dependencies = [ "craft-timeline", "craft-ui-gallery", "craft-update", + "epaint_default_fonts", ] [[package]] @@ -6262,7 +6335,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.59.0", ] @@ -6512,7 +6585,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -8211,7 +8284,7 @@ dependencies = [ "libc", "libspa-sys", "nom 8.0.0", - "rustix 1.1.5", + "rustix 1.1.6", "system-deps", ] @@ -8250,7 +8323,7 @@ dependencies = [ "image", "khronos-egl", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tracing", "wayland-backend", @@ -9925,7 +9998,7 @@ dependencies = [ "libspa", "libspa-sys", "pipewire-sys", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -10056,7 +10129,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -11133,9 +11206,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -11151,7 +11224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" dependencies = [ "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -12515,7 +12588,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -13794,7 +13867,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -13807,7 +13880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -13856,7 +13929,7 @@ checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" dependencies = [ "bitflags 2.13.2", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -14485,7 +14558,7 @@ dependencies = [ "libc", "log", "os_pipe", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tree_magic_mini", "wayland-backend", @@ -14602,7 +14675,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -14685,7 +14758,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -14845,7 +14918,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", @@ -15119,19 +15192,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" diff --git a/Cargo.toml b/Cargo.toml index 8afdc685c5..9e861a40bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-android-res = { path = "crates/android-res" } craft-audio-dsp = { path = "crates/audio-dsp" } craft-xfa = { path = "crates/xfa" } craft-evm = { path = "crates/evm" } @@ -37,9 +38,13 @@ log = "0.4" craft-plist = { path = "crates/plist" } craft-wasm = { path = "crates/wasm" } craft-platform = { path = "crates/platform" } +craft-png = { path = "crates/png" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } craft-win32 = { path = "crates/win32" } +craft-appkit = { path = "crates/appkit" } +craft-wayland = { path = "crates/wayland" } +craft-cdr = { path = "crates/cdr" } craft-ai = { path = "crates/ai" } craft-ai-core = { path = "crates/ai-core" } craft-anicraft-format = { path = "crates/anicraft-format" } @@ -310,20 +315,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } 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 8ca284e8db..c63edc0812 100644 --- a/NOTICE +++ b/NOTICE @@ -432,3 +432,14 @@ Original src/avx2/fdct.rs opening notice * Based on the x86 SIMD extension for IJG JPEG library * Copyright (C) 1999-2006, MIYASAKA Masaru. */ + +The .cdr reader (crates/cdr, moved from VectorCraft crates/cdr) reads the record layouts that the +Kaitai Struct specification coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, +MIT License) and its fork by Zach Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch +new_stuff, MIT License) describe. No part of either specification is copied into the crate; the +license text is in crates/cdr/LICENSE-kaitai.txt. + +The Y4M range-backed source in crates/media-source/src/y4m.rs adapts FilmCraft's +original implementation (3f137a7ed420cac79b32145f5243b7f98b31f71c), licensed +MIT OR Apache-2.0. Source notice retained: +Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors. diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index 8e4828f554..7ea67f4ec1 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -37,6 +37,7 @@ //! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition). mod ids; +pub mod properties; mod read; pub(crate) mod store; mod write; diff --git a/crates/aaf/src/aaf/properties.rs b/crates/aaf/src/aaf/properties.rs new file mode 100644 index 0000000000..e9e6d45562 --- /dev/null +++ b/crates/aaf/src/aaf/properties.rs @@ -0,0 +1,93 @@ +//! Borrowed little-endian AAF property-stream records, independent of CFB and object policy. + +/// One indexed AAF property. The payload borrows the original stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Property<'a> { + /// The property ID (pid). + pub id: u16, + /// The stored form of the value, as the index records it. + pub form: u16, + /// The value's bytes. + pub payload: &'a [u8], +} + +/// Malformed property-stream framing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PropertyError { + /// The stream ends before its 4-byte header. + ShortHeader, + /// The header's byte-order mark is not little-endian (0x4c). + UnsupportedByteOrder, + /// The stream ends inside the property index. + TruncatedIndex, + /// A property's length runs past the end of the stream. + TruncatedValue, +} + +/// Property-stream record iterator. It does not deduplicate IDs, interpret forms, +/// copy payloads or impose object budgets; those decisions belong to the caller. +#[derive(Clone, Debug)] +pub struct Properties<'a> { + headers: std::slice::Iter<'a, [u8; 6]>, + payload: &'a [u8], +} + +impl<'a> Properties<'a> { + /// Validate the header and complete index. Payload extents are checked during + /// iteration; callers can validate all extents before copying by iterating a clone. + pub fn new(stream: &'a [u8]) -> Result { + let [order, _, lo, hi, tail @ ..] = stream else { return Err(PropertyError::ShortHeader) }; + if *order != 0x4c { + return Err(PropertyError::UnsupportedByteOrder); + } + let count = usize::from(u16::from_le_bytes([*lo, *hi])); + let (headers, payload) = tail.split_at_checked(count * 6).ok_or(PropertyError::TruncatedIndex)?; + Ok(Self { headers: headers.as_chunks::<6>().0.iter(), payload }) + } + pub(super) fn remaining_count(&self) -> usize { + self.headers.len() + } + + // The store checks duplicate IDs before validating the corresponding payload, + // so a record that is both duplicate and truncated retains its old diagnostic. + pub(super) fn next_id(&self) -> Option { + let [lo, hi, ..] = self.headers.as_slice().first()?; + Some(u16::from_le_bytes([*lo, *hi])) + } +} + +impl<'a> Iterator for Properties<'a> { + type Item = Result, PropertyError>; + + fn next(&mut self) -> Option { + let [id0, id1, form0, form1, len0, len1] = self.headers.next()?; + let len = usize::from(u16::from_le_bytes([*len0, *len1])); + let Some((payload, tail)) = self.payload.split_at_checked(len) else { + self.headers = [].iter(); + return Some(Err(PropertyError::TruncatedValue)); + }; + self.payload = tail; + Some(Ok(Property { id: u16::from_le_bytes([*id0, *id1]), form: u16::from_le_bytes([*form0, *form1]), payload })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_borrow_ordered_payloads_without_deduplicating() { + let stream = [0x4c, 0x20, 2, 0, 0x55, 0, 0x82, 0, 2, 0, 0x55, 0, 0x22, 0, 1, 0, 9, 8, 7]; + let mut records = Properties::new(&stream).unwrap(); + assert_eq!(records.remaining_count(), 2); + assert_eq!(records.next_id(), Some(0x55)); + let first = records.next().unwrap().unwrap(); + assert_eq!(records.next_id(), Some(0x55)); + let second = records.next().unwrap().unwrap(); + assert_eq!(first, Property { id: 0x55, form: 0x82, payload: &[9, 8] }); + assert_eq!(second, Property { id: 0x55, form: 0x22, payload: &[7] }); + assert!(std::ptr::eq(first.payload, &stream[16..18])); + assert!(std::ptr::eq(second.payload, &stream[18..19])); + assert!(records.next().is_none()); + } +} diff --git a/crates/aaf/src/aaf/store.rs b/crates/aaf/src/aaf/store.rs index 859c0ea776..27bfad8560 100644 --- a/crates/aaf/src/aaf/store.rs +++ b/crates/aaf/src/aaf/store.rs @@ -450,28 +450,21 @@ impl R<'_> { } let mut o = Obj::new(e.clsid); let props = self.stream(entry, "properties")?; - if props.len() < 4 { - return Err(bad("short properties stream")); - } - if props[0] != BYTE_ORDER_LE { - return Err(bad("big-endian AAF files are not supported")); - } - let n = rd_u16(&props, 2).unwrap_or(0) as usize; - let mut at = 4 + n * 6; - if at > props.len() { - return Err(bad("truncated property index")); - } + use super::properties::{Properties, Property, PropertyError}; + let framing = |e| match e { + PropertyError::ShortHeader => bad("short properties stream"), + PropertyError::UnsupportedByteOrder => bad("big-endian AAF files are not supported"), + PropertyError::TruncatedIndex => bad("truncated property index"), + PropertyError::TruncatedValue => bad("truncated property value"), + }; + let mut records = Properties::new(&props).map_err(framing)?; // A properties stream can name tens of thousands of ids: do not rescan all earlier ids. - let mut seen = std::collections::HashSet::with_capacity(n); - for i in 0..n { - let (Some(pid), Some(sf), Some(len)) = (rd_u16(&props, 4 + i * 6), rd_u16(&props, 6 + i * 6), rd_u16(&props, 8 + i * 6)) else { - return Err(bad("truncated property index")); - }; + let mut seen = std::collections::HashSet::with_capacity(records.remaining_count()); + while let Some(pid) = records.next_id() { if !seen.insert(pid) { return Err(bad("duplicate property id")); } - let v = props.get(at..at + len as usize).ok_or_else(|| bad("truncated property value"))?; - at += len as usize; + let Property { form: sf, payload: v, .. } = records.next().ok_or_else(|| bad("truncated property index"))?.map_err(framing)?; let value = match sf { SF_STRONG => { let c = self.child(entry, &utf16_of(v))?; diff --git a/crates/android-res/Cargo.toml b/crates/android-res/Cargo.toml new file mode 100644 index 0000000000..cc54d2513c --- /dev/null +++ b/crates/android-res/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-android-res" +description = "Bounded readers for compiled Android binary XML and resource tables" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/android-res/README.md b/crates/android-res/README.md new file mode 100644 index 0000000000..cc3a643e11 --- /dev/null +++ b/crates/android-res/README.md @@ -0,0 +1,16 @@ +# craft-android-res + +Read-only wire decoding for Android compiled XML (AXML) and Android resource +tables (ARSC). XML and resource tables share the bounded chunk, string-pool, +and typed-value readers. APK container selection, manifest inventory policy, +device/security interpretation, and presentation remain consumer-owned. + +## Provenance + +The decoders, checked-reader subset, and synthetic test fixture subset were +moved from [Craft Anything at 8cec25d](https://github.com/storytold/craft-anything/tree/8cec25d02007db604b57ce6735ad4eb44a1a9948/crates/formats). +The original implementation is Brandon Thomas (echelon), [f64ae3bf](https://github.com/storytold/craft-anything/commit/f64ae3bf3c8863a982af1304e06de20653803968). +Later parser bounds and resource identity/qualifier work came from Afloat +and BFlat; typed-attribute handling also includes RRFZ's work. The original +[fixture generator](https://github.com/storytold/craft-anything/blob/8cec25d02007db604b57ce6735ad4eb44a1a9948/crates/testkit/src/android.rs) +remains the source of the test data. No external assets or added dependencies. diff --git a/crates/android-res/src/arsc.rs b/crates/android-res/src/arsc.rs new file mode 100644 index 0000000000..79a029625c --- /dev/null +++ b/crates/android-res/src/arsc.rs @@ -0,0 +1,677 @@ +//! Android compiled resource tables (`resources.arsc`): the global string pool, packages, type +//! and key string pools, type specs, and typed entries per configuration (locale, density, +//! orientation, SDK level…). Simple and complex (bag) entries, sparse and 16-bit offset tables. + +use crate::Error; +use crate::axml::{ResValue, StringPool, chunk}; +use crate::bytes::Reader; +use serde::Serialize; + +const RES_TABLE: u16 = 0x0002; +const RES_PACKAGE: u16 = 0x0200; +const RES_TYPE: u16 = 0x0201; +const RES_TYPE_SPEC: u16 = 0x0202; +const RES_LIBRARY: u16 = 0x0203; +const NO_ENTRY: u32 = 0xffff_ffff; +const MAX_PACKAGES: usize = 64; +const MAX_BAG: usize = 4096; + +/// Limits for one table. +#[derive(Debug, Clone, Copy)] +pub struct Limits { + /// Most entries decoded across all types and configurations. + pub max_entries: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { max_entries: 2_000_000 } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct TypeInfo { + pub id: u8, + pub name: String, + pub entry_count: u32, + /// Configuration qualifiers that have values for this type ("default" for none). + pub configs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Package { + pub id: u32, + pub name: String, + pub types: Vec, + pub keys: usize, + /// Shared-library package references (id → name). + pub libraries: Vec<(u32, String)>, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BagItem { + pub name: String, + pub value: String, + pub value_type: &'static str, +} + +/// One value of one resource in one configuration. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Entry { + /// `0xPPTTEEEE` + pub id: String, + pub package: String, + #[serde(rename = "type")] + pub type_name: String, + pub key: String, + /// Qualifier string, e.g. `fr`, `es-rMX`, `night-xhdpi`, or `default`. + pub config: String, + /// Android locale qualifier, empty for the default locale. + pub locale: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub value_type: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub bag: Vec, + #[serde(skip)] + pub raw: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +pub struct Table { + pub packages: Vec, + pub global_strings: usize, + pub entries: Vec, + pub truncated: bool, + pub warnings: Vec, +} + +fn utf16_fixed(r: &Reader<'_>, off: usize, chars: usize) -> String { + let units: Vec = (0..chars).map_while(|i| r.u16_le(off + i * 2)).take_while(|&u| u != 0).collect(); + String::from_utf16_lossy(&units) +} + +fn ascii2(b: &[u8]) -> String { + b.iter().take_while(|&&c| c != 0).map(|&c| if c.is_ascii_graphic() { c as char } else { '?' }).collect() +} + +/// A packed 2-byte language or region code (3-letter codes are packed into 15 bits). +fn unpack_code(b: &[u8], base: u8) -> String { + let (b0, b1) = (b.first().copied().unwrap_or(0), b.get(1).copied().unwrap_or(0)); + if b0 & 0x80 != 0 { + let first = b1 & 0x1f; + let second = ((b1 & 0xe0) >> 5) | ((b0 & 0x03) << 3); + let third = (b0 & 0x7c) >> 2; + [first, second, third].iter().map(|c| (c.wrapping_add(base)) as char).collect() + } else { + ascii2(&[b0, b1]) + } +} + +fn locale_qualifier(r: &Reader<'_>, off: usize, size: usize, get8: impl Fn(usize) -> Option) -> String { + let lang = if size >= 12 { r.slice(off + 8, 2).map(|b| unpack_code(b, b'a')).unwrap_or_default() } else { String::new() }; + let region = if size >= 12 { r.slice(off + 10, 2).map(|b| unpack_code(b, b'0')).unwrap_or_default() } else { String::new() }; + // Extended locale fields were appended to ResTable_config. Older + // configurations end before one or more of these fields. + let subtag = |start: usize, len: usize| { + if start + len <= size { r.slice(off + start, len).map(ascii2).unwrap_or_default() } else { String::new() } + }; + let script = if get8(52).unwrap_or(0) == 0 { subtag(36, 4) } else { String::new() }; + let variant = subtag(40, 8); + let numbering = subtag(53, 8); + let mut locale = lang; + if !locale.is_empty() && (!script.is_empty() || !variant.is_empty() || !numbering.is_empty()) { + locale.insert_str(0, "b+"); + for part in [&script, ®ion, &variant].into_iter().filter(|p| !p.is_empty()) { + locale.push('+'); + locale.push_str(part); + } + if !numbering.is_empty() { + locale.push_str("+u+nu+"); + locale.push_str(&numbering); + } + } else if !locale.is_empty() && !region.is_empty() { + locale.push_str(&format!("-r{region}")); + } + locale +} + +/// Qualifier string and locale for a `ResTable_config` at `off`. +fn config_qualifiers(r: &Reader<'_>, off: usize) -> (String, String) { + let size = r.u32_le(off).unwrap_or(0) as usize; + let get8 = |o: usize| if o < size { r.u8(off + o) } else { None }; + let get16 = |o: usize| if o + 1 < size { r.u16_le(off + o) } else { None }; + let mut q: Vec = Vec::new(); + if let Some(mcc) = get16(4).filter(|&v| v != 0) { + q.push(format!("mcc{mcc}")); + } + if let Some(mnc) = get16(6).filter(|&v| v != 0) { + q.push(format!("mnc{}", if mnc == u16::MAX { 0 } else { mnc })); + } + let locale = locale_qualifier(r, off, size, get8); + if !locale.is_empty() { + q.push(locale.clone()); + } + let axis = |q: &mut Vec, v: Option, mask, names: &[(u8, &str)]| { + if let Some(key) = v.map(|n| n & mask) + && let Some((_, name)) = names.iter().find(|(value, _)| *value == key) + { + q.push((*name).to_owned()); + } + }; + axis(&mut q, get8(19), 0x03, &[(1, "neuter"), (2, "feminine"), (3, "masculine")]); + if let Some(sl) = get8(28) { + match sl & 0xc0 { + 0x40 => q.push("ldltr".into()), + 0x80 => q.push("ldrtl".into()), + _ => {} + } + } + if let Some(sw) = get16(30).filter(|&v| v != 0) { + q.push(format!("sw{sw}dp")); + } + if let Some(w) = get16(32).filter(|&v| v != 0) { + q.push(format!("w{w}dp")); + } + if let Some(h) = get16(34).filter(|&v| v != 0) { + q.push(format!("h{h}dp")); + } + if let Some(sl) = get8(28) { + match sl & 0x0f { + 1 => q.push("small".into()), + 2 => q.push("normal".into()), + 3 => q.push("large".into()), + 4 => q.push("xlarge".into()), + _ => {} + } + match sl & 0x30 { + 0x10 => q.push("notlong".into()), + 0x20 => q.push("long".into()), + _ => {} + } + } + axis(&mut q, get8(48), 0x03, &[(1, "notround"), (2, "round")]); + axis(&mut q, get8(49), 0x03, &[(1, "nowidecg"), (2, "widecg")]); + axis(&mut q, get8(49), 0x0c, &[(4, "lowdr"), (8, "highdr")]); + match get8(12) { + Some(1) => q.push("port".into()), + Some(2) => q.push("land".into()), + Some(3) => q.push("square".into()), + _ => {} + } + if let Some(ui) = get8(29) { + match ui & 0x0f { + 2 => q.push("desk".into()), + 3 => q.push("car".into()), + 4 => q.push("television".into()), + 5 => q.push("appliance".into()), + 6 => q.push("watch".into()), + 7 => q.push("vrheadset".into()), + _ => {} + } + match ui & 0x30 { + 0x10 => q.push("notnight".into()), + 0x20 => q.push("night".into()), + _ => {} + } + } + if let Some(d) = get16(14).filter(|&v| v != 0) { + q.push(match d { + 120 => "ldpi".into(), + 160 => "mdpi".into(), + 213 => "tvdpi".into(), + 240 => "hdpi".into(), + 320 => "xhdpi".into(), + 480 => "xxhdpi".into(), + 640 => "xxxhdpi".into(), + 0xfffe => "anydpi".into(), + 0xffff => "nodpi".into(), + d => format!("{d}dpi"), + }); + } + match get8(13) { + Some(1) => q.push("notouch".into()), + Some(3) => q.push("finger".into()), + _ => {} + } + axis(&mut q, get8(18), 0x03, &[(1, "keysexposed"), (2, "keyshidden"), (3, "keyssoft")]); + match get8(16) { + Some(1) => q.push("nokeys".into()), + Some(2) => q.push("qwerty".into()), + Some(3) => q.push("12key".into()), + _ => {} + } + axis(&mut q, get8(18), 0x0c, &[(4, "navexposed"), (8, "navhidden")]); + match get8(17) { + Some(1) => q.push("nonav".into()), + Some(2) => q.push("dpad".into()), + Some(3) => q.push("trackball".into()), + Some(4) => q.push("wheel".into()), + _ => {} + } + if let (Some(w), Some(h)) = (get16(20), get16(22)) + && w != 0 + && h != 0 + { + q.push(format!("{w}x{h}")); + } + if let Some(v) = get16(24).filter(|&v| v != 0) { + q.push(format!("v{v}")); + } + let s = if q.is_empty() { "default".to_string() } else { q.join("-") }; + (s, locale) +} + +/// A type's configuration is part of its header, not the entry offsets or payload. +fn type_config(r: &Reader<'_>, at: usize, header_size: usize) -> Option<(String, String)> { + let config = Reader::new(r.slice(at.checked_add(20)?, header_size.checked_sub(20)?)?); + let size = config.u32_le(0)? as usize; + if size < 4 || config.slice(0, size).is_none() { + return None; + } + Some(config_qualifiers(&config, 0)) +} + +struct Pkg<'a> { + name: &'a str, + id: u32, + types: &'a StringPool, + keys: &'a StringPool, +} + +fn type_name(p: &Pkg<'_>, id: u8) -> String { + p.types.get(u32::from(id).wrapping_sub(1)).map(str::to_string).unwrap_or_else(|| format!("type{id}")) +} + +/// Parse a resource table. +pub fn parse(data: &[u8], limits: Limits) -> Result { + let r = Reader::new(data); + let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("resource table header".into()))?; + if t != RES_TABLE { + return Err(Error::Malformed(format!("not a resource table (chunk type {t:#x})"))); + } + if h < 12 { + return Err(Error::Truncated("resource table header".into())); + } + let data = data.get(..size).ok_or_else(|| Error::Truncated("resource table payload".into()))?; + let r = Reader::new(data); + let mut table = Table::default(); + let mut global = StringPool::default(); + let mut pos = h; + while pos < size { + let Some((ct, _ch, cs)) = chunk(&r, pos) else { + table.warnings.push(format!("unreadable chunk at offset {pos}")); + break; + }; + match ct { + crate::axml::RES_STRING_POOL => match StringPool::parse(data, pos) { + Ok(p) => { + if p.strings.len() < p.declared { + table.truncated = true; + table.warnings.push(format!("global string pool was capped at {} of {} strings", p.strings.len(), p.declared)); + } + table.global_strings = p.declared; + global = p; + } + Err(e) => table.warnings.push(format!("global string pool: {e}")), + }, + RES_PACKAGE => { + if table.packages.len() >= MAX_PACKAGES { + table.truncated = true; + table.warnings.push("too many packages; the rest were skipped".into()); + } else { + parse_package(data, pos, cs, &global, &mut table, limits); + } + } + _ => {} + } + pos = match pos.checked_add(cs) { + Some(p) => p, + None => break, + }; + } + Ok(table) +} + +fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits) { + let Some(data) = pos.checked_add(cs).and_then(|end| data.get(..end)) else { + table.warnings.push("package runs past its resource table".into()); + return; + }; + let r = Reader::new(data); + let hsize = usize::from(r.u16_le(pos + 2).unwrap_or(0)); + if hsize < 284 { + table.warnings.push(format!("package at offset {pos}: incomplete header")); + return; + } + let id = r.u32_le(pos + 8).unwrap_or(0); + let name = utf16_fixed(&r, pos + 12, 128); + // Older 284-byte packages predate this field. Type names still use the + // unshifted chunk ID, while public resource identities include the offset. + let type_id_offset = if hsize >= 288 { r.u32_le(pos + 284).unwrap_or(0) } else { 0 }; + let Ok(type_id_offset) = u8::try_from(type_id_offset) else { + table.truncated = true; + table.warnings.push(format!("package {name}: type ID offset is outside the one-byte type field")); + return; + }; + let type_strings = r.u32_le(pos + 268).unwrap_or(0) as usize; + let key_strings = r.u32_le(pos + 276).unwrap_or(0) as usize; + let end = data.len(); + let mut read_pool = |offset: usize, label: &str| { + if offset == 0 { + return StringPool::default(); + } + let Some(start) = pos.checked_add(offset).filter(|&start| offset >= hsize && start < end) else { + table.warnings.push(format!("package {name}: {label} string pool is outside its payload")); + return StringPool::default(); + }; + match StringPool::parse(data, start) { + Ok(pool) => { + if pool.strings.len() < pool.declared { + table.truncated = true; + table.warnings.push(format!( + "package {name}: {label} string pool was capped at {} of {} strings", + pool.strings.len(), + pool.declared + )); + } + pool + } + Err(error) => { + table.warnings.push(format!("package {name}: {label} string pool: {error}")); + StringPool::default() + } + } + }; + let types = read_pool(type_strings, "type"); + let keys = read_pool(key_strings, "key"); + let mut package = Package { id, name: name.clone(), types: Vec::new(), keys: keys.declared, libraries: Vec::new() }; + let p = Pkg { name: &name, id, types: &types, keys: &keys }; + let mut c = pos.saturating_add(hsize.max(8)); + while c < end { + let Some((ct, ch, sz)) = chunk(&r, c) else { + table.warnings.push(format!("package {name}: unreadable chunk at offset {c}")); + break; + }; + // Each child was checked against its package; reads within it must also stop before + // the next sibling, including fixed-width library records and bag headers. + let Some(child) = data.get(..c.saturating_add(sz)) else { + table.warnings.push(format!("package {name}: child chunk runs past its package")); + break; + }; + let r = Reader::new(child); + let local_tid = r.u8(c + 8).unwrap_or(0); + let type_id = local_tid.checked_add(type_id_offset).filter(|_| local_tid != 0); + match (ct, type_id) { + (RES_TYPE_SPEC, Some(tid)) if ch >= 16 => { + let count = r.u32_le(c + 12).unwrap_or(0); + if !package.types.iter().any(|t| t.id == tid) && package.types.len() < 256 { + package.types.push(TypeInfo { id: tid, name: type_name(&p, local_tid), entry_count: count, configs: Vec::new() }); + } + } + (RES_TYPE, Some(tid)) if ch >= 24 => { + let Some((cfg, locale)) = type_config(&r, c, ch) else { + table.truncated = true; + table.warnings.push(format!("package {name}: incomplete type configuration at offset {c}")); + // The child extent was already validated by chunk(). + c += sz; + continue; + }; + match package.types.iter_mut().find(|t| t.id == tid) { + Some(t) => { + if !t.configs.contains(&cfg) && t.configs.len() < 4096 { + t.configs.push(cfg.clone()); + } + } + None => { + if package.types.len() < 256 { + package.types.push(TypeInfo { + id: tid, + name: type_name(&p, local_tid), + entry_count: r.u32_le(c + 12).unwrap_or(0), + configs: vec![cfg.clone()], + }) + } + } + } + parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits); + } + (RES_TYPE_SPEC | RES_TYPE, None) if ch >= 16 => { + table.truncated = true; + table.warnings.push(format!("package {name}: type ID {local_tid} with offset {type_id_offset} is outside the one-byte type field")); + } + (RES_LIBRARY, _) if ch >= 12 => { + let n = r.u32_le(c + 8).unwrap_or(0) as usize; + let available = (sz - ch) / 260; + if n > available { + table.warnings.push(format!("package {name}: library records run past their chunk")); + } + for i in 0..n.min(256).min(available) { + let e = c + ch + i * 260; + if let Some(lid) = r.u32_le(e) { + package.libraries.push((lid, utf16_fixed(&r, e + 4, 128))); + } + } + } + (RES_TYPE_SPEC | RES_TYPE | RES_LIBRARY, _) => { + table.warnings.push(format!("package {name}: incomplete chunk header at offset {c}")); + } + _ => {} + } + c = match c.checked_add(sz) { + Some(x) => x, + None => break, + }; + } + table.packages.push(package); +} + +#[allow(clippy::too_many_arguments)] +fn parse_type( + r: &Reader<'_>, + c: usize, + (ch, sz): (usize, usize), + (cfg, locale): (String, String), + p: &Pkg<'_>, + type_id: u8, + global: &StringPool, + table: &mut Table, + limits: Limits, +) { + let tid = r.u8(c + 8).unwrap_or(0); + let flags = r.u8(c + 9).unwrap_or(0); + let count = r.u32_le(c + 12).unwrap_or(0) as usize; + let entries_start = r.u32_le(c + 16).unwrap_or(0) as usize; + let end = c + sz; + let tname = type_name(p, tid); + let sparse = flags & 0x01 != 0; + let off16 = flags & 0x02 != 0; + // (entry index, offset from entries_start) + let mut slots: Vec<(u32, usize)> = Vec::new(); + let table_bytes = if sparse || off16 { count.saturating_mul(if sparse { 4 } else { 2 }) } else { count.saturating_mul(4) }; + if c.saturating_add(ch).saturating_add(table_bytes) > end { + table.warnings.push(format!("{tname} ({cfg}): entry table runs past its chunk")); + return; + } + if count != 0 && (entries_start < ch.saturating_add(table_bytes) || entries_start > sz) { + table.warnings.push(format!("{tname} ({cfg}): invalid entry data start")); + return; + } + for i in 0..count { + let at = c + ch; + if sparse { + let (Some(idx), Some(o)) = (r.u16_le(at + i * 4), r.u16_le(at + i * 4 + 2)) else { break }; + slots.push((u32::from(idx), usize::from(o) * 4)); + } else if off16 { + let Some(o) = r.u16_le(at + i * 2) else { break }; + if o != 0xffff { + slots.push((i as u32, usize::from(o) * 4)); + } + } else { + let Some(o) = r.u32_le(at + i * 4) else { break }; + if o != NO_ENTRY { + slots.push((i as u32, o as usize)); + } + } + } + for (idx, o) in slots { + if table.entries.len() >= limits.max_entries { + table.truncated = true; + return; + } + let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)) else { continue }; + if e.saturating_add(8) > end { + continue; + } + let esize = usize::from(r.u16_le(e).unwrap_or(0)); + let eflags = r.u16_le(e + 2).unwrap_or(0); + let id = (p.id << 24) | (u32::from(type_id) << 16) | (idx & 0xffff); + let mut entry = Entry { + id: format!("{id:#010x}"), + package: p.name.to_string(), + type_name: tname.clone(), + key: String::new(), + config: cfg.clone(), + locale: locale.clone(), + value: None, + value_type: None, + parent: None, + bag: Vec::new(), + raw: None, + }; + if eflags & 0x08 != 0 { + // Compact entry: key index in the size field, type in the high byte of flags. + entry.key = p.keys.get(u32::from(r.u16_le(e).unwrap_or(0))).unwrap_or("").to_string(); + let v = ResValue { data_type: (eflags >> 8) as u8, data: r.u32_le(e + 4).unwrap_or(0) }; + entry.value = Some(v.format(global)); + entry.value_type = Some(v.type_name()); + entry.raw = Some(v); + } else { + entry.key = r.u32_le(e + 4).and_then(|k| p.keys.get(k)).unwrap_or("").to_string(); + if eflags & 0x01 != 0 { + if esize < 16 || e.saturating_add(esize) > end { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete bag header")); + table.entries.push(entry); + continue; + } + let n = r.u32_le(e + 12).unwrap_or(0) as usize; + let mut m = e + esize; + if n > (end - m) / 12 { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete bag data")); + table.entries.push(entry); + continue; + } + let parent = r.u32_le(e + 8).unwrap_or(0); + if parent != 0 { + entry.parent = Some(format!("@{parent:#010x}")); + } + if n > MAX_BAG { + table.truncated = true; + } + for _ in 0..n.min(MAX_BAG) { + if m.saturating_add(12) > end { + break; + } + let name = r.u32_le(m).unwrap_or(0); + let v = ResValue { data_type: r.u8(m + 7).unwrap_or(0), data: r.u32_le(m + 8).unwrap_or(0) }; + entry.bag.push(BagItem { name: format!("@{name:#010x}"), value: v.format(global), value_type: v.type_name() }); + m += 12; + } + } else { + let v_at = e.saturating_add(esize.max(8)); + if v_at.saturating_add(8) <= end { + let v = ResValue { data_type: r.u8(v_at + 3).unwrap_or(0), data: r.u32_le(v_at + 4).unwrap_or(0) }; + entry.value = Some(v.format(global)); + entry.value_type = Some(v.type_name()); + entry.raw = Some(v); + } + } + } + table.entries.push(entry); + } +} + +impl Table { + /// String resources grouped by locale (`""` = default): (locale, key, value). + pub fn strings_by_locale(&self) -> std::collections::BTreeMap> { + let mut out: std::collections::BTreeMap> = Default::default(); + for e in self.entries.iter().filter(|e| e.type_name == "string") { + if let Some(v) = &e.value { + out.entry(e.locale.clone()).or_default().push((e.key.clone(), v.clone())); + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fixtures as fx; + + #[test] + fn incomplete_table_prefix_is_rejected() { + let bytes = fx::resources_arsc(); + assert!(matches!(parse(&bytes[..7], Limits::default()), Err(Error::Truncated(_)))); + } + + #[test] + fn decodes_table() { + let t = parse(&fx::resources_arsc(), Limits::default()).unwrap(); + assert!(t.warnings.is_empty(), "{:?}", t.warnings); + assert_eq!(t.packages.len(), 1); + let p = &t.packages[0]; + assert_eq!(p.id, 0x7f); + assert_eq!(p.name, fx::PACKAGE); + assert_eq!(p.types[0].name, "string"); + assert_eq!(p.types[0].configs, vec!["default", "fr"]); + let by = t.strings_by_locale(); + assert_eq!(by[""], vec![("app_name".to_string(), "Notes".to_string()), ("greeting".to_string(), "Hello".to_string())]); + assert_eq!(by["fr"], vec![("app_name".to_string(), "Notes FR".to_string()), ("greeting".to_string(), "Bonjour".to_string())]); + let app = t.entries.iter().find(|e| e.key == "app_name" && e.locale.is_empty()).unwrap(); + assert_eq!(app.id, "0x7f010000"); + let style = t.entries.iter().find(|e| e.type_name == "style").unwrap(); + assert_eq!(style.key, "AppTheme"); + assert_eq!(style.parent.as_deref(), Some("@0x01030005")); + assert_eq!(style.bag[0].value, "#ff336699"); + assert_eq!(style.config, "night-xhdpi-v21"); + } + + #[test] + fn distinct_locale_scripts_and_variants_keep_separate_keys() { + let mut cfg = [0u8; 64]; + cfg[0] = 64; + cfg[8..12].copy_from_slice(b"zhTW"); + cfg[36..40].copy_from_slice(b"Hant"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+Hant+TW"); + cfg[36..40].copy_from_slice(b"Hans"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+Hans+TW"); + cfg[52] = 1; // The inferred script is not part of the requested locale. + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "zh-rTW"); + cfg[40..45].copy_from_slice(b"POSIX"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+TW+POSIX"); + cfg[53..57].copy_from_slice(b"latn"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+TW+POSIX+u+nu+latn"); + cfg[0] = 36; // Bytes beyond the declared configuration are unrelated. + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "zh-rTW"); + } + + #[test] + fn qualifiers() { + let mut cfg = vec![0u8; 64]; + cfg[0] = 64; + cfg[8] = b'e'; + cfg[9] = b's'; + cfg[10] = b'M'; + cfg[11] = b'X'; + cfg[12] = 2; + let (q, l) = config_qualifiers(&Reader::new(&cfg), 0); + assert_eq!(q, "es-rMX-land"); + assert_eq!(l, "es-rMX"); + } +} diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs new file mode 100644 index 0000000000..3aea1f7ffc --- /dev/null +++ b/crates/android-res/src/axml.rs @@ -0,0 +1,793 @@ +//! Android binary XML (AXML): the compiled form of `AndroidManifest.xml` and `res/*.xml`. +//! Chunks, the string pool (UTF-8 and UTF-16), the resource-id map, namespaces, elements and +//! typed attribute values. Also the string pool and typed-value formatting that resource tables +//! share. Manifest inventory and policy are left to callers. + +use crate::Error; +use crate::bytes::Reader; +use serde::Serialize; + +pub const RES_STRING_POOL: u16 = 0x0001; +pub const RES_XML: u16 = 0x0003; +const XML_START_NS: u16 = 0x0100; +const XML_END_NS: u16 = 0x0101; +const XML_START_ELEMENT: u16 = 0x0102; +const XML_END_ELEMENT: u16 = 0x0103; +const XML_CDATA: u16 = 0x0104; +const XML_RESOURCE_MAP: u16 = 0x0180; + +/// Most strings decoded from one pool. +const MAX_STRINGS: usize = 1_000_000; +/// Longest string kept (characters). +const MAX_STRING: usize = 64 * 1024; +/// Base budget for decoded string bytes; larger chunks allow at most three times their size. +const BASE_POOL_BYTES: usize = 64 << 20; +/// Most extra UTF-8 length candidates examined across one string pool. +const MAX_RECOVERY_PROBES: usize = 65_536; +/// Most XML nodes decoded. +const MAX_NODES: usize = 200_000; +/// Deepest element nesting tracked. +const MAX_DEPTH: usize = 512; + +pub const ANDROID_NS: &str = "http://schemas.android.com/apk/res/android"; + +/// A chunk header: type, header size, total size, at `off`. +pub(crate) fn chunk(r: &Reader<'_>, off: usize) -> Option<(u16, usize, usize)> { + let t = r.u16_le(off)?; + let h = usize::from(r.u16_le(off.checked_add(2)?)?); + let s = r.u32_le(off.checked_add(4)?)? as usize; + if h < 8 || s < h || off.checked_add(s)? > r.len() { + return None; + } + Some((t, h, s)) +} + +/// Reads the bounded Android chunk header at the given byte offset. +pub fn chunk_header(data: &[u8], off: usize) -> Option<(u16, usize, usize)> { + chunk(&Reader::new(data), off) +} + +/// A decoded string pool. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct StringPool { + pub strings: Vec, + pub utf8: bool, + /// Strings the pool declared (may exceed `strings.len()` when capped). + pub declared: usize, +} + +impl StringPool { + pub fn get(&self, i: u32) -> Option<&str> { + if i == u32::MAX { + return None; + } + self.strings.get(i as usize).map(String::as_str) + } + + /// Parse the pool whose chunk starts at `off`, retaining a prefix within the string and byte budgets. + pub fn parse(data: &[u8], off: usize) -> Result { + let mut recovery_left = MAX_RECOVERY_PROBES; + Self::parse_with_recovery_budget(data, off, &mut recovery_left) + } + + fn parse_with_recovery_budget(data: &[u8], off: usize, recovery_left: &mut usize) -> Result { + let r = Reader::new(data); + let (t, hdr, size) = chunk(&r, off).ok_or_else(|| Error::Truncated("string pool header".into()))?; + if t != RES_STRING_POOL { + return Err(Error::Malformed(format!("expected a string pool, found chunk type {t:#x}"))); + } + if hdr < 28 { + return Err(Error::Malformed("string pool header is smaller than 28 bytes".into())); + } + let r = Reader::new(r.slice(off, size).ok_or_else(|| Error::Truncated("string pool".into()))?); + let count = r.u32_le(8).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let styles = r.u32_le(12).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let flags = r.u32_le(16).ok_or_else(|| Error::Truncated("string pool".into()))?; + let strings_start = r.u32_le(20).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let styles_start = r.u32_le(24).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let utf8 = flags & (1 << 8) != 0; + let offsets_end = count + .checked_add(styles) + .and_then(|n| n.checked_mul(4)) + .and_then(|n| hdr.checked_add(n)) + .ok_or_else(|| Error::Malformed("string pool offset tables are too large".into()))?; + if offsets_end > size || strings_start > size || (count != 0 && strings_start < offsets_end) { + return Err(Error::Malformed("string pool offset tables or string data lie outside their area".into())); + } + if (styles != 0 && styles_start == 0) + || (styles_start != 0 && (styles_start < offsets_end || styles_start < strings_start || styles_start > size)) + { + return Err(Error::Malformed("string pool style data lie outside their area".into())); + } + let end = if styles_start == 0 { size } else { styles_start }; + let string_bytes = r.slice(strings_start, end - strings_start).ok_or_else(|| Error::Truncated("string data".into()))?; + let strings_reader = Reader::new(string_bytes); + let mut strings = Vec::with_capacity(count.min(MAX_STRINGS).min(65_536)); + let mut bytes_left = BASE_POOL_BYTES.max(size.saturating_mul(3)); + for i in 0..count.min(MAX_STRINGS) { + let at = r.u32_le(hdr + i * 4).ok_or_else(|| Error::Truncated("string offsets".into()))? as usize; + let s = if at >= string_bytes.len() { + None + } else if utf8 { + utf8_string(&strings_reader, at, string_bytes.len(), recovery_left) + } else { + utf16_string(&strings_reader, at, string_bytes.len()) + }; + let s = s.unwrap_or_default(); + if s.len() > bytes_left { + break; + } + bytes_left -= s.len(); + strings.push(s); + } + Ok(StringPool { strings, utf8, declared: count }) + } +} + +fn utf8_len(r: &Reader<'_>, at: usize) -> Option<(usize, usize)> { + let b0 = usize::from(r.u8(at)?); + if b0 & 0x80 != 0 { + let b1 = usize::from(r.u8(at + 1)?); + Some((((b0 & 0x7f) << 8) | b1, 2)) + } else { + Some((b0, 1)) + } +} + +fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) -> Option { + let (_chars, n1) = utf8_len(r, at)?; + let (mut bytes, n2) = utf8_len(r, at.checked_add(n1)?)?; + let start = at.checked_add(n1 + n2)?; + // Older AAPT keeps only the low 15 length bits; probe matching lengths inside this pool. + loop { + let terminator = start.checked_add(bytes)?; + if terminator >= end { + return None; + } + // The declared candidate costs one read per entry, already bounded by MAX_STRINGS. + if bytes >= 0x8000 { + *recovery_left = recovery_left.checked_sub(1)?; + } + if r.u8(terminator)? == 0 { + break; + } + bytes = bytes.checked_add(0x8000)?; + } + let b = r.slice(start, bytes.min(MAX_STRING * 4))?; + Some(String::from_utf8_lossy(b).into_owned()) +} + +fn utf16_string(r: &Reader<'_>, at: usize, end: usize) -> Option { + let u0 = usize::from(r.u16_le(at)?); + let (len, hdr) = if u0 & 0x8000 != 0 { (((u0 & 0x7fff) << 16) | usize::from(r.u16_le(at + 2)?), 4) } else { (u0, 2) }; + let start = at.checked_add(hdr)?; + let terminator = start.checked_add(len.checked_mul(2)?)?; + if terminator.checked_add(2)? > end || r.u16_le(terminator)? != 0 { + return None; + } + let n = len.min(MAX_STRING); + let mut units = Vec::with_capacity(n); + for i in 0..n { + units.push(r.u16_le(start + i * 2)?); + } + Some(String::from_utf16_lossy(&units)) +} + +/// A typed value (`Res_value`): data type and 32-bit data. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct ResValue { + pub data_type: u8, + pub data: u32, +} + +impl ResValue { + pub fn type_name(&self) -> &'static str { + match self.data_type { + 0x00 => "null", + 0x01 => "reference", + 0x02 => "attribute", + 0x03 => "string", + 0x04 => "float", + 0x05 => "dimension", + 0x06 => "fraction", + 0x07 => "dynamic-reference", + 0x08 => "dynamic-attribute", + 0x10 => "int-dec", + 0x11 => "int-hex", + 0x12 => "boolean", + 0x1c => "color-argb8", + 0x1d => "color-rgb8", + 0x1e => "color-argb4", + 0x1f => "color-rgb4", + _ => "unknown", + } + } + + /// Human form; strings come from `pool`. + pub fn format(&self, pool: &StringPool) -> String { + let d = self.data; + match self.data_type { + 0x00 => { + if d == 1 { + "@empty".into() + } else { + "@null".into() + } + } + 0x01 | 0x07 => { + if d == 0 { + "@null".into() + } else { + format!("@{d:#010x}") + } + } + 0x02 | 0x08 => format!("?{d:#010x}"), + 0x03 => pool.get(d).unwrap_or("").to_string(), + 0x04 => format!("{}", f32::from_bits(d)), + 0x05 => complex(d, &["px", "dp", "sp", "pt", "in", "mm"]), + 0x06 => complex(d, &["%", "%p"]), + 0x10 => (d as i32).to_string(), + 0x11 => format!("{d:#x}"), + 0x12 => (if d != 0 { "true" } else { "false" }).into(), + 0x1c..=0x1f => format!("#{d:08x}"), + _ => format!("{d:#x} (type {:#x})", self.data_type), + } + } +} + +fn complex(d: u32, units: &[&str]) -> String { + const RADIX: [f64; 4] = [1.0, 1.0 / 128.0, 1.0 / 32768.0, 1.0 / 8_388_608.0]; + let mantissa = f64::from((d & 0xffff_ff00) as i32 >> 8); + let radix = RADIX.get(((d >> 4) & 3) as usize).copied().unwrap_or(1.0); + let mut v = mantissa * radix; + let unit = units.get((d & 0xf) as usize).copied().unwrap_or("?"); + if units.len() == 2 { + v *= 100.0; + } + let v = (v * 10_000.0).round() / 10_000.0; + format!("{v}{unit}") +} + +/// One attribute of an element. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Attribute { + #[serde(skip_serializing_if = "Option::is_none")] + pub namespace: Option, + pub name: String, + /// The framework/app resource id of the attribute name, when the resource map gives one. + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_id: Option, + /// Formatted value. + pub value: String, + pub value_type: &'static str, + #[serde(skip)] + pub raw: ResValue, +} + +/// One XML node event. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Node { + Start { depth: usize, name: String, namespace: Option, line: u32, attributes: Vec }, + End { depth: usize, name: String }, + Text { depth: usize, text: String }, + Namespace { prefix: String, uri: String }, +} + +/// A decoded binary XML document. +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +pub struct Document { + pub nodes: Vec, + #[serde(skip)] + pub pool: StringPool, + pub resource_ids: usize, + pub namespaces: Vec<(String, String)>, + pub truncated: bool, + pub warnings: Vec, +} + +/// Names of common framework attributes by resource id, used when a name string was stripped. +pub fn framework_attr(id: u32) -> Option<&'static str> { + Some(match id { + 0x0101_0000 => "theme", + 0x0101_0001 => "label", + 0x0101_0002 => "icon", + 0x0101_0003 => "name", + 0x0101_0006 => "permission", + 0x0101_0007 => "readPermission", + 0x0101_0008 => "writePermission", + 0x0101_0009 => "protectionLevel", + 0x0101_000e => "enabled", + 0x0101_000f => "debuggable", + 0x0101_0010 => "exported", + 0x0101_0018 => "authorities", + 0x0101_020c => "minSdkVersion", + 0x0101_021b => "versionCode", + 0x0101_021c => "versionName", + 0x0101_0270 => "targetSdkVersion", + 0x0101_0271 => "maxSdkVersion", + 0x0101_0280 => "allowBackup", + _ => return None, + }) +} + +/// Decode a binary XML file. +pub fn parse(data: &[u8]) -> Result { + parse_with_limits(data, MAX_NODES, MAX_DEPTH) +} + +fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result { + let r = Reader::new(data); + let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("binary XML header".into()))?; + if t != RES_XML { + return Err(Error::Malformed(format!("not binary XML (chunk type {t:#x})"))); + } + let data = r.slice(0, size).ok_or_else(|| Error::Truncated("binary XML document".into()))?; + let r = Reader::new(data); + let mut doc = Document::default(); + let mut res_map: Vec = Vec::new(); + let mut pos = h; + let mut depth = 0usize; + let mut ns_stack: Vec<(String, String)> = Vec::new(); + while pos < size { + let Some((ct, ch, cs)) = chunk(&r, pos) else { + doc.truncated = true; + doc.warnings.push(format!("unreadable chunk at offset {pos}")); + break; + }; + let extension = match ct { + XML_START_NS | XML_END_NS | XML_END_ELEMENT => 8, + XML_START_ELEMENT => 20, + XML_CDATA => 12, + _ => 0, + }; + if extension != 0 && (ch < 16 || cs - ch < extension) { + doc.truncated = true; + doc.warnings.push(format!("incomplete XML node at offset {pos}")); + break; + } + if matches!(ct, XML_START_NS | XML_START_ELEMENT | XML_END_ELEMENT | XML_CDATA) && doc.nodes.len() >= max_nodes { + doc.truncated = true; + doc.warnings.push("XML node limit reached; the remaining events were skipped".into()); + break; + } + match ct { + RES_STRING_POOL => match StringPool::parse(data, pos) { + Ok(p) => { + if p.strings.len() < p.declared { + doc.truncated = true; + doc.warnings.push(format!("string pool was capped at {} of {} strings", p.strings.len(), p.declared)); + } + doc.pool = p; + } + Err(e) => doc.warnings.push(format!("string pool: {e}")), + }, + XML_RESOURCE_MAP => { + let n = (cs - ch) / 4; + res_map = (0..n.min(MAX_STRINGS)).filter_map(|i| r.u32_le(pos + ch + i * 4)).collect(); + doc.resource_ids = res_map.len(); + } + XML_START_NS | XML_END_NS => { + let prefix = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + let uri = r.u32_le(pos + ch + 4).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + if ct == XML_START_NS { + if doc.namespaces.len() < 256 { + doc.namespaces.push((prefix.clone(), uri.clone())); + } + if ns_stack.len() < MAX_DEPTH { + ns_stack.push((prefix.clone(), uri.clone())); + } + doc.nodes.push(Node::Namespace { prefix, uri }); + } else { + ns_stack.pop(); + } + } + XML_START_ELEMENT => { + if depth >= max_depth { + doc.truncated = true; + doc.warnings.push("XML nesting limit reached; the remaining events were skipped".into()); + break; + } + let line = r.u32_le(pos + 8).unwrap_or(0); + let ext = pos + ch; + let ns = r.u32_le(ext).and_then(|i| doc.pool.get(i)).map(str::to_string); + let name = r.u32_le(ext + 4).and_then(|i| doc.pool.get(i)).unwrap_or("?").to_string(); + let a_start = usize::from(r.u16_le(ext + 8).unwrap_or(20)); + let a_size = usize::from(r.u16_le(ext + 10).unwrap_or(20)); + let a_count = usize::from(r.u16_le(ext + 12).unwrap_or(0)); + if a_count != 0 && (a_start < 20 || a_size < 20) { + doc.truncated = true; + doc.warnings.push(format!("element {name}: invalid attribute table layout")); + break; + } + let mut attributes = Vec::new(); + for i in 0..a_count { + let relative = a_start + i * a_size; + if relative.checked_add(a_size).is_none_or(|end| end > cs - ch) { + doc.truncated = true; + doc.warnings.push(format!("element {name}: attribute {i} runs past its chunk")); + break; + } + let a = ext + relative; + let value_size = usize::from(r.u16_le(a + 12).unwrap_or(0)); + if value_size < 8 || value_size > a_size - 12 { + doc.truncated = true; + doc.warnings.push(format!("element {name}: invalid typed value size in attribute {i}")); + break; + } + let ans = r.u32_le(a).and_then(|i| doc.pool.get(i)).map(str::to_string); + let name_idx = r.u32_le(a + 4).unwrap_or(u32::MAX); + let raw_str = r.u32_le(a + 8).unwrap_or(u32::MAX); + let vt = r.u8(a + 15).unwrap_or(0); + let vd = r.u32_le(a + 16).unwrap_or(0); + let rid = res_map.get(name_idx as usize).copied(); + let mut aname = doc.pool.get(name_idx).unwrap_or("").to_string(); + if aname.is_empty() { + aname = rid.and_then(framework_attr).map(str::to_string).unwrap_or_else(|| format!("attr_{name_idx}")); + } + let raw = ResValue { data_type: vt, data: vd }; + let value = if vt == 0x03 || (raw_str != u32::MAX && vt == 0) { + doc.pool.get(if vt == 0x03 { vd } else { raw_str }).unwrap_or("").to_string() + } else { + raw.format(&doc.pool) + }; + attributes.push(Attribute { + namespace: ans, + name: aname, + resource_id: rid.map(|x| format!("{x:#010x}")), + value, + value_type: raw.type_name(), + raw, + }); + } + doc.nodes.push(Node::Start { depth, name, namespace: ns, line, attributes }); + depth += 1; + } + XML_END_ELEMENT => { + depth = depth.saturating_sub(1); + let name = r.u32_le(pos + ch + 4).and_then(|i| doc.pool.get(i)).unwrap_or("?").to_string(); + doc.nodes.push(Node::End { depth, name }); + } + XML_CDATA => { + let text = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + doc.nodes.push(Node::Text { depth, text }); + } + _ => {} + } + pos = match pos.checked_add(cs) { + Some(p) => p, + None => break, + }; + } + Ok(doc) +} + +fn esc(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +impl Document { + fn prefix_for(&self, uri: &str) -> Option<&str> { + self.namespaces.iter().find(|(_, u)| u == uri).map(|(p, _)| p.as_str()) + } + + /// An XML text rendition (for reading, not byte-exact source). + pub fn to_xml(&self, max_bytes: usize) -> String { + let mut out = String::from("\n"); + let mut first = true; + for n in &self.nodes { + if out.len() > max_bytes { + out.push_str("\n"); + break; + } + match n { + Node::Start { depth, name, attributes, .. } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push('<'); + out.push_str(name); + if first { + for (p, u) in &self.namespaces { + out.push_str(&format!(" xmlns:{p}=\"{}\"", esc(u))); + } + first = false; + } + for a in attributes { + let p = a.namespace.as_deref().and_then(|u| self.prefix_for(u)).map(|p| format!("{p}:")).unwrap_or_default(); + out.push_str(&format!(" {p}{}=\"{}\"", a.name, esc(&a.value))); + } + out.push_str(">\n"); + } + Node::End { depth, name } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push_str(&format!("\n")); + } + Node::Text { depth, text } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push_str(&esc(text)); + out.push('\n'); + } + Node::Namespace { .. } => {} + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fixtures as fx; + + fn pool_with_offsets(offsets: &[u32], string_data: &[u8]) -> Vec { + let start = 28 + offsets.len() * 4; + let mut data = vec![0; start]; + data[..2].copy_from_slice(&RES_STRING_POOL.to_le_bytes()); + data[2..4].copy_from_slice(&28u16.to_le_bytes()); + data[8..12].copy_from_slice(&(offsets.len() as u32).to_le_bytes()); + data[16..20].copy_from_slice(&0x100u32.to_le_bytes()); + data[20..24].copy_from_slice(&(start as u32).to_le_bytes()); + for (i, offset) in offsets.iter().enumerate() { + let at = 28 + i * 4; + data[at..at + 4].copy_from_slice(&offset.to_le_bytes()); + } + data.extend_from_slice(string_data); + data.resize(data.len().next_multiple_of(4), b'x'); + let size = data.len() as u32; + data[4..8].copy_from_slice(&size.to_le_bytes()); + data + } + + fn append_legacy_ascii(data: &mut Vec, len: usize) -> u32 { + let offset = data.len() as u32; + let encoded = [0x80 | ((len >> 8) & 0x7f) as u8, (len & 0xff) as u8]; + data.extend_from_slice(&encoded); + data.extend_from_slice(&encoded); + data.resize(data.len() + len, b'x'); + data.push(0); + offset + } + + fn shared_ascii_pool(utf8: bool, count: usize) -> Vec { + let len = 16_384usize; + let mut strings = Vec::new(); + if utf8 { + append_legacy_ascii(&mut strings, len); + } else { + strings.extend_from_slice(&(len as u16).to_le_bytes()); + for _ in 0..len { + strings.extend_from_slice(b"x\0"); + } + strings.extend_from_slice(&[0, 0]); + } + let mut data = pool_with_offsets(&vec![0; count], &strings); + if !utf8 { + data[16..20].fill(0); + } + data + } + + #[test] + fn shared_offsets_spend_a_pool_byte_budget() { + for utf8 in [true, false] { + let mut data = shared_ascii_pool(utf8, 8192); + for appended in [false, true] { + if appended { + // Unrelated bytes after the chunk cannot buy more retained copies. + data.resize(24 << 20, 0); + } + let pool = StringPool::parse(&data, 0).unwrap(); + assert_eq!(pool.declared, 8192); + assert_eq!(pool.strings.len(), 4096); + assert_eq!(pool.strings.iter().map(String::len).sum::(), 64 << 20); + assert_eq!(pool.get(4095).map(str::len), Some(16_384)); + assert_eq!(pool.get(4096), None); + } + let data = shared_ascii_pool(utf8, 2); + let pool = StringPool::parse(&data, 0).unwrap(); + assert_eq!(pool.strings.len(), 2); + assert_eq!(pool.get(0), pool.get(1)); + } + } + + fn pool_container(kind: u16, header: usize, children: &[u8]) -> Vec { + let mut data = vec![0; header]; + data[0..2].copy_from_slice(&kind.to_le_bytes()); + data[2..4].copy_from_slice(&(header as u16).to_le_bytes()); + data.extend_from_slice(children); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + data + } + + #[test] + fn xml_and_resource_tables_disclose_partial_string_pools() { + let pool = shared_ascii_pool(true, 8192); + { + let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap(); + assert!(doc.truncated); + assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("4096 of 8192"))); + assert_eq!(doc.pool.strings.len(), 4096); + } + let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated); + assert_eq!(table.global_strings, 8192); + assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("4096 of 8192"))); + for (field, label) in [(268, "type"), (276, "key")] { + let mut package = pool_container(0x0200, 288, &pool); + package[8..12].copy_from_slice(&0x7fu32.to_le_bytes()); + package[field..field + 4].copy_from_slice(&288u32.to_le_bytes()); + let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated, "{label}"); + assert!(table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("4096 of 8192"))); + assert_eq!(table.packages.len(), 1); + } + } + + #[test] + fn repeated_offsets_share_the_utf8_recovery_budget() { + let mut strings = Vec::new(); + let long = append_legacy_ascii(&mut strings, 0x8000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&[long, long, long, short], &strings); + let mut left = 2; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 0); + assert_eq!(parsed.declared, 4); + assert_eq!(parsed.strings.len(), 4); + assert_eq!(parsed.get(0).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(1), parsed.get(0)); + assert_eq!(parsed.get(2), Some("")); + assert_eq!(parsed.get(3), Some("ok")); + } + + #[test] + fn distinct_offsets_share_the_utf8_recovery_budget() { + let mut strings = Vec::new(); + let mut offsets: Vec = (0..3).map(|_| append_legacy_ascii(&mut strings, 0x8000)).collect(); + offsets.push(strings.len() as u32); + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&offsets, &strings); + let mut left = 2; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 0); + assert_eq!(parsed.get(0).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(1).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(2), Some("")); + assert_eq!(parsed.get(3), Some("ok")); + } + + #[test] + fn utf8_recovery_stops_before_a_probe_without_credit() { + let mut strings = Vec::new(); + let long = append_legacy_ascii(&mut strings, 0x10000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&[long, short], &strings); + for (allowance, length, remaining) in [(0, 0, 0), (1, 0, 0), (2, 0x10000, 0), (3, 0x10000, 1)] { + let mut left = allowance; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, remaining); + assert_eq!(parsed.get(0).map(str::len), Some(length)); + assert_eq!(parsed.get(1), Some("ok")); + } + } + + #[test] + fn short_strings_and_out_of_bounds_candidates_spend_no_recovery_probes() { + let data = pool_with_offsets(&[0, 5], b"\x80\0\x80\0x\x02\x02ok\0"); + let mut left = 7; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 7); + assert_eq!(parsed.get(0), Some("")); + assert_eq!(parsed.get(1), Some("ok")); + } + + #[test] + fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + let mut strings = vec![b'x'; 2 * 0x8000 + 16]; + strings[..4].copy_from_slice(&[0x80, 0, 0x80, 0]); + let long = append_legacy_ascii(&mut strings, 0x8000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + // Offset zero has three in-bounds extra candidates, all nonzero. + let repeated = MAX_RECOVERY_PROBES / 3 + 1; + let mut offsets = vec![0; repeated]; + offsets.extend([long, short]); + let data = pool_with_offsets(&offsets, &strings); + let parsed = StringPool::parse(&data, 0).unwrap(); + assert_eq!(parsed.declared, repeated + 2); + assert_eq!(parsed.strings.len(), repeated + 2); + assert!(parsed.strings[..repeated].iter().all(String::is_empty)); + assert_eq!(parsed.get(repeated as u32), Some("")); + assert_eq!(parsed.get((repeated + 1) as u32), Some("ok")); + } + + fn chunk_at(data: &[u8], kind: u16) -> usize { + let r = Reader::new(data); + let mut pos = 8; + loop { + let (t, _, n) = chunk(&r, pos).unwrap(); + if t == kind { + return pos; + } + pos += n; + } + } + + #[test] + fn namespace_extensions_follow_the_declared_header() { + let mut data = fx::manifest_axml(); + let pos = chunk_at(&data, XML_START_NS); + data.splice(pos + 16..pos + 16, [0xff; 4]); + data[pos + 2..pos + 4].copy_from_slice(&20u16.to_le_bytes()); + data[pos + 4..pos + 8].copy_from_slice(&28u32.to_le_bytes()); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + let doc = parse(&data).unwrap(); + assert!(doc.warnings.is_empty()); + assert_eq!(doc.namespaces[0], ("android".into(), ANDROID_NS.into())); + } + + #[test] + fn extended_attribute_strides_keep_each_manifest_value() { + let mut data = fx::manifest_axml(); + let pos = chunk_at(&data, XML_START_ELEMENT); + let ext = pos + 16; + // The fixture writes three 20-byte attributes with 8-byte typed values. + for index in (1..=3).rev() { + let end = ext + 20 + index * 20; + data.splice(end..end, [0xff; 4]); + } + data[ext + 10..ext + 12].copy_from_slice(&24u16.to_le_bytes()); + data[pos + 4..pos + 8].copy_from_slice(&(36 + 3 * 24u32).to_le_bytes()); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + + let doc = parse(&data).unwrap(); + assert!(!doc.truncated); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + let Node::Start { attributes, .. } = &doc.nodes[1] else { + panic!("expected the manifest start after the namespace"); + }; + let pairs: Vec<_> = attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect(); + assert_eq!(pairs, [("package", fx::PACKAGE), ("versionCode", "42"), ("versionName", "1.2.3")]); + } + + #[test] + fn dropping_a_close_event_marks_the_document_partial() { + let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::End("root")]); + let complete = parse_with_limits(&bytes, 3, 1).unwrap(); + assert!(!complete.truncated); + assert!(matches!(complete.nodes.last(), Some(Node::End { depth: 0, .. }))); + + let partial = parse_with_limits(&bytes, 2, 1).unwrap(); + assert!(partial.truncated); + assert_eq!(partial.nodes, complete.nodes[..2]); + } + + #[test] + fn nesting_limit_keeps_an_exact_prefix_instead_of_saturating_depth() { + let bytes = + fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::Start("child", vec![]), fx::AxNode::End("child"), fx::AxNode::End("root")]); + let complete = parse_with_limits(&bytes, 5, 2).unwrap(); + assert!(!complete.truncated); + assert!(matches!(complete.nodes[3], Node::End { depth: 1, .. })); + assert!(matches!(complete.nodes[4], Node::End { depth: 0, .. })); + + let partial = parse_with_limits(&bytes, 5, 1).unwrap(); + assert!(partial.truncated); + assert_eq!(partial.nodes, complete.nodes[..2]); + } + + #[test] + fn values_format() { + let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1 }; + assert_eq!(ResValue { data_type: 0x05, data: (16 << 8) | 1 }.format(&p), "16dp"); + assert_eq!(ResValue { data_type: 0x12, data: 0xffff_ffff }.format(&p), "true"); + assert_eq!(ResValue { data_type: 0x1c, data: 0xff00_ff00 }.format(&p), "#ff00ff00"); + assert_eq!(ResValue { data_type: 0x10, data: (-5i32) as u32 }.format(&p), "-5"); + assert_eq!(ResValue { data_type: 0x03, data: 0 }.format(&p), "x"); + assert_eq!(ResValue { data_type: 0x04, data: 1.5f32.to_bits() }.format(&p), "1.5"); + } +} diff --git a/crates/android-res/src/bytes.rs b/crates/android-res/src/bytes.rs new file mode 100644 index 0000000000..bf2e751d66 --- /dev/null +++ b/crates/android-res/src/bytes.rs @@ -0,0 +1,37 @@ +//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub fn len(&self) -> usize { + self.data.len() + } + + pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } +} diff --git a/crates/android-res/src/fixtures.rs b/crates/android-res/src/fixtures.rs new file mode 100644 index 0000000000..54235d3b0c --- /dev/null +++ b/crates/android-res/src/fixtures.rs @@ -0,0 +1,376 @@ +//! Test-only XML and resource table fixtures ported from Craft Anything. + +pub const PACKAGE: &str = "com.example.notes"; + +fn u16le(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn u32le(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn align4(v: &mut Vec) { + while !v.len().is_multiple_of(4) { + v.push(0); + } +} + +/// A string pool chunk (UTF-16, or UTF-8 when `utf8`). +pub fn string_pool(strings: &[&str], utf8: bool) -> Vec { + let mut data = Vec::new(); + let mut offs = Vec::new(); + for s in strings { + offs.push(data.len() as u32); + if utf8 { + let n16 = s.encode_utf16().count(); + data.push(n16 as u8); + data.push(s.len() as u8); + data.extend_from_slice(s.as_bytes()); + data.push(0); + } else { + let units: Vec = s.encode_utf16().collect(); + u16le(&mut data, units.len() as u16); + for u in units { + u16le(&mut data, u); + } + u16le(&mut data, 0); + } + } + align4(&mut data); + let strings_start = 28 + 4 * strings.len(); + let mut v = Vec::new(); + u16le(&mut v, 0x0001); + u16le(&mut v, 28); + u32le(&mut v, (strings_start + data.len()) as u32); + u32le(&mut v, strings.len() as u32); + u32le(&mut v, 0); + u32le(&mut v, if utf8 { 1 << 8 } else { 0 }); + u32le(&mut v, strings_start as u32); + u32le(&mut v, 0); + for o in offs { + u32le(&mut v, o); + } + v.extend_from_slice(&data); + v +} + +/// An attribute value in a binary XML element. +#[derive(Debug, Clone, Copy)] +pub enum AxVal<'a> { + Str(&'a str), + Bool(bool), + Int(i32), + Hex(u32), + Ref(u32), +} + +#[derive(Debug, Clone)] +pub struct AxAttr<'a> { + pub name: &'a str, + /// Android framework attribute (namespaced, with its resource id). + pub res_id: Option, + pub val: AxVal<'a>, +} + +#[derive(Debug, Clone)] +pub enum AxNode<'a> { + Start(&'a str, Vec>), + End(&'a str), +} + +const NS: &str = "http://schemas.android.com/apk/res/android"; + +/// Shorthand for an `android:` attribute. +pub fn a<'a>(name: &'a str, res_id: u32, val: AxVal<'a>) -> AxAttr<'a> { + AxAttr { name, res_id: Some(res_id), val } +} + +/// Write a binary XML document with the android namespace declared on the root. +pub fn axml(nodes: &[AxNode<'_>]) -> Vec { + let mut strings: Vec = Vec::new(); + let mut ids: Vec = Vec::new(); + for n in nodes { + if let AxNode::Start(_, attrs) = n { + for at in attrs { + if let Some(id) = at.res_id + && !strings.iter().any(|s| s == at.name) + { + strings.push(at.name.to_string()); + ids.push(id); + } + } + } + } + let intern = |s: &str, strings: &mut Vec| -> u32 { + if let Some(i) = strings.iter().position(|x| x == s) { + return i as u32; + } + strings.push(s.to_string()); + (strings.len() - 1) as u32 + }; + let prefix = intern("android", &mut strings); + let uri = intern(NS, &mut strings); + let mut body = Vec::new(); + let ns_chunk = |t: u16| { + let mut c = Vec::new(); + u16le(&mut c, t); + u16le(&mut c, 16); + u32le(&mut c, 24); + u32le(&mut c, 1); + u32le(&mut c, u32::MAX); + u32le(&mut c, prefix); + u32le(&mut c, uri); + c + }; + body.extend(ns_chunk(0x0100)); + for (line, n) in nodes.iter().enumerate() { + match n { + AxNode::Start(name, attrs) => { + let nidx = intern(name, &mut strings); + let mut c = Vec::new(); + u16le(&mut c, 0x0102); + u16le(&mut c, 16); + u32le(&mut c, (36 + 20 * attrs.len()) as u32); + u32le(&mut c, line as u32 + 2); + u32le(&mut c, u32::MAX); + u32le(&mut c, u32::MAX); + u32le(&mut c, nidx); + u16le(&mut c, 20); + u16le(&mut c, 20); + u16le(&mut c, attrs.len() as u16); + u16le(&mut c, 0); + u16le(&mut c, 0); + u16le(&mut c, 0); + for at in attrs { + let an = intern(at.name, &mut strings); + let (raw, ty, data) = match at.val { + AxVal::Str(s) => { + let i = intern(s, &mut strings); + (i, 0x03u8, i) + } + AxVal::Bool(b) => (u32::MAX, 0x12, if b { u32::MAX } else { 0 }), + AxVal::Int(i) => (u32::MAX, 0x10, i as u32), + AxVal::Hex(h) => (u32::MAX, 0x11, h), + AxVal::Ref(r) => (u32::MAX, 0x01, r), + }; + u32le(&mut c, if at.res_id.is_some() { uri } else { u32::MAX }); + u32le(&mut c, an); + u32le(&mut c, raw); + u16le(&mut c, 8); + c.push(0); + c.push(ty); + u32le(&mut c, data); + } + body.extend(c); + } + AxNode::End(name) => { + let nidx = intern(name, &mut strings); + let mut c = Vec::new(); + u16le(&mut c, 0x0103); + u16le(&mut c, 16); + u32le(&mut c, 24); + u32le(&mut c, line as u32 + 2); + u32le(&mut c, u32::MAX); + u32le(&mut c, u32::MAX); + u32le(&mut c, nidx); + body.extend(c); + } + } + } + body.extend(ns_chunk(0x0101)); + let refs: Vec<&str> = strings.iter().map(String::as_str).collect(); + let pool = string_pool(&refs, false); + let mut map = Vec::new(); + u16le(&mut map, 0x0180); + u16le(&mut map, 8); + u32le(&mut map, (8 + 4 * ids.len()) as u32); + for id in &ids { + u32le(&mut map, *id); + } + let mut out = Vec::new(); + u16le(&mut out, 0x0003); + u16le(&mut out, 8); + u32le(&mut out, (8 + pool.len() + map.len() + body.len()) as u32); + out.extend(pool); + out.extend(map); + out.extend(body); + out +} + +/// The Notes app's `AndroidManifest.xml`. +pub fn manifest_axml() -> Vec { + use AxNode::{End, Start}; + use AxVal::*; + let name = |v| a("name", 0x0101_0003, Str(v)); + axml(&[ + Start( + "manifest", + vec![ + AxAttr { name: "package", res_id: None, val: Str(PACKAGE) }, + a("versionCode", 0x0101_021b, Int(42)), + a("versionName", 0x0101_021c, Str("1.2.3")), + ], + ), + Start("uses-sdk", vec![a("minSdkVersion", 0x0101_020c, Int(24)), a("targetSdkVersion", 0x0101_0270, Int(34))]), + End("uses-sdk"), + Start("uses-permission", vec![name("android.permission.INTERNET")]), + End("uses-permission"), + Start("uses-permission", vec![name("android.permission.CAMERA")]), + End("uses-permission"), + Start("permission", vec![name("com.example.notes.permission.SYNC"), a("protectionLevel", 0x0101_0009, Hex(2))]), + End("permission"), + Start( + "application", + vec![ + name(".NotesApp"), + a("label", 0x0101_0001, Ref(0x7f01_0000)), + a("debuggable", 0x0101_000f, Bool(true)), + a("allowBackup", 0x0101_0280, Bool(false)), + ], + ), + Start("activity", vec![name(".MainActivity"), a("exported", 0x0101_0010, Bool(true))]), + Start("intent-filter", vec![]), + Start("action", vec![name("android.intent.action.MAIN")]), + End("action"), + Start("category", vec![name("android.intent.category.LAUNCHER")]), + End("category"), + Start("data", vec![a("scheme", 0x0101_0027, Str("notes")), a("host", 0x0101_0028, Str("open"))]), + End("data"), + End("intent-filter"), + End("activity"), + Start("service", vec![name(".SyncService"), a("exported", 0x0101_0010, Bool(false))]), + End("service"), + Start( + "provider", + vec![ + name("androidx.core.content.FileProvider"), + a("authorities", 0x0101_0018, Str("com.example.notes.files")), + a("exported", 0x0101_0010, Bool(false)), + ], + ), + End("provider"), + End("application"), + End("manifest"), + ]) +} + +fn config(lang: &[u8; 2], density: u16, ui_mode: u8, sdk: u16) -> Vec { + let mut c = vec![0u8; 64]; + c[0] = 64; + if lang != b"\0\0" { + c[8..10].copy_from_slice(lang); + } + c[14..16].copy_from_slice(&density.to_le_bytes()); + c[24..26].copy_from_slice(&sdk.to_le_bytes()); + c[29] = ui_mode; + c +} + +fn type_spec(id: u8, entries: u32) -> Vec { + let mut c = Vec::new(); + u16le(&mut c, 0x0202); + u16le(&mut c, 16); + u32le(&mut c, 16 + 4 * entries); + c.push(id); + c.push(0); + u16le(&mut c, 0); + u32le(&mut c, entries); + for _ in 0..entries { + u32le(&mut c, 0); + } + c +} + +/// A type chunk from already-encoded entries. +fn type_chunk(id: u8, cfg: &[u8], entries: &[Vec]) -> Vec { + let header = 20 + cfg.len(); + let start = header + 4 * entries.len(); + let mut offs = Vec::new(); + let mut body = Vec::new(); + for e in entries { + offs.push(body.len() as u32); + body.extend_from_slice(e); + } + let mut c = Vec::new(); + u16le(&mut c, 0x0201); + u16le(&mut c, header as u16); + u32le(&mut c, (start + body.len()) as u32); + c.push(id); + c.push(0); + u16le(&mut c, 0); + u32le(&mut c, entries.len() as u32); + u32le(&mut c, start as u32); + c.extend_from_slice(cfg); + for o in offs { + u32le(&mut c, o); + } + c.extend(body); + c +} + +fn simple_entry(key: u32, ty: u8, data: u32) -> Vec { + let mut e = Vec::new(); + u16le(&mut e, 8); + u16le(&mut e, 0); + u32le(&mut e, key); + u16le(&mut e, 8); + e.push(0); + e.push(ty); + u32le(&mut e, data); + e +} + +/// `resources.arsc`: `string/app_name` and `string/greeting` in the default locale and French, +/// and one `style/AppTheme` bag (night, xhdpi, v21) with a parent and a colour item. +pub fn resources_arsc() -> Vec { + let global = string_pool(&["Notes", "Hello", "Notes FR", "Bonjour"], true); + let types = string_pool(&["string", "style"], false); + let keys = string_pool(&["app_name", "greeting", "AppTheme"], false); + let mut bag = Vec::new(); + u16le(&mut bag, 16); + u16le(&mut bag, 1); + u32le(&mut bag, 2); + u32le(&mut bag, 0x0103_0005); + u32le(&mut bag, 1); + u32le(&mut bag, 0x7f03_0000); + u16le(&mut bag, 8); + bag.push(0); + bag.push(0x1c); + u32le(&mut bag, 0xff33_6699); + let mut chunks = Vec::new(); + chunks.extend(type_spec(1, 2)); + chunks.extend(type_chunk(1, &config(b"\0\0", 0, 0, 0), &[simple_entry(0, 3, 0), simple_entry(1, 3, 1)])); + chunks.extend(type_chunk(1, &config(b"fr", 0, 0, 0), &[simple_entry(0, 3, 2), simple_entry(1, 3, 3)])); + chunks.extend(type_spec(2, 1)); + chunks.extend(type_chunk(2, &config(b"\0\0", 320, 0x20, 21), &[bag])); + let header = 288usize; + let mut pkg = Vec::new(); + u16le(&mut pkg, 0x0200); + u16le(&mut pkg, header as u16); + u32le(&mut pkg, (header + types.len() + keys.len() + chunks.len()) as u32); + u32le(&mut pkg, 0x7f); + let mut name = [0u16; 128]; + for (i, u) in PACKAGE.encode_utf16().enumerate() { + name[i] = u; + } + for u in name { + u16le(&mut pkg, u); + } + u32le(&mut pkg, header as u32); + u32le(&mut pkg, 2); + u32le(&mut pkg, (header + types.len()) as u32); + u32le(&mut pkg, 3); + u32le(&mut pkg, 0); + pkg.extend(types); + pkg.extend(keys); + pkg.extend(chunks); + let mut out = Vec::new(); + u16le(&mut out, 0x0002); + u16le(&mut out, 12); + u32le(&mut out, (12 + global.len() + pkg.len()) as u32); + u32le(&mut out, 1); + out.extend(global); + out.extend(pkg); + out +} diff --git a/crates/android-res/src/lib.rs b/crates/android-res/src/lib.rs new file mode 100644 index 0000000000..656f6dbf13 --- /dev/null +++ b/crates/android-res/src/lib.rs @@ -0,0 +1,17 @@ +//! Bounded readers for compiled Android XML and resource tables. +pub mod arsc; +pub mod axml; +mod bytes; +#[cfg(test)] +mod fixtures; + +/// Failure to decode the Android wire format. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// A required record did not fit within the available bytes. + #[error("truncated: {0}")] + Truncated(String), + /// The available bytes do not form the required structure. + #[error("malformed: {0}")] + Malformed(String), +} diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml new file mode 100644 index 0000000000..ad602e383a --- /dev/null +++ b/crates/appkit/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "craft-appkit" +description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through +# `NSNotificationCenter` with a block. +[target.'cfg(target_os = "macos")'.dependencies] +block2 = "0.6.2" +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] } + +# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's +# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one +# workspace lint. +[lints.rust] +unsafe_code = "deny" +missing_docs = "warn" +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] } + +[lints.clippy] +cognitive_complexity = "deny" +too_many_arguments = "deny" +wildcard_imports = "deny" +dbg_macro = "warn" +todo = "warn" diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs new file mode 100644 index 0000000000..78dd786b15 --- /dev/null +++ b/crates/appkit/src/lib.rs @@ -0,0 +1,37 @@ +//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS +//! only; the crate is empty elsewhere. +//! +//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every +//! block says why it is sound. +#![warn(missing_docs)] +#![cfg(target_os = "macos")] +#![allow(unsafe_code)] + +use std::ptr::NonNull; +use std::sync::{Arc, Once}; + +use block2::RcBlock; +use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; +use objc2_foundation::{NSNotification, NSNotificationCenter}; + +/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` +/// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once +/// for the process; a later call replaces nothing and does nothing. +pub fn observe_menu_tracking(on_change: Arc) { + static OBSERVE: Once = Once::new(); + OBSERVE.call_once(|| { + // SAFETY: AppKit initializes these immutable notification-name constants before any code of the app runs. + let names = unsafe { [(NSMenuDidBeginTrackingNotification, true), (NSMenuDidEndTrackingNotification, false)] }; + let center = NSNotificationCenter::defaultCenter(); + for (name, tracking) in names { + let on_change = on_change.clone(); + let block = RcBlock::new(move |_: NonNull| on_change(tracking)); + // SAFETY: `name` is one of AppKit's notification names and the block takes the notification by pointer + // without reading it. The center copies the block and keeps the observer for the process's lifetime; + // nothing removes it, so the returned token is not needed. + unsafe { + center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block); + } + } + }); +} diff --git a/crates/atomic/Cargo.toml b/crates/atomic/Cargo.toml index c19c64359e..2b0b43a475 100644 --- a/crates/atomic/Cargo.toml +++ b/crates/atomic/Cargo.toml @@ -11,5 +11,8 @@ description = "Crash-safe atomic file writing and replacement for the Craft suit [lints] workspace = true +# Plain fsync where F_FULLFSYNC is refused, and the replaced file's extended attributes (`fs`), with +# explicit size queries (`fgetxattr_query`). + [target.'cfg(target_vendor = "apple")'.dependencies] -rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } +rustix = { version = "1.1.6", default-features = false, features = ["std", "fs"] } diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index a87a8734d8..2fa589d099 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -34,6 +34,13 @@ //! Existing destinations always stage privately and retain their original Unix mode. Restoring //! an already-matching mode needs no chmod, including on fixed-mode network filesystems. //! +//! ### Attributes +//! A replaced file is the same document: its stage gets the file's extended attributes (macOS), +//! its hidden and system attributes (Windows, at creation) and its creation date (macOS, +//! Windows) before it is flushed. An extended attribute that cannot be read or copied whole, or +//! passes a bound, refuses the save and leaves the original as it was. Saving through a symbolic +//! link keeps the link and replaces the file it names, so the attributes kept are that file's. +//! //! ### Platform Characteristics //! - **Windows**: Antivirus scanners, search indexers, and backup utilities briefly hold files //! open with sharing violations. The rename is retried with exponential backoff (`RenameRetry`). @@ -59,6 +66,15 @@ pub trait AtomicFs { /// request mode `0600` for `Private` or `0666` for `PlatformDefault`; the OS applies its /// umask/default ACL. Other platforms keep their native creation behavior. fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result; + /// Create the stage like [`AtomicFs::create_new`], carrying over the attributes of the file it + /// replaces that can only be given at creation (Windows: hidden and system). `keep` is the + /// `metadata` of the regular file being replaced: a save through a symbolic link keeps the + /// link and replaces the file it names, so `keep` describes that file, never the link. `None` + /// for a new file. The default ignores `keep` and calls `create_new`. + fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result { + let _ = keep; + self.create_new(path, permissions) + } /// Flush a written file to durable storage. fn sync(&self, file: &File) -> io::Result<()>; /// Rename `from` over `to`, replacing it atomically. @@ -99,6 +115,21 @@ impl AtomicFs for RealFs { options.open(path) } + fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result { + // Given as the file is created, so a hidden file's stage is never visible: Windows has no + // safe call that sets them on an open file afterwards. + #[cfg(windows)] + if let Some(keep) = keep { + use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; + let mut options = OpenOptions::new(); + options.write(true).create_new(true).attributes(keep.file_attributes() & KEPT_ATTRIBUTES); + return options.open(path); + } + #[cfg(not(windows))] + let _ = keep; + self.create_new(path, permissions) + } + fn sync(&self, file: &File) -> io::Result<()> { sync_file(file) } @@ -315,12 +346,16 @@ fn replace_with_options( check_writable(&target).map_err(|e| read_only_error(e, path))?; } - let tmp = stage(fs, &dir, &name, path, existing.as_ref(), new_permissions, fill)?; + let tmp = stage(fs, &dir, &name, path, existing.as_ref().map(|m| (target.as_path(), m)), new_permissions, fill)?; if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) { let _ = fs.remove(&tmp); return Err(rename_error(e, path, existed)); } + #[cfg(windows)] + if let Some(replaced) = existing.as_ref().filter(|m| m.is_file()) { + restore_kept_attributes(&target, replaced); + } // The new bytes are in place; a failed directory fsync can't be undone and must not report // the save as failed, so it is best effort. @@ -369,31 +404,35 @@ fn adopt_group(fs: &dyn AtomicFs, file: &File, stage_gid: u32, replaced_gid: u32 } /// Create a temporary file in `dir`, fill it with `fill`, give it the permissions and group of -/// the file it replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when +/// the file it replaces (`replaced`: its resolved path and `metadata`, Unix), keep that file's +/// other attributes ([`keep_attributes`]) and flush it. Permission restoration is skipped when /// the mode already matches after `fill`; the group bits are dropped when the file cannot be put /// in the replaced file's group, so they never open the file to a group that was not granted -/// them. A leftover file with the same name is skipped. When any step fails, the temporary file -/// is removed. +/// them. A name something already has (a leftover file, a link, a folder) is skipped, never +/// opened, so nothing planted there receives or redirects the write. When any step fails, the +/// temporary file is removed. fn stage( fs: &dyn AtomicFs, dir: &Path, name: &str, path: &Path, - replaced: Option<&std::fs::Metadata>, + replaced: Option<(&Path, &std::fs::Metadata)>, new_permissions: NewFilePermissions, fill: impl FnOnce(&mut File) -> io::Result<()>, ) -> io::Result { let existed = replaced.is_some(); // Windows files carry only a read-only flag, and a read-only file can't be replaced. - let perms = replaced.filter(|_| cfg!(unix)).map(|m| m.permissions()); + let perms = replaced.filter(|_| cfg!(unix)).map(|(_, m)| m.permissions()); + // A folder or other non-file at the target has no attributes a stage could carry. + let keep = replaced.map(|(_, m)| m).filter(|m| m.is_file()); // New documents inherit the directory's policy directly: no probe or chmod is needed. // Existing destinations still stage privately, including when their final mode is shared. let creation = if existed { NewFilePermissions::Private } else { new_permissions }; for _ in 0..8 { let tmp = dir.join(temp_name(name)); - let mut file = match fs.create_new(&tmp, creation) { + let mut file = match fs.create_new_keeping(&tmp, creation, keep) { Ok(f) => f, - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) if name_taken(&e, &tmp) => continue, Err(e) => return Err(write_error(e, path, dir, existed)), }; let written = fill(&mut file) @@ -413,7 +452,7 @@ fn stage( } // The group bits belong to the replaced file's group, which a new // inode need not be in (setgid directory, another primary group). - if let Some(replaced) = replaced { + if let Some((_, replaced)) = replaced { let stage_gid = std::os::unix::fs::MetadataExt::gid(&file.metadata()?); let replaced_gid = std::os::unix::fs::MetadataExt::gid(replaced); let perms = adopt_group(fs, &file, stage_gid, replaced_gid, p)?; @@ -424,6 +463,7 @@ fn stage( }) .map_err(|e| permissions_error(e, path)) }) + .and_then(|()| keep_attributes(&file, replaced.filter(|(_, m)| m.is_file())).map_err(|e| attributes_error(e, path))) .and_then(|()| fs.sync(&file).map_err(|e| write_error(e, path, dir, existed))); #[allow( clippy::drop_non_drop, @@ -438,6 +478,142 @@ fn stage( Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display()))) } +/// Whether creating the stage failed because something already has its name: a file, a link +/// (even a dangling one) or a folder. Windows reports a folder there as access denied. +fn name_taken(e: &io::Error, tmp: &Path) -> bool { + match e.kind() { + io::ErrorKind::AlreadyExists => true, + io::ErrorKind::PermissionDenied => cfg!(windows) && std::fs::symlink_metadata(tmp).is_ok(), + _ => false, + } +} + +/// The Windows attributes a replaced file passes on to its stage: hidden and system, the two that +/// say who should see the file. A read-only file is never replaced, the archive bit is the +/// system's to set on a changed file, and the others describe how the volume stores it. +#[cfg(windows)] +const KEPT_ATTRIBUTES: u32 = 0x2 | 0x4; + +/// A server that hides dot-named files (Samba, NAS) marks the stage hidden and keeps the mark +/// through the rename: the saved file then gets the replaced file's attributes back. Only when the +/// kept bits differ, since restoring the whole attribute word on a local disk would clear the +/// archive bit backup tools read. Best effort: the new bytes are already in place. +#[cfg(windows)] +fn restore_kept_attributes(target: &Path, replaced: &std::fs::Metadata) { + use std::os::windows::fs::MetadataExt; + let saved = std::fs::symlink_metadata(target).map(|m| m.file_attributes() & KEPT_ATTRIBUTES); + if saved.is_ok_and(|bits| bits != replaced.file_attributes() & KEPT_ATTRIBUTES) { + let _ = std::fs::set_permissions(target, replaced.permissions()); + } +} + +/// Give the stage what the replaced regular file (`replaced`: its resolved path and `metadata`) +/// carries besides its bytes and mode, before the stage is flushed: on macOS its extended +/// attributes (`copy_xattrs`; an attribute that cannot be kept refuses the save), on macOS and +/// Windows its creation date (best effort: a volume that stores none keeps the stage's own). A +/// saved document is the same document. A new file has nothing to keep. +fn keep_attributes(stage: &File, replaced: Option<(&Path, &std::fs::Metadata)>) -> io::Result<()> { + let Some((target, meta)) = replaced else { return Ok(()) }; + #[cfg(target_os = "macos")] + copy_xattrs(target, stage)?; + #[cfg(not(target_os = "macos"))] + let _ = target; + #[cfg(any(target_os = "macos", windows))] + if let Ok(created) = meta.created() { + #[cfg(target_os = "macos")] + use std::os::macos::fs::FileTimesExt; + #[cfg(windows)] + use std::os::windows::fs::FileTimesExt; + let _ = stage.set_times(std::fs::FileTimes::new().set_created(created)); + } + #[cfg(not(any(target_os = "macos", windows)))] + let _ = (stage, meta); + Ok(()) +} + +/// The longest list of extended attribute names read from a replaced file. +#[cfg(target_os = "macos")] +const MAX_XATTR_NAMES_BYTES: usize = 64 * 1024; +/// The most extended attributes copied from a replaced file. +#[cfg(target_os = "macos")] +const MAX_XATTRS: usize = 1024; +/// The largest extended attribute value copied (a resource fork can be larger than ordinary ones). +#[cfg(target_os = "macos")] +const MAX_XATTR_VALUE_BYTES: usize = 16 * 1024 * 1024; +/// The most extended attribute bytes copied from one file in all. +#[cfg(target_os = "macos")] +const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024; + +/// Copy the extended attributes of the regular file at `target` (Finder tags, the "Open with" +/// binding, quarantine, resource forks) to the stage. The attributes are as untrusted as the +/// bytes, so the reads are bounded; one that cannot be read or written whole, or passes a bound, +/// refuses the save rather than dropping the user's metadata unnoticed. Only a volume without +/// extended attributes (`ENOTSUP`) is skipped. `com.apple.provenance` belongs to macOS, which +/// gives the new file its own. Compression bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`). +#[cfg(target_os = "macos")] +fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { + use rustix::fs::{Mode, OFlags, XattrFlags, fgetxattr, fgetxattr_query, flistxattr, fsetxattr, open}; + use rustix::io::Errno; + + // Never read through a link: the target is already resolved, and a link swapped in since + // names another file. NONBLOCK keeps a FIFO put at the name from hanging the open. + let source = match open(target, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, Mode::empty()) { + Ok(fd) => File::from(fd), + Err(Errno::NOENT | Errno::LOOP) => return Ok(()), + Err(e) => return Err(e.into()), + }; + if !source.metadata()?.is_file() { + return Ok(()); + } + let names_too_long = || io::Error::other("the extended attribute names exceed 64 KiB"); + let mut names = vec![0u8; MAX_XATTR_NAMES_BYTES]; + let len = match flistxattr(&source, names.as_mut_slice()) { + Ok(len) => len, + Err(Errno::NOTSUP) => return Ok(()), + Err(Errno::RANGE) => return Err(names_too_long()), + Err(e) => return Err(e.into()), + }; + let names = names.get(..len).ok_or_else(names_too_long)?; + let mut total = 0usize; + for (index, name) in names.split(|b| *b == 0).filter(|name| !name.is_empty()).enumerate() { + if index >= MAX_XATTRS { + return Err(io::Error::other("more than 1024 extended attributes")); + } + if name == b"com.apple.provenance" { + continue; + } + let name = std::ffi::CString::new(name).map_err(|_| io::Error::other("an extended attribute name is not valid"))?; + // An empty read buffer reads zero bytes in rustix, not the size: query it explicitly. + let size = fgetxattr_query(&source, &name)?; + if size > MAX_XATTR_VALUE_BYTES || size > MAX_XATTR_TOTAL_BYTES.saturating_sub(total) { + return Err(io::Error::other("the extended attributes exceed 16 MiB per value or 64 MiB in total")); + } + let value = read_xattr_value(size, |buffer| Ok(fgetxattr(&source, &name, buffer)?), || Ok(fgetxattr_query(&source, &name)?))?; + fsetxattr(stage, &name, &value, XattrFlags::empty())?; + total = total.saturating_add(value.len()); + } + Ok(()) +} + +/// Read one attribute value of `size` bytes (already within the bounds) with `read`, then ask +/// its size again with `query_size`. A read that does not fill `size`, or a size that changed, +/// is refused: a growing resource fork returns the prefix that fits instead of an error. +#[cfg(target_os = "macos")] +fn read_xattr_value( + size: usize, + read: impl FnOnce(&mut [u8]) -> io::Result, + query_size: impl FnOnce() -> io::Result, +) -> io::Result> { + let mut value = vec![0u8; size.max(1)]; + let len = read(value.as_mut_slice())?; + let after = query_size()?; + if len != size || after != size { + return Err(io::Error::other("an extended attribute changed size while saving")); + } + value.truncate(len); + Ok(value) +} + /// Exclusively creates and writes `path` with normal OS permissions, without replacing existing files. /// Use [`WriteOptions`] for private data. pub fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> { @@ -597,11 +773,18 @@ fn resolve_links(path: &Path) -> io::Result { Err(io::Error::new(io::ErrorKind::InvalidInput, format!("cannot save {}: too many levels of symbolic links", path.display()))) } -/// Generates a unique, hidden temporary file name beside `file`. +/// The most bytes of the target's name a temporary name keeps: with the leading `.`, the pid, the +/// counter and `.craft_tmp` the name stays within the 255-byte (Linux, macOS) and 255-unit +/// (Windows) limits however long the target's name is. +const TEMP_STEM_BYTES: usize = 128; + +/// Generates a unique, hidden temporary file name beside `file`: `.{file}.{pid}-{n}.craft_tmp`, +/// with `file` cut to its first 128 bytes between characters. pub fn temp_name(file: &str) -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); - let stem: String = file.chars().take(64).collect(); + let end = file.char_indices().map(|(i, c)| i + c.len_utf8()).take_while(|&end| end <= TEMP_STEM_BYTES).last().unwrap_or(0); + let stem = file.get(..end).unwrap_or_default(); #[cfg(not(target_arch = "wasm32"))] let pid = std::process::id(); #[cfg(target_arch = "wasm32")] @@ -633,6 +816,11 @@ fn permissions_error(e: io::Error, path: &Path) -> io::Error { io::Error::new(e.kind(), msg) } +fn attributes_error(e: io::Error, path: &Path) -> io::Error { + let msg = format!("cannot save {}: the original's extended attributes cannot be kept ({e}){}", path.display(), unchanged(true)); + io::Error::new(e.kind(), msg) +} + fn read_only_error(e: io::Error, path: &Path) -> io::Error { let kept = unchanged(true); let msg = match e.kind() { diff --git a/crates/atomic/src/tests.rs b/crates/atomic/src/tests.rs index 6edcc5430f..78cc37ae16 100644 --- a/crates/atomic/src/tests.rs +++ b/crates/atomic/src/tests.rs @@ -241,6 +241,341 @@ fn temp_name_format_is_valid() { assert!(name.ends_with(".craft_tmp")); } +/// What a [`Planting`] filesystem puts at a stage name just before the stage is created there. +#[derive(Clone, Copy, Debug)] +enum Obstacle { + File, + Folder, + /// A link to the file `outside` beside the stage. + #[cfg(unix)] + Link, + /// A link to `missing` beside the stage, which does not exist. + #[cfg(unix)] + DanglingLink, +} + +/// The real filesystem, except that the first `obstacles.len()` stage names get an obstacle +/// planted at them first, as someone racing the save would. +struct Planting { + obstacles: Vec, + planted: std::cell::RefCell>, +} + +impl Planting { + fn new(obstacles: Vec) -> Self { + Self { obstacles, planted: Default::default() } + } + + fn plant(&self, at: &Path) -> io::Result<()> { + let next = self.planted.borrow().len(); + let Some(&obstacle) = self.obstacles.get(next) else { return Ok(()) }; + match obstacle { + Obstacle::File => std::fs::write(at, b"PLANTED")?, + Obstacle::Folder => std::fs::create_dir(at)?, + #[cfg(unix)] + Obstacle::Link => std::os::unix::fs::symlink(at.with_file_name("outside"), at)?, + #[cfg(unix)] + Obstacle::DanglingLink => std::os::unix::fs::symlink(at.with_file_name("missing"), at)?, + } + self.planted.borrow_mut().push(at.to_path_buf()); + Ok(()) + } +} + +impl AtomicFs for Planting { + fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result { + self.plant(path)?; + RealFs.create_new(path, permissions) + } + fn sync(&self, file: &File) -> io::Result<()> { + RealFs.sync(file) + } + fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.rename(from, to) + } + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.hard_link(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + RealFs.sync_dir(dir) + } + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { + RealFs.set_permissions(file, perms) + } + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + RealFs.set_group(file, gid) + } +} + +/// A stage name something already has (a file, a folder, a link, a dangling link) is skipped, +/// never opened: writing through it would put the user's document where the planter chose. With +/// every name taken the save fails and the original is kept. +#[test] +fn a_name_taken_at_the_stage_is_skipped_and_never_written_through() { + let d = TempDir::new("planted"); + let p = d.0.join("doc.craft"); + let outside = d.0.join("outside"); + std::fs::write(&p, ORIGINAL).unwrap(); + std::fs::write(&outside, b"OUTSIDE").unwrap(); + + #[cfg(unix)] + let obstacles = vec![Obstacle::File, Obstacle::Folder, Obstacle::Link, Obstacle::DanglingLink]; + #[cfg(not(unix))] + let obstacles = vec![Obstacle::File, Obstacle::Folder]; + let fs = Planting::new(obstacles.clone()); + atomic_write_custom(&fs, NO_RETRY, &p, b"new").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + let planted = fs.planted.into_inner(); + assert_eq!(planted.len(), obstacles.len(), "every obstacle was met"); + for (at, obstacle) in planted.iter().zip(&obstacles) { + let meta = std::fs::symlink_metadata(at).unwrap(); + match obstacle { + Obstacle::File => assert_eq!(std::fs::read(at).unwrap(), b"PLANTED", "the planted file is not written"), + Obstacle::Folder => assert!(meta.is_dir() && std::fs::read_dir(at).unwrap().next().is_none(), "the folder is left empty"), + #[cfg(unix)] + Obstacle::Link | Obstacle::DanglingLink => assert!(meta.file_type().is_symlink(), "the link is left as a link"), + } + } + assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE", "nothing was written through a link"); + assert!(!outside.with_file_name("missing").exists(), "a dangling link's file was not created"); + for at in &planted { + let _ = std::fs::remove_file(at).or_else(|_| std::fs::remove_dir(at)); + } + assert_no_temp(&d.0); + + // Every name taken: the save is refused and the original kept. + let fs = Planting::new(vec![Obstacle::File; 64]); + let e = atomic_write_custom(&fs, NO_RETRY, &p, b"newer").unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{e}"); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + for at in fs.planted.into_inner() { + assert_eq!(std::fs::read(&at).unwrap(), b"PLANTED"); + let _ = std::fs::remove_file(at); + } + assert_no_temp(&d.0); +} + +/// A name near the 255-byte limit, in four-byte characters, still stages: the temporary name +/// keeps at most 128 bytes of it, cut between characters, and only the target is left. +#[test] +fn a_long_name_stages_and_leaves_only_the_target() { + let d = TempDir::new("long-name"); + // 2 + 61 × 4 + 4 = 250 bytes, 67 characters: the first 64 characters alone are 247 bytes. + let name = format!("ab{}.pdf", "\u{1F600}".repeat(61)); + assert_eq!(name.len(), 250); + let p = d.0.join(&name); + atomic_write(&p, b"first").unwrap(); + atomic_write(&p, b"second").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"second"); + let left: Vec<_> = std::fs::read_dir(&d.0).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(left, [std::ffi::OsString::from(&name)], "only the target is left"); + + let staged = temp_name(&name); + assert!(staged.len() <= 255, "{} bytes", staged.len()); + assert!(staged.starts_with(&format!(".ab{}.", "\u{1F600}".repeat(31))), "128 bytes of the name, cut between characters: {staged}"); +} + +/// Reads the extended attribute `name` of `path`, following no further than the path itself. +#[cfg(target_os = "macos")] +fn xattr(path: &Path, name: &str) -> Option> { + let size = rustix::fs::getxattr_query(path, name).ok()?; + let mut value = vec![0u8; size.max(1)]; + let len = rustix::fs::getxattr(path, name, &mut value[..]).ok()?; + value.truncate(len); + Some(value) +} + +/// A save keeps the replaced file's extended attributes (Finder tags, the "Open with" binding, +/// quarantine, binary, empty and resource-fork values), save after save, including one another +/// process sets while the stage is written. Through a symbolic link the link stays and the file it +/// names keeps them. A link swapped in at the target while staging is never read through: its +/// file's attributes stay its own. (`com.apple.provenance` cannot be set by a test; a file that +/// has it saves only because the copy skips it, as macOS refuses writing it.) +#[cfg(target_os = "macos")] +#[test] +fn attributes_set_while_staging_are_kept() { + use rustix::fs::{XattrFlags, setxattr}; + let d = TempDir::new("xattrs"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + let attributes: &[(&str, &[u8])] = &[ + ("com.apple.metadata:_kMDItemUserTags", b"Craft\n6"), + ("com.apple.LaunchServices.OpenWith", b"bplist00\xd1\x01\x02Wversion\x10\x00"), + ("com.apple.quarantine", b"0081;5e0d1d05;Craft;"), + ("com.craft.test.binary", b"\0\xff\x80original\0"), + ("com.craft.test.empty", b""), + ("com.apple.ResourceFork", b"\0\xfffork"), + ]; + for (name, value) in attributes { + setxattr(&target, *name, value, XattrFlags::empty()).unwrap(); + } + // What the system stored (quarantine may be normalised): the saved file must hold the same. + let stored: Vec<_> = attributes.iter().map(|(name, _)| (*name, xattr(&target, name).unwrap())).collect(); + + for save in 0..2 { + atomic_write_with(&target, |f| { + // Another process tags the original while the new bytes are written. + setxattr(&target, "com.craft.test.late", format!("late {save}").as_bytes(), XattrFlags::empty())?; + f.write_all(b"new") + }) + .unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + for (name, value) in &stored { + assert_eq!(xattr(&target, name).as_ref(), Some(value), "save {save} keeps {name}"); + } + assert_eq!(xattr(&target, "com.craft.test.late"), Some(format!("late {save}").into_bytes()), "set while staging"); + assert_no_temp(&d.0); + } + + // Through a link: the link stays, the file it names is replaced and keeps its attributes. + let link = d.0.join("link.pdf"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + atomic_write(&link, b"through the link").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link"); + assert_eq!(std::fs::read(&target).unwrap(), b"through the link"); + for (name, value) in &stored { + assert_eq!(xattr(&target, name).as_ref(), Some(value), "the linked file keeps {name}"); + } + + // A link put at the target while staging names another file: nothing is read through it. + let outside = d.0.join("outside.pdf"); + std::fs::write(&outside, b"OUTSIDE").unwrap(); + setxattr(&outside, "com.craft.test.private", b"private", XattrFlags::empty()).unwrap(); + atomic_write_with(&target, |f| { + std::fs::remove_file(&target)?; + std::os::unix::fs::symlink(&outside, &target)?; + f.write_all(b"swapped") + }) + .unwrap(); + assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE"); + assert_eq!(xattr(&outside, "com.craft.test.private"), Some(b"private".to_vec())); + assert!(!std::fs::symlink_metadata(&target).unwrap().file_type().is_symlink()); + assert_eq!(xattr(&target, "com.craft.test.private"), None, "the swapped-in link's file lent nothing"); + assert_no_temp(&d.0); +} + +/// An attribute past the 16 MiB value bound refuses the save instead of dropping it: the target +/// keeps its bytes and its attribute, and no stage is left. +#[cfg(target_os = "macos")] +#[test] +fn oversized_attributes_refuse_the_save_and_keep_the_target() { + use rustix::fs::{XattrFlags, getxattr_query, setxattr}; + let d = TempDir::new("xattrs-bound"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + // Only a resource fork may be this large; the bytes exist only in this temporary file. + let fork = vec![42u8; 16 * 1024 * 1024 + 1]; + setxattr(&target, "com.apple.ResourceFork", &fork, XattrFlags::empty()).unwrap(); + let e = atomic_write(&target, b"new").unwrap_err(); + assert!(e.to_string().contains("extended attributes"), "{e}"); + assert_eq!(std::fs::read(&target).unwrap(), ORIGINAL); + assert_eq!(getxattr_query(&target, "com.apple.ResourceFork").unwrap(), fork.len()); + assert_no_temp(&d.0); +} + +/// A value read must fill the size first queried and keep it in a second query: a growing +/// resource fork returns the prefix that fits instead of an error. Complete values, empty and +/// binary, are kept as read. +#[cfg(target_os = "macos")] +#[test] +fn an_attribute_read_must_fill_its_size_and_keep_it() { + for bytes in [&b""[..], &b"\0\xffB"[..]] { + let value = read_xattr_value( + bytes.len(), + |buffer| { + buffer[..bytes.len()].copy_from_slice(bytes); + Ok(bytes.len()) + }, + || Ok(bytes.len()), + ) + .unwrap(); + assert_eq!(value, bytes); + } + // A short read, a size that grew after the read, a prefix of a grown value. + for (before, read_len, after) in [(3, 2, 3), (3, 3, 4), (0, 1, 1), (3, 2, 2)] { + let e = read_xattr_value(before, |_| Ok(read_len), || Ok(after)).unwrap_err(); + assert!(e.to_string().contains("changed size"), "{before} {read_len} {after}: {e}"); + } + let e = read_xattr_value(3, |_| Ok(3), || Err(io::Error::new(io::ErrorKind::PermissionDenied, "recheck refused"))).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::PermissionDenied); +} + +/// A saved document is the same document: it keeps its creation date. A new file gets its own. +#[cfg(any(target_os = "macos", windows))] +#[test] +fn a_replaced_files_creation_date_is_kept() { + #[cfg(target_os = "macos")] + use std::os::macos::fs::FileTimesExt; + #[cfg(windows)] + use std::os::windows::fs::FileTimesExt; + let d = TempDir::new("created"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + // 2020-01-02 03:04:05 UTC. + let then = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_577_934_245); + let file = OpenOptions::new().write(true).open(&target).unwrap(); + file.set_times(std::fs::FileTimes::new().set_created(then)).unwrap(); + drop(file); + assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the fixture's date is set"); + atomic_write(&target, b"new").unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the saved file keeps its creation date"); + let fresh = d.0.join("new.pdf"); + atomic_write(&fresh, b"new").unwrap(); + assert!(std::fs::metadata(&fresh).unwrap().created().unwrap() > then, "a new file has a date of its own"); +} + +/// A hidden or system file stays hidden or system, and its stage already is while written; a +/// plain file stays plain though the stage's name starts with a dot; a new file gets neither. +/// Through a symbolic link the file it names is the replaced file and keeps its attributes. +#[cfg(windows)] +#[test] +fn hidden_and_system_attributes_are_kept() { + use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; + const HIDDEN: u32 = 0x2; + const SYSTEM: u32 = 0x4; + let d = TempDir::new("attributes"); + let kept = |p: &Path| std::fs::metadata(p).unwrap().file_attributes() & (HIDDEN | SYSTEM); + let plant = |p: &Path, attributes: u32| { + let mut fixture = OpenOptions::new().write(true).create_new(true).attributes(attributes).open(p).unwrap(); + fixture.write_all(ORIGINAL).unwrap(); + }; + for (i, keep) in [0, HIDDEN, SYSTEM, HIDDEN | SYSTEM].into_iter().enumerate() { + let target = d.0.join(format!("doc{i}.pdf")); + plant(&target, keep); + assert_eq!(kept(&target), keep, "the fixture has attributes {keep:#x}"); + let mut staged = u32::MAX; + atomic_write_with(&target, |f| { + staged = f.metadata()?.file_attributes() & (HIDDEN | SYSTEM); + f.write_all(b"new") + }) + .unwrap(); + assert_eq!(staged, keep, "the stage has the target's attributes before it is flushed"); + assert_eq!(kept(&target), keep, "the saved file keeps attributes {keep:#x}"); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + } + let fresh = d.0.join("new.pdf"); + atomic_write(&fresh, b"new").unwrap(); + assert_eq!(kept(&fresh), 0, "a new file is neither hidden nor system"); + + let referent = d.0.join("referent.pdf"); + plant(&referent, HIDDEN); + let link = d.0.join("link.pdf"); + if let Err(e) = std::os::windows::fs::symlink_file(&referent, &link) { + eprintln!("skipped the link case: creating a symbolic link needs Developer Mode or administrator rights ({e})"); + return; + } + atomic_write(&link, b"through the link").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link"); + assert_eq!(std::fs::read(&referent).unwrap(), b"through the link"); + assert_eq!(kept(&referent), HIDDEN, "the file the link names stays hidden"); + assert_no_temp(&d.0); +} + #[cfg(target_arch = "wasm32")] #[test] fn wasm_atomic_write_returns_unsupported() { diff --git a/crates/audio/src/flac_decode.rs b/crates/audio/src/flac_decode.rs index bb56e65c52..790a9110e9 100644 --- a/crates/audio/src/flac_decode.rs +++ b/crates/audio/src/flac_decode.rs @@ -205,6 +205,16 @@ impl<'a> Bits<'a> { const BLOCK_SIZES: [usize; 16] = [0, 192, 576, 1152, 2304, 4608, 0, 0, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768]; +struct FrameHeader { + variable: bool, + number: u64, + block_size: usize, + sample_rate: u32, + bits: u32, + channels: usize, + mode: Stereo, +} + /// A frame decoder. `info` supplies what a frame header leaves to the STREAMINFO. #[derive(Debug, Clone, Copy, Default)] pub struct Decoder { @@ -223,14 +233,12 @@ impl Decoder { Decoder { info: None } } - /// Decode the frame at the start of `data`. - pub fn decode_frame(&self, data: &[u8]) -> Result { + fn read_frame_header(&self, r: &mut Bits<'_>) -> Result { // StreamInfo has public fields: container callers can construct it without // parse(), so validate before it can control shifts and sample reads. if self.info.is_some_and(|i| !(4..=32).contains(&i.bits_per_sample) || !(1..=8).contains(&i.channels) || i.sample_rate == 0) { return Err(DecodeError::Invalid("invalid decoder STREAMINFO")); } - let mut r = Bits::new(data); if r.bits(15)? != 0x7FFC { return Err(DecodeError::Invalid("missing frame sync code")); } @@ -240,7 +248,7 @@ impl Decoder { if r.bit()? != 0 { return Err(DecodeError::Invalid("reserved bit set")); } - let number = coded_number(&mut r)?; + let number = coded_number(r)?; let block_size = match bs_code { 0 => return Err(DecodeError::Invalid("reserved block size")), 6 => r.bits(8)? as usize + 1, @@ -267,7 +275,7 @@ impl Decoder { }; let header_len = r.pos.div_ceil(8); let stored_crc = r.bits(8)? as u8; - if crc8(&data[..header_len]) != stored_crc { + if crc8(&r.data[..header_len]) != stored_crc { return Err(DecodeError::Crc("a frame header")); } let bits = match bps_code { @@ -287,6 +295,24 @@ impl Decoder { 10 => (2, Stereo::MidSide), _ => return Err(DecodeError::Invalid("reserved channel assignment")), }; + Ok(FrameHeader { variable, number, block_size, sample_rate, bits, channels, mode }) + } + + /// Read a FLAC packet's sample count from an intact header even if the body is damaged. + pub(crate) fn packet_block_size(&self, data: &[u8]) -> Option { + let info = self.info?; + let header = self.read_frame_header(&mut Bits::new(data)).ok()?; + (header.sample_rate == info.sample_rate + && header.bits == u32::from(info.bits_per_sample) + && header.channels == usize::from(info.channels) + && header.block_size <= usize::from(u16::MAX)) + .then_some(header.block_size) + } + + /// Decode the frame at the start of `data`. + pub fn decode_frame(&self, data: &[u8]) -> Result { + let mut r = Bits::new(data); + let FrameHeader { variable, number, block_size, sample_rate, bits, channels, mode } = self.read_frame_header(&mut r)?; let mut out: Vec> = Vec::with_capacity(channels); for c in 0..channels { let extra = match (mode, c) { diff --git a/crates/audio/src/flac_layout.rs b/crates/audio/src/flac_layout.rs new file mode 100644 index 0000000000..f1f53e5b86 --- /dev/null +++ b/crates/audio/src/flac_layout.rs @@ -0,0 +1,114 @@ +//! FLAC speaker layout from STREAMINFO and Vorbis comments (RFC 9639). + +use crate::ChannelLayout; +use crate::pcm::{be_u32, le_u32}; + +/// The layout of the FLAC stream at `at`, from its STREAMINFO channel count and its channel mask +/// comment, or `None` when it does not start with a STREAMINFO block. +#[cfg(feature = "symphonia")] +pub(crate) fn layout(b: &[u8], at: usize) -> Option { + let head = be_u32(b, at.checked_add(4)?)?; + if (head >> 24) & 0x7f != 0 { + return None; + } + // In STREAMINFO: 3 bits of channels - 1 after the 20 bits of rate. + let channels = u16::from((b.get(at.checked_add(4 + 4 + 10 + 2)?)? >> 1) & 0x7) + 1; + Some(layout_of(b, at, channels)) +} + +/// `channels` channels described by the channel mask comment of the stream at `at`, or else in +/// the layout decoders assume for the count (RFC 9639 §8.6.2, §9.1.3). +pub(crate) fn layout_of(b: &[u8], at: usize, channels: u16) -> ChannelLayout { + layout_from(channel_mask(b, at), channels) +} + +/// `channels` channels described by a channel mask comment's value, or else in the layout decoders +/// assume for the count. +pub(crate) fn layout_from(mask: Option, channels: u16) -> ChannelLayout { + let mask = mask.unwrap_or_else(|| crate::layout::flac_assumed_mask(usize::from(channels))); + ChannelLayout::from_mask_and_channels(mask, channels) +} + +/// The value of the first `WAVEFORMATEXTENSIBLE_CHANNEL_MASK` comment that holds a `0x` hexadecimal +/// number, in the stream at `at`. +fn channel_mask(b: &[u8], at: usize) -> Option { + let mut pos = at.checked_add(4)?; + loop { + let head = be_u32(b, pos)?; + let (body, len) = (pos.checked_add(4)?, (head & 0x00ff_ffff) as usize); + let end = body.checked_add(len)?.min(b.len()); + if (head >> 24) & 0x7f == 4 { + return comments_mask(b.get(body..end)?); + } + if head >> 31 == 1 { + return None; + } + pos = body.checked_add(len)?; + } +} + +/// The mask in a comment, when its key is the channel mask's and its value a `0x` hexadecimal number. +fn comment_mask(key: &[u8], value: &[u8]) -> Option { + if !key.eq_ignore_ascii_case(b"WAVEFORMATEXTENSIBLE_CHANNEL_MASK") { + return None; + } + let hex = value.strip_prefix(b"0x").or_else(|| value.strip_prefix(b"0X"))?; + u32::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok() +} + +/// The channel mask in a Vorbis comment block's body. +pub(crate) fn comments_mask(block: &[u8]) -> Option { + let vendor = le_u32(block, 0)? as usize; + let mut at = 4usize.checked_add(vendor)?; + let count = le_u32(block, at)?; + at += 4; + for _ in 0..count { + let len = le_u32(block, at)? as usize; + let comment = block.get(at + 4..(at + 4).checked_add(len)?)?; + at += 4 + len; + let Some(eq) = comment.iter().position(|&c| c == b'=') else { continue }; + if let Some(mask) = comment_mask(&comment[..eq], &comment[eq + 1..]) { + return Some(mask); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::comments_mask; + + fn block(comments: &[&str]) -> Vec { + let mut b = 3u32.to_le_bytes().to_vec(); + b.extend_from_slice(b"abc"); + b.extend_from_slice(&(comments.len() as u32).to_le_bytes()); + for c in comments { + b.extend_from_slice(&(c.len() as u32).to_le_bytes()); + b.extend_from_slice(c.as_bytes()); + } + b + } + + #[test] + fn the_channel_mask_comment_is_found_in_any_case() { + assert_eq!(comments_mask(&block(&["TITLE=x", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"])), Some(0x107)); + assert_eq!(comments_mask(&block(&["waveformatextensible_channel_mask=0X3f"])), Some(0x3F)); + assert_eq!(comments_mask(&block(&["TITLE=x"])), None); + } + + #[test] + fn a_bad_channel_mask_comment_is_ignored() { + for value in ["63", "0x", "0xZZ", "0x1FFFFFFFF"] { + assert_eq!(comments_mask(&block(&[&format!("WAVEFORMATEXTENSIBLE_CHANNEL_MASK={value}")])), None, "{value}"); + } + assert_eq!(comments_mask(&block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=bad", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"])), Some(3)); + } + + #[test] + fn a_truncated_comment_block_has_no_mask() { + let whole = block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"]); + for cut in 0..whole.len() { + assert_eq!(comments_mask(&whole[..cut]), None, "{cut}"); + } + } +} diff --git a/crates/audio/src/layout.rs b/crates/audio/src/layout.rs index fc3cb2d524..08abe5423d 100644 --- a/crates/audio/src/layout.rs +++ b/crates/audio/src/layout.rs @@ -151,6 +151,7 @@ impl TryFrom for ChannelLayout { feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode", + feature = "flac-decode", feature = "pcm-encode" ))] pub(crate) fn count(n: usize) -> u16 { @@ -273,7 +274,7 @@ impl std::fmt::Display for ChannelLayout { /// The layout decoders assume for 1–8 FLAC channels with no channel mask comment, as a WAV mask. /// RFC 9639 §9.1.3 leaves "back/surround" open for 5 and 6 channels; libFLAC and ffmpeg read side /// surrounds. 7 channels are 6.1 with sides (FL FR FC LFE BC SL SR). -#[cfg(any(feature = "symphonia", feature = "flac-encode"))] +#[cfg(any(feature = "symphonia", feature = "flac-encode", feature = "flac-decode"))] pub(crate) fn flac_assumed_mask(channels: usize) -> u32 { match channels { 5 => 0x607, diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 9ca1571cf8..29054288ec 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -49,6 +49,8 @@ pub mod alac; mod buffer; #[cfg(feature = "dsd")] pub mod dsd; +#[cfg(any(feature = "flac-decode", feature = "symphonia"))] +mod flac_layout; #[cfg(feature = "g722")] pub mod g722; #[cfg(feature = "g726")] @@ -62,7 +64,14 @@ pub mod mp3; pub mod mpa; #[cfg(any(feature = "opus-decode", feature = "opus-encode"))] pub mod opus; -#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] +#[cfg(any( + feature = "aac-decode", + feature = "alac-decode", + feature = "opus-decode", + feature = "ac3-decode", + feature = "mpa-decode", + feature = "flac-decode" +))] mod pcm; #[cfg(feature = "peaks")] pub mod peaks; @@ -72,7 +81,14 @@ pub mod qoa; mod read; #[cfg(feature = "sbc")] pub mod sbc; -#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] +#[cfg(any( + feature = "aac-decode", + feature = "alac-decode", + feature = "opus-decode", + feature = "ac3-decode", + feature = "mpa-decode", + feature = "flac-decode" +))] mod track; #[cfg(feature = "vmd-decode")] pub mod vmd; @@ -150,7 +166,14 @@ pub use read::{ }; #[cfg(feature = "decode-native")] pub use read::{RawPcm, aiff_pcm, wav_pcm}; -#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] +#[cfg(any( + feature = "aac-decode", + feature = "alac-decode", + feature = "opus-decode", + feature = "ac3-decode", + feature = "mpa-decode", + feature = "flac-decode" +))] pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; #[cfg(any( feature = "pcm-encode", diff --git a/crates/audio/src/pcm.rs b/crates/audio/src/pcm.rs index 397f0c07f6..6cef7527f0 100644 --- a/crates/audio/src/pcm.rs +++ b/crates/audio/src/pcm.rs @@ -14,7 +14,7 @@ pub(crate) fn le_u16(b: &[u8], pos: usize) -> Option { } /// Little-endian `u32` at `pos`. -#[cfg(feature = "decode-native")] +#[cfg(any(feature = "decode-native", feature = "flac-decode"))] pub(crate) fn le_u32(b: &[u8], pos: usize) -> Option { let s: [u8; 4] = b.get(pos..pos.checked_add(4)?)?.try_into().ok()?; Some(u32::from_le_bytes(s)) @@ -35,7 +35,7 @@ pub(crate) fn be_u16(b: &[u8], pos: usize) -> Option { } /// Big-endian `u32` at `pos`. -#[cfg(feature = "decode-native")] +#[cfg(any(feature = "decode-native", feature = "flac-decode"))] pub(crate) fn be_u32(b: &[u8], pos: usize) -> Option { let s: [u8; 4] = b.get(pos..pos.checked_add(4)?)?.try_into().ok()?; Some(u32::from_be_bytes(s)) diff --git a/crates/audio/src/read/flac.rs b/crates/audio/src/read/flac.rs index 16ffd3a06c..fb8da9851a 100644 --- a/crates/audio/src/read/flac.rs +++ b/crates/audio/src/read/flac.rs @@ -2,8 +2,10 @@ use craft_media::ogg; +use crate::flac_layout::{comments_mask, layout_of}; +pub(crate) use crate::flac_layout::{layout, layout_from}; use crate::pcm::{be_u32, le_u32}; -use crate::{AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result, SampleFormat}; +use crate::{AudioError, AudioInfo, CodecId, Container, Result, SampleFormat}; /// Refuse the FLAC stream at `at` if a comment or picture field claims more bytes than its /// metadata block holds: symphonia allocates each field's length before reading it. @@ -72,58 +74,6 @@ pub(crate) fn empty_stream_info(b: &[u8], at: usize) -> Option { Some(AudioInfo::new(Container::Flac, CodecId::Flac, sample_format, sample_rate, layout_of(b, at, channels), 0)) } -/// The layout of the FLAC stream at `at`, from its STREAMINFO channel count and its channel mask -/// comment, or `None` when it does not start with a STREAMINFO block. -pub(crate) fn layout(b: &[u8], at: usize) -> Option { - let head = be_u32(b, at.checked_add(4)?)?; - if (head >> 24) & 0x7f != 0 { - return None; - } - // In STREAMINFO: 3 bits of channels - 1 after the 20 bits of rate. - let channels = u16::from((b.get(at.checked_add(4 + 4 + 10 + 2)?)? >> 1) & 0x7) + 1; - Some(layout_of(b, at, channels)) -} - -/// `channels` channels described by the channel mask comment of the stream at `at`, or else in -/// the layout decoders assume for the count (RFC 9639 §8.6.2, §9.1.3). -fn layout_of(b: &[u8], at: usize, channels: u16) -> ChannelLayout { - layout_from(channel_mask(b, at), channels) -} - -/// `channels` channels described by a channel mask comment's value, or else in the layout decoders -/// assume for the count. -pub(crate) fn layout_from(mask: Option, channels: u16) -> ChannelLayout { - let mask = mask.unwrap_or_else(|| crate::layout::flac_assumed_mask(usize::from(channels))); - ChannelLayout::from_mask_and_channels(mask, channels) -} - -/// The value of the first `WAVEFORMATEXTENSIBLE_CHANNEL_MASK` comment that holds a `0x` hexadecimal -/// number, in the stream at `at`. -fn channel_mask(b: &[u8], at: usize) -> Option { - let mut pos = at.checked_add(4)?; - loop { - let head = be_u32(b, pos)?; - let (body, len) = (pos.checked_add(4)?, (head & 0x00ff_ffff) as usize); - let end = body.checked_add(len)?.min(b.len()); - if (head >> 24) & 0x7f == 4 { - return comments_mask(b.get(body..end)?); - } - if head >> 31 == 1 { - return None; - } - pos = body.checked_add(len)?; - } -} - -/// The mask in a comment, when its key is the channel mask's and its value a `0x` hexadecimal number. -fn comment_mask(key: &[u8], value: &[u8]) -> Option { - if !key.eq_ignore_ascii_case(b"WAVEFORMATEXTENSIBLE_CHANNEL_MASK") { - return None; - } - let hex = value.strip_prefix(b"0x").or_else(|| value.strip_prefix(b"0X"))?; - u32::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok() -} - /// The audio streams of the Ogg file `b` in file order, as `tracks` lists them: each one's serial /// and, for FLAC, its channel mask comment. Empty when the demuxer cannot read the file. pub(crate) fn ogg_audio_streams(b: &[u8]) -> Vec<(u32, Option)> { @@ -136,24 +86,6 @@ pub(crate) fn ogg_audio_streams(b: &[u8]) -> Vec<(u32, Option)> { file.streams.iter().filter(|s| s.codec.codec_id().is_audio()).map(|s| (s.serial, mask(s).filter(|_| s.codec == ogg::Codec::Flac))).collect() } -/// The channel mask in a Vorbis comment block's body. -fn comments_mask(block: &[u8]) -> Option { - let vendor = le_u32(block, 0)? as usize; - let mut at = 4usize.checked_add(vendor)?; - let count = le_u32(block, at)?; - at += 4; - for _ in 0..count { - let len = le_u32(block, at)? as usize; - let comment = block.get(at + 4..(at + 4).checked_add(len)?)?; - at += 4 + len; - let Some(eq) = comment.iter().position(|&c| c == b'=') else { continue }; - if let Some(mask) = comment_mask(&comment[..eq], &comment[eq + 1..]) { - return Some(mask); - } - } - None -} - /// Whether a vendor string or comment in a (little-endian) Vorbis comment block claims more than /// the block holds. fn comments_overrun(b: &[u8], body: usize, end: usize) -> bool { diff --git a/crates/audio/src/read/native.rs b/crates/audio/src/read/native.rs index d2eef95e59..a42aec6d47 100644 --- a/crates/audio/src/read/native.rs +++ b/crates/audio/src/read/native.rs @@ -820,6 +820,11 @@ fn open_mp4<'a>(src: &Src<'a>, container: Container, track: Option) -> Op return Some(Err(AudioError::Malformed("MP4 sample is larger than the file".into()))); } let params = t.codec_params(); + // Keep file-level FLAC on its existing path until this reader can index variable packet + // lengths and final duration from the frame headers. The packet API has no such timing role. + if params.codec == CodecId::Flac { + return None; + } let lookahead: Vec> = (0..t.samples.len().min(crate::track::LOOKAHEAD_PACKETS)).filter_map(|i| file.read_sample(src, track, i).ok()).collect(); let timescale = t.timescale; @@ -897,6 +902,11 @@ fn open_mkv<'a>(src: &Src<'a>, container: Container, track: Option) -> Op return None; } let params = t.codec_params(); + // The Matroska file API needs FLAC frame counts to undo timestamp rounding on seeks. + // Keep its existing fallback until it can index those counts. + if params.codec == CodecId::Flac { + return None; + } let lookahead: Vec> = (0..t.samples.len().min(crate::track::LOOKAHEAD_PACKETS)).filter_map(|i| demux.read_sample(track, i).ok()).collect(); let probe = TrackDecoder::new(¶ms, &lookahead.iter().map(Vec::as_slice).collect::>()).ok()?; diff --git a/crates/audio/src/track.rs b/crates/audio/src/track.rs index ce0182d75a..cc1d9d7079 100644 --- a/crates/audio/src/track.rs +++ b/crates/audio/src/track.rs @@ -1,5 +1,5 @@ //! [`TrackDecoder`]: one track's packets in, planar `f32` in WAV channel order out, whatever the -//! codec. The file-level [`crate::decode`] and [`crate::Decoder`] use it for every native codec; +//! codec. The file-level [`crate::decode`] and [`crate::Decoder`] use it for their native routes; //! an app with its own demuxer (MXF, MPEG-TS, a network stream) uses it directly. #[cfg(feature = "aac-decode")] @@ -17,6 +17,9 @@ use crate::opus; use crate::pcm::{PcmKind, deinterleave}; use crate::{AudioBuffer, AudioError, ChannelLayout, CodecId, CodecParams, Result, SampleFormat}; +#[cfg(feature = "flac-decode")] +mod flac_packet; + /// How many leading packets [`TrackDecoder::new`] looks at. pub const LOOKAHEAD_PACKETS: usize = 8; @@ -39,6 +42,8 @@ enum Inner { /// 2^-(bit depth - 1): full scale to ±1. scale: f64, }, + #[cfg(feature = "flac-decode")] + Flac(Box), /// The decoder, and what the packets read so far say of the track's packets. #[cfg(feature = "ac3-decode")] Ac3(Box, Ac3Packets), @@ -76,7 +81,7 @@ pub(crate) type PacketFrames = fn(&[u8], u64) -> Option; /// /// It takes the track's [`CodecParams`] (from `isobmff::Track::codec_params`, /// `matroska::Track::codec_params`, `ogg::Stream::codec_params`, or built by hand for another -/// container) and decodes AAC (LC, and HE-AAC with its SBR high band), ALAC, Opus, AC-3/E-AC-3, +/// container) and decodes AAC (LC, and HE-AAC with its SBR high band), ALAC, FLAC, Opus, AC-3/E-AC-3, /// MP1/MP2, MP3 and PCM. Container timing (AAC priming, Opus pre-skip, end trimming) is the caller's: /// every decoded sample is returned. /// @@ -130,11 +135,10 @@ impl TrackDecoder { /// Opus with empty `extradata` and 1 or 2 `channels` (RTP, MPEG-TS) needs no `OpusHead`. Other /// missing configuration is [`AudioError::Malformed`]. /// + /// FLAC needs the `fLaC` magic and metadata blocks, starting with STREAMINFO, in `extradata`. /// ALAC needs its magic cookie in `extradata`. /// - /// Codecs without a native packet decoder yet (FLAC, Vorbis) are - /// [`AudioError::Unsupported`]; `craft_audio::decode` decodes them through symphonia when the - /// `symphonia` feature is on. + /// Unavailable packet codecs return [`AudioError::Unsupported`]. pub fn new(params: &CodecParams, lookahead: &[&[u8]]) -> Result { #[cfg(not(feature = "aac-decode"))] let _ = lookahead; @@ -209,6 +213,18 @@ impl TrackDecoder { let scale = 2f64.powi(1 - i32::from(cfg.bit_depth)); (Inner::Alac { dec, order, scale }, CodecId::Alac, rate, layout, sample_format) } + #[cfg(feature = "flac-decode")] + CodecId::Flac => { + let (track, layout) = flac_packet::FlacTrack::new(¶ms.extradata)?; + let rate = track.info.sample_rate; + let sample_format = match track.info.bits_per_sample { + 4..=8 => SampleFormat::Int8, + 9..=16 => SampleFormat::Int16, + 17..=24 => SampleFormat::Int24, + _ => SampleFormat::Int32, + }; + (Inner::Flac(Box::new(track)), CodecId::Flac, rate, layout, sample_format) + } #[cfg(feature = "ac3-decode")] CodecId::Ac3 | CodecId::Eac3 => match ac3::parse_header(first) { Ok(h) => { @@ -313,6 +329,25 @@ impl TrackDecoder { self.sample_format } + /// The exact codec configuration for a FLAC track. + #[cfg(feature = "flac-decode")] + pub fn flac_stream_info(&self) -> Option { + match &self.inner { + Inner::Flac(track) => Some(track.info), + _ => None, + } + } + + /// The FLAC packet's actual sample count, including a short final frame. This requires an + /// intact header and matching stream format but can read through a damaged frame body. + #[cfg(feature = "flac-decode")] + pub fn flac_packet_frames(&self, packet: &[u8]) -> Option { + match &self.inner { + Inner::Flac(track) => track.packet_frames(packet), + _ => None, + } + } + /// Decode one packet. An MP4 or Matroska packet may hold several AC-3 or MPEG audio frames; /// an E-AC-3 dependent substream decodes to no frames. A packet that fails is an error for /// every codec: call [`TrackDecoder::conceal`] for audio of its length, so what follows keeps @@ -347,6 +382,8 @@ impl TrackDecoder { let floats = decoded.into_iter().map(|c| c.into_iter().map(|v| (f64::from(v) * *scale) as f32).collect()).collect(); reorder(floats, *order) } + #[cfg(feature = "flac-decode")] + Inner::Flac(track) => track.decode(packet)?, #[cfg(feature = "mpa-decode")] Inner::Mpa { dec, several } => { let (out, first, count, cut) = mpa_frames(packet, |f| dec.decode(f))?; @@ -453,6 +490,8 @@ impl TrackDecoder { Inner::Alac { dec, .. } => { Some(dec.packet_frames(data).unwrap_or(if self.last_frames > 0 { self.last_frames } else { dec.config().frame_length as usize })) } + #[cfg(feature = "flac-decode")] + Inner::Flac(track) => track.packet_frames(data), #[cfg(feature = "ac3-decode")] Inner::Ac3(..) => Some(ac3_packet_frames(data)), #[cfg(feature = "mpa-decode")] @@ -488,6 +527,8 @@ impl TrackDecoder { Inner::Aac { sbr, .. } => Some(aac::FRAME_LEN * if *sbr { 2 } else { 1 }), #[cfg(feature = "alac-decode")] Inner::Alac { .. } => None, + #[cfg(feature = "flac-decode")] + Inner::Flac(..) => None, #[cfg(feature = "ac3-decode")] Inner::Ac3(_, shape) if shape.varies => None, #[cfg(feature = "ac3-decode")] @@ -544,6 +585,8 @@ impl TrackDecoder { Inner::Aac { sbr, .. } => 2 * aac::FRAME_LEN * if *sbr { 2 } else { 1 }, #[cfg(feature = "alac-decode")] Inner::Alac { .. } => 0, + #[cfg(feature = "flac-decode")] + Inner::Flac(..) => 0, #[cfg(feature = "ac3-decode")] Inner::Ac3(_, shape) if shape.short => usize::MAX, #[cfg(feature = "ac3-decode")] @@ -570,6 +613,8 @@ impl TrackDecoder { Inner::Aac { dec, .. } => dec.reset(), #[cfg(feature = "alac-decode")] Inner::Alac { .. } => {} + #[cfg(feature = "flac-decode")] + Inner::Flac(..) => {} #[cfg(feature = "ac3-decode")] Inner::Ac3(d, _) => d.reset(), #[cfg(feature = "opus-decode")] @@ -587,6 +632,7 @@ fn unsupported(codec: CodecId) -> AudioError { let feature = match codec { CodecId::Aac | CodecId::HeAac => Some("aac-decode"), CodecId::Alac => Some("alac-decode"), + CodecId::Flac => Some("flac-decode"), CodecId::Ac3 | CodecId::Eac3 => Some("ac3-decode"), CodecId::Opus => Some("opus-decode"), CodecId::Mp1 | CodecId::Mp2 => Some("mpa-decode"), @@ -596,7 +642,7 @@ fn unsupported(codec: CodecId) -> AudioError { match feature { // A codec this crate decodes, in a build without its feature. Some(f) => AudioError::Unsupported(format!("decoding {} needs the `{f}` feature", codec.name())), - None if cfg!(feature = "symphonia") && matches!(codec, CodecId::Flac | CodecId::Vorbis) => { + None if cfg!(feature = "symphonia") && codec == CodecId::Vorbis => { AudioError::Unsupported(format!("no native {} packet decoder yet (craft_audio::decode reads it through symphonia)", codec.name())) } None => AudioError::Unsupported(format!("no native {} packet decoder yet", codec.name())), diff --git a/crates/audio/src/track/flac_packet.rs b/crates/audio/src/track/flac_packet.rs new file mode 100644 index 0000000000..07cc5c047c --- /dev/null +++ b/crates/audio/src/track/flac_packet.rs @@ -0,0 +1,46 @@ +//! FLAC framing shared by the MP4 and Matroska packet readers. + +use crate::flac_decode::{Decoder, StreamInfo}; +use crate::{AudioError, ChannelLayout, Result}; + +pub(super) struct FlacTrack { + pub(super) info: StreamInfo, + decoder: Decoder, +} + +impl FlacTrack { + pub(super) fn new(private: &[u8]) -> Result<(Self, ChannelLayout)> { + let [b'f', b'L', b'a', b'C', kind, 0, 0, 34, body @ ..] = private else { + return Err(AudioError::Malformed("FLAC track without a STREAMINFO block".into())); + }; + if kind & 0x7f != 0 { + return Err(AudioError::Malformed("FLAC STREAMINFO must be the first metadata block".into())); + } + let info = StreamInfo::parse(body).map_err(|error| AudioError::Malformed(format!("FLAC STREAMINFO: {error}")))?; + if info.sample_rate == 0 { + return Err(AudioError::Malformed("FLAC track sample rate is zero".into())); + } + let layout = crate::flac_layout::layout_of(private, 0, u16::from(info.channels)); + Ok((Self { info, decoder: Decoder::new(info) }, layout)) + } + + pub(super) fn decode(&self, packet: &[u8]) -> Result>> { + let frame = self.decoder.decode_frame(packet).map_err(|error| AudioError::Malformed(format!("FLAC packet: {error}")))?; + if frame.size != packet.len() { + return Err(AudioError::Malformed("FLAC packet must hold exactly one frame".into())); + } + if frame.sample_rate != self.info.sample_rate + || frame.bits_per_sample != self.info.bits_per_sample + || frame.channels.len() != usize::from(self.info.channels) + || frame.block_size > usize::from(u16::MAX) + { + return Err(AudioError::Malformed("FLAC packet format differs from STREAMINFO".into())); + } + let scale = 2f64.powi(1 - i32::from(self.info.bits_per_sample)); + Ok(frame.channels.into_iter().map(|plane| plane.into_iter().map(|sample| (f64::from(sample) * scale) as f32).collect()).collect()) + } + + pub(super) fn packet_frames(&self, data: &[u8]) -> Option { + self.decoder.packet_block_size(data) + } +} diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs index a1895789b2..d252372514 100644 --- a/crates/audio/tests/flac_decode.rs +++ b/crates/audio/tests/flac_decode.rs @@ -4,6 +4,7 @@ //! ffmpeg's encoder writes at every compression level. use craft_audio::flac::{DecodeError, Decoder, Encoder, EncoderConfig, STREAMINFO_OFFSET, StreamInfo, decode}; +use craft_audio::{AudioError, CodecId, CodecParams, SampleFormat, TrackDecoder}; use std::process::Command; fn signal(channels: usize, frames: usize, bits: u32, seed: u32) -> Vec> { @@ -79,6 +80,56 @@ fn frames_decode_one_at_a_time() { let _ = Decoder::without_streaminfo().decode_frame(&file[at..]); } +#[test] +fn track_decoder_uses_streaminfo_layout_and_packet_length() { + let source = signal(4, 80, 24, 17); + let mut config = EncoderConfig::new(96_000, 4, 24); + config.block_size = 32; + let mut encoder = Encoder::new(config).expect("encoder"); + let mut private = encoder.header(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x603"]); + let planes: Vec<&[i32]> = source.iter().map(Vec::as_slice).collect(); + let mut packets = encoder.encode_frames(&planes).expect("packets"); + packets.push(encoder.finish()); + let at = STREAMINFO_OFFSET as usize; + private[at..at + 34].copy_from_slice(&encoder.streaminfo()); + + let params = CodecParams::new(CodecId::Flac).with_extradata(private).with_sample_rate(48_000).with_channels(4); + let mut track = TrackDecoder::new(¶ms, &[]).expect("native FLAC track"); + assert_eq!(track.sample_rate(), 96_000); + assert_eq!(track.flac_stream_info().expect("FLAC stream info").bits_per_sample, 24); + assert_eq!(track.layout().channels(), 4); + assert_eq!(track.layout().mask(), Some(0x603)); + assert_eq!(track.sample_format(), SampleFormat::Int24); + assert_eq!(track.frames_per_packet(), None); + assert_eq!(track.preroll(), 0); + + let final_packet = packets.last().expect("final packet"); + let decoded = track.decode(final_packet).expect("independent final frame"); + assert_eq!(decoded.frames(), 16); + for (plane, expected) in decoded.channels.iter().zip(&source) { + for (sample, expected) in plane.iter().zip(&expected[64..]) { + assert_eq!(*sample, (f64::from(*expected) / 8_388_608.0) as f32); + } + } + assert_eq!(track.decode(&packets[0]).expect("backwards seek").frames(), 32); + let truncated = &final_packet[..final_packet.len() - 1]; + assert_eq!(track.flac_packet_frames(truncated), Some(16)); + assert!(matches!(track.decode(truncated), Err(AudioError::Malformed(_)))); + let concealed = track.conceal(Some(truncated)).expect("silence from the intact header"); + assert_eq!(concealed.frames(), 16); + assert_eq!(concealed.peak(), 0.0); + track.reset(); + assert_eq!(track.decode(final_packet).expect("decode after reset"), decoded); + + let mut extra = final_packet.clone(); + extra.push(0); + assert!(matches!(track.decode(&extra), Err(AudioError::Malformed(_)))); + assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Flac), &[]), Err(AudioError::Malformed(_)))); + let mut incomplete = params.clone(); + incomplete.extradata.truncate(at + 33); + assert!(matches!(TrackDecoder::new(&incomplete, &[]), Err(AudioError::Malformed(_)))); +} + #[test] fn hostile_input_is_an_error_not_a_panic() { let src = signal(2, 6000, 16, 11); diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index cd8e76439e..7fd0ce225b 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-automation" -description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue, frame profiler and frame trace; native only), and recorded actions with the Actions panel (every target)." +description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue and synthetic input on every target; server, client, frame profiler and frame trace native only), and recorded actions with the Actions panel (every target)." version.workspace = true edition.workspace = true license.workspace = true @@ -22,7 +22,7 @@ default = [] # The egui parts: the Actions panel, the control channel's server side (screenshots, synthetic # input) and `ui` stories. Without it the crate has no egui: `ControlOptions`, `ControlClient`, # `Params` and the recorded actions' model and files. -ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"] +ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-host"] # The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`. screen-testing = ["ui", "agents", "craft-ui/testing"] # Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an @@ -31,28 +31,30 @@ screen-testing = ["ui", "agents", "craft-ui/testing"] agents = ["craft-control/agents", "dep:craft-host"] [dependencies] +# The screenshot reply's PNG and its inline base64 (the control channel builds on every target with `ui`). +base64 = "0.23" craft-behavior = { workspace = true, optional = true } # The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the # CLI's live client), re-exported by `agents` so every app shares one copy. craft-control = { workspace = true } +# The recorded actions' file picks (`ui`) go through the host on every target. +craft-host = { workspace = true, optional = true } craft-keymap = { workspace = true, optional = true } craft-theme = { workspace = true } craft-ui = { workspace = true, optional = true } egui = { workspace = true, optional = true } +png = "0.17" serde = { workspace = true } serde_json = { workspace = true } -web-time = "1.1" -# The screenshot queue encodes and inlines PNGs on every target the control channel builds for. -base64 = "0.22" -png = "0.17" - -# The server, client, profiler and trace. -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-platform = { workspace = true } -craft-host = { workspace = true, optional = true } +log = "0.4" +# `std::time::Instant` panics on wasm; this is the same type on native. +web-time = "1.1" + +# The server, client, token files, profiler and trace. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] getrandom = "0.3" hmac = "0.12" -log = "0.4" sha2 = { version = "0.10", default-features = false, features = ["std"] } thiserror = { workspace = true } diff --git a/crates/automation/README.md b/crates/automation/README.md index d82a01e5b5..2fdbf75be4 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,8 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | | `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | diff --git a/crates/automation/src/access.rs b/crates/automation/src/access.rs new file mode 100644 index 0000000000..d25f93d112 --- /dev/null +++ b/crates/automation/src/access.rs @@ -0,0 +1,390 @@ +//! Named controls over the window's access tree (`ui.find`, `control` targets) and `ui.inspect` (the reported +//! widgets of a window's access tree, and the lookup of the one node a click or a focus names). +//! +//! Both read the tree the window host keeps from the last presented frame ([`WindowHost::keep_access_tree`], which +//! the control server turns on) and walk only the nodes assistive technology reports ([`AccessTree::keys`]): a hidden node, +//! one below it and one behind an open modal are neither listed nor reachable. + +use std::collections::HashSet; + +use craft_behavior::Mixed; +use craft_ui::runtime::access::Role; +use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey, name}; +use craft_ui::runtime::windows::WindowHost; +use egui::{Rect, ViewportId}; +use serde_json::{Map, Value, json}; + +use crate::protocol::Params; + +/// The error of a request made before the first kept pass has an access tree. +pub const NO_TREE: &str = "no accessibility tree yet: send the request after a frame was drawn"; + +/// The error of a target no control matches. +pub const NO_CONTROL: &str = "no control matches"; + +/// The error of a target several controls match, with no `index`. +pub const AMBIGUOUS: &str = "more than one control matches"; + +/// The error of a control with no bounds to place a point on. +pub const NO_PLACE: &str = "the control has no place on the screen"; + +/// The largest `index` a target takes. +pub const MAX_INDEX: usize = 1024; + +/// The widgets `ui.inspect` lists when the request names no `limit`. +pub const DEFAULT_LIMIT: u64 = 500; + +/// The place of a control a target names: its rect in screen points, or the error why it has none. +pub type ControlMap<'a> = &'a dyn Fn(&Target) -> Result; + +/// A control named by `{name, role?, within?, index?}`. +/// +/// A name match ignores surrounding white space and one trailing `:`; `role` is an AccessKit role name, compared +/// ignoring case; `within` is the name of any matching ancestor. Without `index` exactly one control matches; the +/// reading order is depth first. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Target { + /// The control's accessible name. + pub name: String, + /// The control's role. + pub role: Option, + /// The name of an ancestor the control is inside. + pub within: Option, + /// Which match to take, in reading order. + pub index: Option, +} + +/// `text` as a name is compared: without surrounding white space and one trailing `:`. +fn plain(text: &str) -> &str { + let text = text.trim(); + text.strip_suffix(':').unwrap_or(text).trim() +} + +/// The node a method names: its id or its label. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NodeTarget { + /// The node's id. + Id(u64), + /// The node's label, matched case-insensitively. + Label(String), +} + +impl NodeTarget { + /// The node `params` name (`id` or `label`), or none when they name none. `id` is the id `ui.inspect` lists, a + /// decimal string or a number; `label` is a string; naming both is an error. Other fields are the caller's to + /// check; a `null` field is absent. + pub fn from_params(params: &Value) -> Result, String> { + let field = |key: &str| params.get(key).filter(|value| !value.is_null()); + match (field("id"), field("label")) { + (Some(_), Some(_)) => Err("`id` and `label` exclude each other".into()), + (Some(id), None) => { + let raw = id.as_u64().or_else(|| id.as_str().and_then(|text| text.parse().ok())); + raw.map(|raw| Some(NodeTarget::Id(raw))).ok_or_else(|| "id must be a widget id from ui.inspect".into()) + } + (None, Some(Value::String(label))) => Ok(Some(NodeTarget::Label(label.clone()))), + (None, Some(_)) => Err("label must be a string".into()), + (None, None) => Ok(None), + } + } +} + +/// What a node that takes `action` is, for the refusal of one that does not. +fn able(action: Declared) -> &'static str { + match action { + Declared::Click => "clickable", + Declared::Focus => "focusable", + Declared::ContextMenu => "a widget with a context menu", + _ => "a widget that takes this action", + } +} + +/// Queues `action` on the node `target` names in `viewport`'s kept access tree. +fn inject_node(host: &WindowHost, viewport: ViewportId, target: &NodeTarget, action: Declared) -> Result<(), String> { + let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?; + let node = resolve(&tree, target, action)?; + host.inject_access(viewport, node, action); + Ok(()) +} + +/// Queues a click of the node `target` names in `viewport`, once the kept tree has it as one reported, enabled, +/// clickable node ([`resolve`]). +pub fn inject_click(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::Click) +} + +/// Queues the context menu of the node `target` names in `viewport`, once the kept tree has it as one reported, +/// enabled node with a context menu ([`resolve`]). +pub fn inject_context_menu(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::ContextMenu) +} + +/// Queues the focus request for the node `target` names in `viewport`, once the kept tree has it as one reported, +/// enabled, focusable node ([`resolve`]). +pub fn inject_focus(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::Focus) +} + +/// The one reported, enabled node of `tree` that declares `action` and that `target` names; an error names none, +/// several, disabled or undeclared. An id must be a reported node; a label matches the reported, enabled nodes that +/// declare `action` and whose label equals it, ignoring case, and exactly one must match. +pub fn resolve(tree: &AccessTree, target: &NodeTarget, action: Declared) -> Result { + let reported = tree.keys(); + let label_of = |key: NodeKey| tree.name_of(key).unwrap_or("unlabelled").to_owned(); + let key = match target { + NodeTarget::Id(raw) => { + let key = NodeKey::from_raw(*raw); + if !reported.contains(&key) { + return Err(format!("no widget with id {raw} on screen (run ui.inspect again)")); + } + key + } + NodeTarget::Label(label) => { + let wanted = label.to_lowercase(); + let named: Vec = + reported.iter().copied().filter(|key| tree.name_of(*key).is_some_and(|name| name.to_lowercase() == wanted)).collect(); + let usable: Vec = named.iter().copied().filter(|key| !tree.is_disabled_key(*key) && tree.declares_key(*key, action)).collect(); + match usable.as_slice() { + [one] => *one, + [] if named.is_empty() => return Err(format!("no widget labelled {label:?} on screen (try ui.inspect with query)")), + [] if named.iter().any(|key| tree.declares_key(*key, action)) => { + return Err(format!("the widget labelled {label:?} is disabled")); + } + [] => return Err(format!("the widget labelled {label:?} is not {}", able(action))), + many => return Err(format!("{} widgets are labelled {label:?}; name one by id", many.len())), + } + } + }; + if tree.is_disabled_key(key) { + return Err(format!("widget {} ({}) is disabled", key.raw(), label_of(key))); + } + if !tree.declares_key(key, action) { + return Err(format!("widget {} ({}) is not {}", key.raw(), label_of(key), able(action))); + } + Ok(key) +} + +/// The accesskit role's name as agents' scripts read it (`Button`, `CheckBox`). +fn role_name(tree: &AccessTree, key: NodeKey) -> Option { + match tree.role_of(key)? { + Role::Node(role) => Some(format!("{role:?}")), + _ => None, + } +} + +impl Target { + /// The target `value` names: `{name, role?, within?, index?}` and no other field. + pub fn from_params(value: &Value) -> Result { + let p = Params(value).only(None, &["name", "role", "within", "index"])?; + let p = Params(&p); + let target = p.str_field("name")?.ok_or_else(|| "missing `name`".to_owned())?; + if target.trim().is_empty() { + return Err("`name` must not be empty".into()); + } + let index = match p.uint_field("index")? { + Some(index) if index > MAX_INDEX as u64 => return Err(format!("`index` must be at most {MAX_INDEX} (got {index})")), + index => index.map(|index| index as usize), + }; + Ok(Self { name: target.to_owned(), role: p.str_field("role")?.map(str::to_owned), within: p.str_field("within")?.map(str::to_owned), index }) + } + + /// Whether the control `key` has this target's name, role and ancestor. + fn accepts(&self, tree: &AccessTree, key: NodeKey) -> bool { + let named = |key: NodeKey, wanted: &str| name(tree, key).is_some_and(|found| plain(found) == plain(wanted)); + if !named(key, &self.name) { + return false; + } + if self.role.as_deref().is_some_and(|wanted| !role_name(tree, key).is_some_and(|role| role.eq_ignore_ascii_case(wanted))) { + return false; + } + let Some(within) = self.within.as_deref() else { return true }; + let mut above = tree.parent_of_key(key); + while let Some(ancestor) = above { + if named(ancestor, within) { + return true; + } + above = tree.parent_of_key(ancestor); + } + false + } + + /// The error of no control matching, with the fields the target gave. + fn missing(&self) -> String { + let mut error = format!("{NO_CONTROL}: name `{}`", self.name); + if let Some(role) = &self.role { + error.push_str(&format!(" role `{role}`")); + } + if let Some(within) = &self.within { + error.push_str(&format!(" within `{within}`")); + } + if let Some(index) = self.index { + error.push_str(&format!(" index {index}")); + } + error + } + + /// The control of `tree` this target names: [`NO_CONTROL`] when none matches, [`AMBIGUOUS`] when several do and + /// there is no `index`. + pub fn find(&self, tree: &AccessTree) -> Result { + let reported: HashSet = tree.keys().into_iter().collect(); + let mut matches = Vec::new(); + let mut pending: Vec = tree.root_key().into_iter().collect(); + while let Some(key) = pending.pop() { + if reported.contains(&key) && self.accepts(tree, key) { + matches.push(key); + } + pending.extend(tree.children_of(key).into_iter().rev()); + } + match (self.index, matches.as_slice()) { + (_, []) => Err(self.missing()), + (Some(index), found) => found.get(index).copied().ok_or_else(|| format!("index {index} is past the {} matching controls", found.len())), + (None, [only]) => Ok(*only), + (None, found) => Err(format!("{AMBIGUOUS} ({}): add `role`, `within` or `index`", found.len())), + } + } + + /// The rect of this target's control in the tree the host kept for `viewport`: [`NO_TREE`] before the first, + /// [`NO_PLACE`] for a control with no area. + pub fn rect(&self, host: &WindowHost, viewport: ViewportId) -> Result { + let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?; + tree.bounds_of(self.find(&tree)?) + .filter(|rect| rect.is_finite() && rect.width() > 0.0 && rect.height() > 0.0) + .ok_or_else(|| NO_PLACE.to_owned()) + } +} + +/// What `ui.find` answers for the control `key`: `{name, role, rect or null, enabled, focused, value?, numeric?, +/// expanded?, selected?, toggled?}`, the rect in screen points. +pub fn describe(tree: &AccessTree, key: NodeKey) -> Value { + let mut out = Map::new(); + out.insert("name".into(), json!(name(tree, key))); + out.insert("role".into(), json!(role_name(tree, key))); + out.insert("rect".into(), json!(tree.bounds_of(key).map(|rect| [rect.left(), rect.top(), rect.width(), rect.height()]))); + out.insert("enabled".into(), json!(!tree.is_disabled_key(key))); + out.insert("focused".into(), json!(tree.focused_key() == key)); + if let Some(value) = tree.value_of(key) { + out.insert("value".into(), json!(value)); + } + if let Some(numeric) = tree.numeric_of(key) { + out.insert("numeric".into(), json!({"value": numeric.value, "range": [numeric.range.start(), numeric.range.end()], "step": numeric.step})); + } + if let Some(expanded) = tree.expanded_of(key) { + out.insert("expanded".into(), json!(expanded)); + } + if let Some(selected) = tree.selected_of(key) { + out.insert("selected".into(), json!(selected)); + } + if let Some(toggled) = tree.toggled_of(key) { + out.insert( + "toggled".into(), + match toggled { + Mixed::Same(on) => json!(on), + Mixed::Mixed => json!("mixed"), + }, + ); + } + Value::Object(out) +} + +/// Runs the access method `method` with `params` in `viewport` from the tree the host kept ([`NO_TREE`] before the +/// first); `None` for a method this module does not have. +pub fn access_method(method: &str, params: &Value, host: &WindowHost, viewport: ViewportId) -> Option> { + match method { + "ui.find" => Some(find(params, host, viewport)), + _ => None, + } +} + +/// `ui.find`: the description of the control `params` names. +fn find(params: &Value, host: &WindowHost, viewport: ViewportId) -> Result { + let target = Target::from_params(params)?; + let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?; + Ok(describe(&tree, target.find(&tree)?)) +} + +/// One listed widget: `{id, role, depth, enabled, clickable, focusable}` and, where the node says, `label`, `value`, +/// `description`, `rect` (`[x0, y0, x1, y1]` in points), `toggled` (`true`, `false` or `mixed`), `selected`, and +/// `focused: true` for the focused node. The id is a decimal string: 64-bit ids do not survive JSON readers that use +/// doubles. +fn widget(tree: &AccessTree, key: NodeKey, depth: usize, focused: bool) -> Value { + let mut w = Map::new(); + w.insert("id".into(), json!(key.raw().to_string())); + w.insert("role".into(), json!(role_name(tree, key))); + w.insert("depth".into(), json!(depth)); + w.insert("enabled".into(), json!(!tree.is_disabled_key(key))); + w.insert("clickable".into(), json!(tree.declares_key(key, Declared::Click))); + w.insert("focusable".into(), json!(tree.declares_key(key, Declared::Focus))); + if let Some(label) = tree.name_of(key) { + w.insert("label".into(), json!(label)); + } + if let Some(value) = tree.value_of(key) { + w.insert("value".into(), json!(value)); + } + if let Some(description) = tree.description_of(key) { + w.insert("description".into(), json!(description)); + } + if let Some(rect) = tree.bounds_of(key) { + w.insert("rect".into(), json!([rect.min.x, rect.min.y, rect.max.x, rect.max.y])); + } + if let Some(toggled) = tree.toggled_of(key) { + let toggled = match toggled { + Mixed::Same(true) => "true", + Mixed::Same(false) => "false", + Mixed::Mixed => "mixed", + }; + w.insert("toggled".into(), json!(toggled)); + } + if let Some(selected) = tree.selected_of(key) { + w.insert("selected".into(), json!(selected)); + } + if focused { + w.insert("focused".into(), json!(true)); + } + Value::Object(w) +} + +/// `inspect {query?, role?, focused?, limit?=500}`: the reply `{widgets, count, truncated}` over the reported nodes +/// of `viewport`'s access tree, in tree order (depth first from the root, which is not listed, children in their +/// order). `query` matches a widget whose label, value or description contains it, ignoring case; `role` its role's +/// name, ignoring case; `focused` whether it is the focused node. `count` is every widget the filters keep, `widgets` +/// the first `limit` of them. No other fields; [`NO_TREE`] before the window presented a frame. +pub fn inspect(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result { + let p = Params(params).only(None, &["query", "role", "focused", "limit"])?; + let p = Params(&p); + let query = p.str_field("query")?.map(str::to_lowercase); + let role = p.str_field("role")?.map(str::to_lowercase); + let focused = p.bool_field("focused")?; + let limit = usize::try_from(p.uint_field("limit")?.unwrap_or(DEFAULT_LIMIT)).unwrap_or(usize::MAX); + let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?; + + let reported: HashSet = tree.keys().into_iter().collect(); + let root = tree.root_key(); + let focus = tree.focused_key(); + let (mut widgets, mut count) = (Vec::new(), 0usize); + // A stack, not recursion: the tree comes from the app and may be deep. `walked` keeps a malformed tree that lists + // a node twice from listing it twice or looping. + let mut walked = HashSet::new(); + let mut pending: Vec<(NodeKey, usize)> = root.into_iter().map(|key| (key, 0)).collect(); + while let Some((key, depth)) = pending.pop() { + if !reported.contains(&key) || !walked.insert(key) { + continue; + } + pending.extend(tree.children_of(key).into_iter().rev().map(|child| (child, depth + 1))); + if Some(key) == root { + continue; + } + let text = + [tree.name_of(key), tree.value_of(key), tree.description_of(key)].into_iter().flatten().collect::>().join(" ").to_lowercase(); + let keep = query.as_ref().is_none_or(|query| text.contains(query.as_str())) + && role.as_ref().is_none_or(|role| role_name(&tree, key).is_some_and(|name| name.to_lowercase() == *role)) + && focused.is_none_or(|wanted| (key == focus) == wanted); + if !keep { + continue; + } + count += 1; + if widgets.len() < limit { + widgets.push(widget(&tree, key, depth, key == focus)); + } + } + Ok(json!({"widgets": widgets, "count": count, "truncated": count > widgets.len()})) +} diff --git a/crates/automation/src/actions/list.rs b/crates/automation/src/actions/list.rs index 9415f9d850..4828bcb13e 100644 --- a/crates/automation/src/actions/list.rs +++ b/crates/automation/src/actions/list.rs @@ -83,9 +83,9 @@ struct LibrarySnapshot { } /// The recorded actions: one flat list (PhotoCraft's engine, journal and file are flat), each -/// action with an optional set name, plus the names of sets that hold no action yet, so New Set -/// works before anything is recorded into it (VectorCraft's nested sets map onto -/// it). +/// action with an optional set name, plus the order of every set, with or without actions, so New +/// Set works before anything is recorded into it and a set keeps its place as it fills and empties +/// (VectorCraft's nested sets map onto it). /// /// The list is app data shared by the panel, the app's commands, the CLI and the control channel: /// the panel only reads it and reports events, and the app applies each event with these calls @@ -123,12 +123,11 @@ impl ActionList { self.actions.get(index) } - /// Every set name in display order: sets of actions in order of first appearance, then the - /// empty sets in the order they were made. + /// Every set name in display order: the order sets were made or loaded, with or without actions. + /// A set an action names that the order lacks follows, by first appearance. pub fn sets(&self) -> Vec<&str> { - let mut sets: Vec<&str> = Vec::new(); - let named = self.actions.iter().filter_map(|action| action.set.as_deref()); - for set in named.chain(self.sets.iter().map(String::as_str)) { + let mut sets: Vec<&str> = self.sets.iter().map(String::as_str).collect(); + for set in self.actions.iter().filter_map(|action| action.set.as_deref()) { if !sets.contains(&set) { sets.push(set); } @@ -183,6 +182,9 @@ impl ActionList { if self.name_in_use(name) { return Err(ActionListError::NameTaken(name.to_owned())); } + if let Some(set) = &set { + self.record_set(set); + } self.actions.push(Action { set, ..Action::new(name, Vec::new()) }); self.touch(); Ok(self.actions.len() - 1) @@ -227,7 +229,7 @@ impl ActionList { Ok(()) } - /// Removes and returns the action at `index`. + /// Removes and returns the action at `index`; the set it leaves empty stays, in its place. pub fn delete_action(&mut self, index: usize) -> Result { if index >= self.actions.len() { return Err(ActionListError::NoSuchAction(index)); @@ -270,22 +272,29 @@ impl ActionList { } /// Puts the action at `index` into `set` (`None`: out of any set), as a drop into or out of a - /// set folder does. + /// set folder does. A new set goes at the end of the order; the set the action leaves stays, in + /// its place, even when it is now empty. pub fn assign_set(&mut self, index: usize, set: Option) -> Result<(), ActionListError> { - let target = self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?; + if index >= self.actions.len() { + return Err(ActionListError::NoSuchAction(index)); + } let set = match set { None => None, Some(set) if set.trim().is_empty() => return Err(ActionListError::EmptyName), Some(set) => Some(set.trim().to_owned()), }; - target.set = set; + if let Some(set) = &set { + self.record_set(set); + } + self.actions[index].set = set; self.touch(); Ok(()) } /// Moves step `step` of action `from` to position `to` of action `into` (the same action or /// another). Within one action `disabled` and `dialogs` follow [`moved_index`]; between - /// actions the step takes its include and dialog flags along. + /// actions the step takes its include and dialog flags along. A set never changes: one whose last + /// step moves away keeps its place. pub fn move_step(&mut self, from: usize, step: usize, into: usize, to: usize) -> Result<(), ActionListError> { let source = self.actions.get(from).ok_or(ActionListError::NoSuchAction(from))?; if step >= source.steps.len() { @@ -400,6 +409,17 @@ impl ActionList { Ok(()) } + /// Replaces the app's own options of the action at `index` ([`Action::options`]). Setting the options it holds + /// changes nothing, so the revision stays. + pub fn set_options(&mut self, index: usize, options: serde_json::Map) -> Result<(), ActionListError> { + let action = self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?; + if action.options != options { + action.options = options; + self.touch(); + } + Ok(()) + } + /// Appends a whole action and returns its index; an empty or taken name is refused. pub fn push(&mut self, action: Action) -> Result { if action.name.trim().is_empty() { @@ -408,6 +428,9 @@ impl ActionList { if self.name_in_use(&action.name) { return Err(ActionListError::NameTaken(action.name)); } + if let Some(set) = &action.set { + self.record_set(set); + } self.actions.push(action); self.touch(); Ok(self.actions.len() - 1) @@ -457,17 +480,57 @@ impl ActionList { Ok(()) } + /// Renames the set `set` to `name` (trimmed) in the order and in every member's `set`: [`ActionListError::EmptyName`] + /// for an empty name, [`ActionListError::NameTaken`] for a name another set has, [`ActionListError::NoSuchSet`] for an + /// unknown set. The same name succeeds and changes nothing. + pub fn rename_set(&mut self, set: &str, name: &str) -> Result<(), ActionListError> { + let name = name.trim(); + if name.is_empty() { + return Err(ActionListError::EmptyName); + } + let order: Vec = self.sets().into_iter().map(str::to_owned).collect(); + let at = order.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; + if name == set { + return Ok(()); + } + if order.iter().any(|each| each == name) { + return Err(ActionListError::NameTaken(name.to_owned())); + } + self.sets = order; + self.sets[at] = name.to_owned(); + for action in self.actions.iter_mut().filter(|action| action.set.as_deref() == Some(set)) { + action.set = Some(name.to_owned()); + } + self.touch(); + Ok(()) + } + + /// Removes the set `set` from the order and its actions from the list, and returns the actions in list order: + /// [`ActionListError::NoSuchSet`] for an unknown set. + pub fn delete_set(&mut self, set: &str) -> Result, ActionListError> { + if !self.sets().contains(&set) { + return Err(ActionListError::NoSuchSet(set.to_owned())); + } + let (removed, kept): (Vec, Vec) = + std::mem::take(&mut self.actions).into_iter().partition(|action| action.set.as_deref() == Some(set)); + self.actions = kept; + self.sets.retain(|each| each != set); + self.touch(); + Ok(removed) + } + /// Duplicates the set `set` under a unique name and returns that name; `shift` is as for - /// [`duplicate_action`](Self::duplicate_action). The copies of its actions go after its last - /// action; a set with none becomes an empty set after it. + /// [`duplicate_action`](Self::duplicate_action). The new set goes right after `set` in the order; + /// the copies of its actions go after its last action, and a set with none gives an empty set. pub fn duplicate_set(&mut self, set: &str, mut shift: impl FnMut(&mut ActionStep, usize, usize)) -> Result { + let mut order: Vec = self.sets().into_iter().map(str::to_owned).collect(); + let position = order.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; + let name = Names::new(order.iter().cloned()).claim(&format!("{set} copy")); + order.insert(position + 1, name.clone()); + self.sets = order; let members: Vec = (0..self.actions.len()).filter(|&i| self.actions[i].set.as_deref() == Some(set)).collect(); - let name = Names::new(self.sets().into_iter().map(str::to_owned)).claim(&format!("{set} copy")); - if members.is_empty() { - let position = self.sets.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; - self.sets.insert(position + 1, name.clone()); - } else { - let at = members[members.len() - 1] + 1; + if let Some(&last) = members.last() { + let at = last + 1; // Each copy's name is claimed before the next, so the copies never repeat one. let mut names = Names::of(&self.actions); for (offset, &source) in members.iter().enumerate() { @@ -543,6 +606,9 @@ impl ActionList { merged.ids.push((id.clone(), name.clone())); } action.name = name; + if let Some(set) = &action.set { + self.record_set(set); + } self.actions.push(action); merged.added.push(self.actions.len() - 1); } @@ -552,9 +618,7 @@ impl ActionList { } } for set in empty_sets { - if !self.sets().contains(&set.as_str()) { - self.sets.push(set); - } + self.record_set(&set); } self.touch(); merged @@ -699,6 +763,13 @@ impl ActionList { ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()) } + /// Puts `set` at the end of the set order when the order lacks it. + fn record_set(&mut self, set: &str) { + if !self.sets.iter().any(|each| each == set) { + self.sets.push(set.to_owned()); + } + } + /// Whether an action has `name`. fn name_in_use(&self, name: &str) -> bool { self.actions.iter().any(|action| action.name == name) diff --git a/crates/automation/src/actions/model.rs b/crates/automation/src/actions/model.rs index 247d9f4d1a..09b3b6df1b 100644 --- a/crates/automation/src/actions/model.rs +++ b/crates/automation/src/actions/model.rs @@ -161,6 +161,10 @@ pub struct Action { /// Written by an automation client: playback keeps that client's gate. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub automation: bool, + /// The app's own options for the action. The framework never reads them; every edit, duplicate, move, merge and + /// the file keep them. + #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] + pub options: serde_json::Map, } fn is_no_color(color: &ActionColor) -> bool { diff --git a/crates/automation/src/actions/tests.rs b/crates/automation/src/actions/tests.rs index 9e5bfc1e90..7bea5df8c7 100644 --- a/crates/automation/src/actions/tests.rs +++ b/crates/automation/src/actions/tests.rs @@ -271,3 +271,81 @@ fn action_player_charges_a_shared_budget_and_detects_loops() { } assert_eq!(deep.enter("more"), Err(PlaybackRefusal::TooDeep)); } + +// A set keeps its place as it gets its first action and loses its last; a duplicate goes right after its source; +// rename keeps the place and moves the members and refuses empty, taken and unknown names; delete returns the members +// in list order. +#[trial] +fn sets_keep_their_place_as_they_fill_empty_rename_and_go() { + let mut list = ActionList::new(); + for set in ["A", "B", "C"] { + list.new_set(set).unwrap(); + } + list.new_action("x", Some("B".into())).unwrap(); + assert_eq!(list.sets(), ["A", "B", "C"], "B keeps its place when it gets its first action"); + list.delete_action(0).unwrap(); + assert_eq!(list.sets(), ["A", "B", "C"], "B keeps its place when it loses its last"); + + assert_eq!(list.duplicate_set("A", |_, _, _| {}).unwrap(), "A copy"); + list.new_action("y", Some("B".into())).unwrap(); + assert_eq!(list.duplicate_set("B", |_, _, _| {}).unwrap(), "B copy"); + list.new_action("z", Some("B".into())).unwrap(); + assert_eq!(list.sets(), ["A", "A copy", "B", "B copy", "C"], "a copy follows its source, with or without actions"); + + let revision = list.revision(); + list.rename_set("B", "B").unwrap(); + assert_eq!(list.revision(), revision, "the same name changes nothing"); + assert_eq!(list.rename_set("B", " "), Err(ActionListError::EmptyName)); + assert_eq!(list.rename_set("B", "C"), Err(ActionListError::NameTaken("C".into()))); + assert_eq!(list.rename_set("Nope", "Z"), Err(ActionListError::NoSuchSet("Nope".into()))); + assert_eq!(list.revision(), revision, "a refused rename changes nothing"); + list.rename_set("B", " Beta ").unwrap(); + assert_eq!(list.sets(), ["A", "A copy", "Beta", "B copy", "C"]); + let members = list.actions().iter().filter(|action| action.set.as_deref() == Some("Beta")).count(); + assert_eq!(members, 2, "the members follow the rename"); + + let gone = list.delete_set("Beta").unwrap(); + assert_eq!(gone.iter().map(|action| action.name.as_str()).collect::>(), ["y", "z"]); + assert_eq!(list.sets(), ["A", "A copy", "B copy", "C"]); + assert_eq!(list.actions().len(), 1); + assert_eq!(list.delete_set("Beta"), Err(ActionListError::NoSuchSet("Beta".into()))); +} + +// An option of an action stays with it through a duplicate, a set duplicate, a step move, the file and a merge. +#[trial] +fn app_options_ride_with_an_action_through_edits_and_files() { + let mut base = action("A", &["a", "b"]); + base.set = Some("S".into()); + base.options.insert("key".into(), json!(3)); + let mut list = list_of(vec![base]); + list.duplicate_action(0, |_, _, _| {}).unwrap(); + list.duplicate_set("S", |_, _, _| {}).unwrap(); + list.move_step(0, 0, 0, 1).unwrap(); + assert_eq!(list.actions().len(), 4); + assert!(list.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); + + let text = list.to_file().to_json().unwrap(); + assert!(text.contains("\"options\"")); + let loaded = ActionList::from_file(ActionsFile::from_json(&text).unwrap()); + assert!(loaded.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); + let mut merged = ActionList::new(); + merged.merge_file(ActionsFile::from_json(&text).unwrap(), false, |_, _| {}); + assert!(merged.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); +} + +// An action's options are set in the list, kept through a duplicate and the file, and the same options or an unknown +// action change nothing. +#[trial] +fn an_actions_options_are_set_and_kept_through_a_duplicate_and_the_file() { + let mut list = list_of(vec![action("a", &["one"])]); + let options = json!({"key": "F5", "automaticAlignTo": "artboard"}).as_object().cloned().unwrap(); + list.set_options(0, options.clone()).unwrap(); + assert_eq!(list.action(0).unwrap().options, options); + let revision = list.revision(); + list.set_options(0, options.clone()).unwrap(); + assert_eq!(list.revision(), revision, "the options it holds change nothing"); + assert_eq!(list.set_options(7, serde_json::Map::new()), Err(ActionListError::NoSuchAction(7))); + let copy = list.duplicate_action(0, |_, _, _| {}).unwrap(); + assert_eq!(list.action(copy).unwrap().options, options, "a duplicate keeps them"); + assert_eq!(ActionList::from_file(list.to_file()).action(0).unwrap().options, options, "the file keeps them"); +} diff --git a/crates/automation/src/client.rs b/crates/automation/src/client.rs index d84125f58a..7d6ca67e72 100644 --- a/crates/automation/src/client.rs +++ b/crates/automation/src/client.rs @@ -1,6 +1,6 @@ //! A JSON-lines client for integration tests and CLIs. -use std::io::{BufRead, BufReader, Write}; +use std::io::{BufRead, BufReader, Read, Write}; use std::net::SocketAddr; use serde_json::{Value, json}; @@ -12,6 +12,12 @@ use crate::security::{AUTH_METHOD, IO_TIMEOUT}; /// server's own timeout error arrives before the client gives up. pub const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(REPLY_DEADLINE.as_secs() + 5); +/// How long [`ControlClient::connect`] waits for the connection: 800 ms, as the server is on loopback only. +pub const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(800); + +/// The longest reply line a client reads: 256 MiB. A longer one is an error and closes the connection. +pub const MAX_REPLY_BYTES: u64 = 256 << 20; + /// Why [`ControlClient::connect`] failed. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -47,20 +53,53 @@ impl ControlClient { self.broken } + /// Whether a call can be sent now: false when the connection is broken, the server closed it, + /// or it holds bytes no call asked for (a server that says why it closes), as no reply to the + /// next call could be read from it. Every call checks this before it sends and, when false, + /// closes the connection and fails with nothing sent; a caller reconnects instead. + pub fn is_usable(&self) -> bool { + if self.broken || !self.reader.buffer().is_empty() || self.stream.set_nonblocking(true).is_err() { + return false; + } + let probe = self.stream.peek(&mut [0]); + self.stream.set_nonblocking(false).is_ok() && probe.is_err_and(|e| e.kind() == std::io::ErrorKind::WouldBlock) + } + /// Connect (read timeout [`CALL_TIMEOUT`]), send /// `{"id": 1, "method": "auth", "params": {"token": token}}` and read one reply line; `Err` with /// the reply's `error` text as `Refused` when it isn't `ok`, or the I/O error's message as `Transport`. + /// A line the server wrote before the request (a refusal at accept) is the reply, and nothing is sent. pub fn connect(addr: SocketAddr, token: &str) -> Result { let io = |e: std::io::Error| ConnectError::Transport(e.to_string()); - let stream = std::net::TcpStream::connect(addr).map_err(io)?; - stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(io)?; - stream.set_write_timeout(Some(IO_TIMEOUT)).map_err(io)?; - let reader = BufReader::new(stream.try_clone().map_err(io)?); - let mut client = Self { stream, broken: false, reader, next_id: 2 }; - // `exchange` marks the client broken on a transport failure only, so an error reply is a refusal. - let auth = client.exchange(1, AUTH_METHOD, json!({"token": token})); - auth.map_err(|e| if client.broken { ConnectError::Transport(e) } else { ConnectError::Refused(e) })?; - Ok(client) + let stream = std::net::TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).map_err(io)?; + Self::over(stream).map_err(io)?.sign_in(token) + } + + /// A client over a connected `stream`, not yet signed in. + fn over(stream: std::net::TcpStream) -> std::io::Result { + stream.set_read_timeout(Some(CALL_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; + let reader = BufReader::new(stream.try_clone()?); + Ok(Self { stream, broken: false, reader, next_id: 2 }) + } + + /// Sends the sign-in and reads its answer. A server that refuses the connection at once (over its connection + /// limit) writes why before any request: that line answers the sign-in, which is then not sent, so only its + /// error counts. + fn sign_in(mut self, token: &str) -> Result { + let auth = if self.is_usable() { + self.round_trip(1, AUTH_METHOD, json!({"token": token}), None) + } else { + self.read_reply(1, None).and_then(|_| Err(Failure::Io("reply before the sign-in".into()))) + }; + match auth { + Ok(_) => Ok(self), + Err(Failure::Reply(why)) => Err(ConnectError::Refused(why)), + Err(Failure::Io(why)) => { + self.close(); + Err(ConnectError::Transport(why)) + } + } } /// Send `{"id": n, "method", "params"}` as one line (ids count up from 2) and read the reply @@ -68,36 +107,65 @@ impl ControlClient { /// `"ok": true`, `Err(error)` otherwise. After an I/O error or a timeout the connection is /// closed and every later call fails, so a late reply can't answer the wrong call. pub fn call(&mut self, method: &str, params: Value) -> Result { - let id = self.next_id; - self.next_id += 1; - self.exchange(id, method, params) + self.call_with(method, params, None) } - fn exchange(&mut self, id: u64, method: &str, params: Value) -> Result { - if self.broken { + /// As [`ControlClient::call`], but gives up with `Err("cancelled")` and closes the connection when `cancelled()` + /// turns true while it waits for the reply. + pub fn call_until(&mut self, method: &str, params: Value, cancelled: &dyn Fn() -> bool) -> Result { + self.call_with(method, params, Some(cancelled)) + } + + fn call_with(&mut self, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { + let id = self.next_id; + self.next_id += 1; + self.exchange(id, method, params, cancelled) + } + + fn exchange(&mut self, id: u64, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { + if !self.is_usable() { + self.close(); return Err("connection closed".into()); } - let result = self.round_trip(id, method, params); + let result = self.round_trip(id, method, params, cancelled); if matches!(result, Err(Failure::Io(_))) { - self.broken = true; - let _ = self.stream.shutdown(std::net::Shutdown::Both); + self.close(); } result.map_err(|f| match f { Failure::Io(e) | Failure::Reply(e) => e, }) } - fn round_trip(&mut self, id: u64, method: &str, params: Value) -> Result { + fn close(&mut self) { + self.broken = true; + let _ = self.stream.shutdown(std::net::Shutdown::Both); + } + + fn round_trip(&mut self, id: u64, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { let io = |e: std::io::Error| Failure::Io(e.to_string()); writeln!(self.stream, "{}", json!({"id": id, "method": method, "params": params})).map_err(io)?; self.stream.flush().map_err(io)?; + self.read_reply(id, cancelled) + } + + /// Reads reply lines until the one with `id`, or with a null id (the server's answer to an unparseable line or a + /// refused connection). + fn read_reply(&mut self, id: u64, cancelled: Option<&dyn Fn() -> bool>) -> Result { + let io = |e: std::io::Error| Failure::Io(e.to_string()); loop { + if let Some(cancelled) = cancelled { + self.wait_for_reply(cancelled)?; + } let mut line = String::new(); - if self.reader.read_line(&mut line).map_err(io)? == 0 { + let read = (&mut self.reader).take(MAX_REPLY_BYTES + 1).read_line(&mut line).map_err(io)?; + if read == 0 { return Err(Failure::Io("connection closed".into())); } + if read as u64 > MAX_REPLY_BYTES { + return Err(Failure::Io(format!("reply longer than {MAX_REPLY_BYTES} bytes"))); + } let mut reply: Value = serde_json::from_str(&line).map_err(|e| Failure::Io(format!("bad reply: {e}")))?; - // A reply to an earlier request (a null id is the server's answer to an unparseable line). + // A reply to an earlier request. if reply.get("id").is_some_and(|got| !got.is_null() && got != &json!(id)) { continue; } @@ -108,6 +176,36 @@ impl ControlClient { }; } } + + /// Waits until a reply line starts to arrive, asking `cancelled` between short reads, for at most + /// [`CALL_TIMEOUT`]. A cancel is a transport failure, so the connection closes and a late reply can't answer the + /// next call. + fn wait_for_reply(&self, cancelled: &dyn Fn() -> bool) -> Result<(), Failure> { + const POLL: std::time::Duration = std::time::Duration::from_millis(100); + if !self.reader.buffer().is_empty() { + return Ok(()); + } + let io = |e: std::io::Error| Failure::Io(e.to_string()); + let start = std::time::Instant::now(); + self.stream.set_read_timeout(Some(POLL)).map_err(io)?; + let outcome = loop { + match self.stream.peek(&mut [0]) { + Ok(_) => break Ok(()), + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { + if cancelled() { + break Err(Failure::Io("cancelled".into())); + } + if start.elapsed() >= CALL_TIMEOUT { + break Err(io(e)); + } + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => break Err(io(e)), + } + }; + self.stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(io)?; + outcome + } } /// Why a round trip failed: the transport (the connection is then unusable) or an error reply. diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 252841ea64..4718057ea8 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -37,3 +37,96 @@ fn replies_are_matched_by_id() { assert!(client.call("b", json!({})).is_err(), "the closed connection fails the call"); assert_eq!(client.call("c", json!({})), Err("connection closed".to_string()), "a failed client stays closed"); } + +// A cancelled wait gives up on a reply that never comes and closes the connection, so a late reply can't answer a +// later call. +#[trial] +fn a_cancelled_call_stops_waiting_and_closes_the_connection() { + use std::io::{BufRead, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (done, wait) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + // The call is read and never answered while the client waits. + line.clear(); + reader.read_line(&mut line).unwrap(); + wait.recv().unwrap(); + writeln!(out, "{}", json!({"id": 2, "ok": true, "result": "late"})).ok(); + }); + let mut client = ControlClient::connect(addr, TOKEN).unwrap(); + let asked = std::cell::Cell::new(0); + let cancelled = || { + asked.set(asked.get() + 1); + asked.get() > 1 + }; + assert_eq!(client.call_until("slow", json!({}), &cancelled), Err("cancelled".to_string())); + assert!(client.is_broken(), "a cancelled call closes the connection"); + done.send(()).unwrap(); + server.join().unwrap(); + assert_eq!(client.call("next", json!({})), Err("connection closed".to_string()), "the late reply answers nothing"); +} + +// A connection the server closed, or one holding a line no call asked for, is unusable: the next +// call sends nothing and fails, so the caller reconnects instead of reading the wrong answer. +#[trial] +fn an_unasked_line_makes_the_connection_unusable_before_sending() { + use std::io::{BufRead, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (said, wait) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + wait.recv().unwrap(); + writeln!(out, "{}", json!({"id": null, "ok": false, "error": "idle connection closed"})).unwrap(); + out.flush().unwrap(); + // The client's close shows as an end of input or, with the unread line, a reset. + line.clear(); + reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) + }); + 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)); + } + 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"); + assert_eq!(server.join().unwrap(), None, "the call sent nothing"); +} + +// A server that refuses a connection at accept writes why and closes: the sign-in reads that waiting line as its +// answer, so the caller learns the reason, and sends nothing. +#[trial] +fn a_refusal_waiting_at_sign_in_is_the_reason_connect_gives() { + use std::io::{BufRead, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + writeln!(out, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})).unwrap(); + out.flush().unwrap(); + let mut line = String::new(); + reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) + }); + let stream = std::net::TcpStream::connect(addr).unwrap(); + stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); + assert!(stream.peek(&mut [0]).unwrap() > 0, "the refusal is waiting before the sign-in"); + let signed = ControlClient::over(stream).unwrap().sign_in(TOKEN); + assert_eq!(signed.err(), Some(ConnectError::Refused("connection limit reached".into()))); + assert_eq!(server.join().unwrap(), None, "the sign-in sent nothing"); +} diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index cc1e37c812..b1c005dadf 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -14,13 +14,13 @@ //! two happened, once, between the UI thread and the transport. use std::sync::mpsc::{Receiver, Sender}; -use web_time::Instant; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use serde_json::{Value, json}; +use web_time::Instant; -use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotRequest, screenshot_reply}; +use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotParams, ScreenshotRequest, screenshot_reply}; use crate::synthetic::TARGET_CHANGED; /// A reply: the JSON object the transport writes as one line. @@ -112,13 +112,16 @@ pub enum Reply { /// Reply with this JSON now. Done(Value), /// A `ui.screenshot`: admit `token` to the queue; `path` is where the app's write authority - /// puts the PNG, `None` inlines it as base64 in the reply. + /// puts the PNG, `None` inlines it as base64 in the reply; `region` is refused at admission + /// when it lies outside the window. #[non_exhaustive] Screenshot { /// Identifies the capture; must differ from every pending token. token: u64, /// File to write the PNG to, or `None` to inline it. path: Option, + /// The part of the window to capture, in points; `None` captures the whole window. + region: Option, /// The viewport to capture. viewport: egui::ViewportId, }, @@ -138,10 +141,10 @@ impl Reply { Reply::AccessTree } - /// A `ui.screenshot` reply for `token` of `viewport`, writing the PNG to `path` or inlining it - /// when `None`. - pub fn screenshot(token: u64, path: Option, viewport: egui::ViewportId) -> Self { - Self::Screenshot { token, path, viewport } + /// A `ui.screenshot` reply for `token` of `viewport` with what [`ScreenshotParams::from_params`] read: the PNG + /// goes to `params.path` or is inlined when `None`, and shows `params.region` or the whole window. + pub fn screenshot(token: u64, params: ScreenshotParams, viewport: egui::ViewportId) -> Self { + Self::Screenshot { token, path: params.path, region: params.region, viewport } } /// `Done` with the [`result_reply`] of a method's result. @@ -207,8 +210,9 @@ impl ControlChannel { Reply::AfterInput => self.input_waiters.push(reply), Reply::AfterJob(job) => self.job_waiters.push((job, reply)), Reply::AccessTree => self.tree_waiters.push(reply), - Reply::Screenshot { token, path, viewport } => { - if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) { + Reply::Screenshot { token, path, region, viewport } => { + let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms }; + if let Err((reply, e)) = self.captures.admit(request, motion::now()) { let _ = reply.send(json!({"ok": false, "error": e})); } } @@ -238,8 +242,10 @@ impl ControlChannel { /// `input cancelled` when the host withdrew queued input ([`TARGET_CHANGED`]), with success /// once nothing is queued or in flight. Call it once per pass, at the end of the pass (after its /// UI ran): the step that pass consumed counts as run, so the reply goes out with that pass - /// ([`WindowHost::injected_idle_at_pass_end`]). Called between passes, it waits for the pass. + /// ([`WindowHost::injected_idle_at_pass_end`]). Called between passes, it waits for the pass. It also has the host + /// keep its access trees, which `control` targets and `ui.find` read. pub fn poll_input(&mut self, host: &WindowHost) { + host.keep_access_trees(); if host.take_injected_withdrawn() { self.input_cancelled(TARGET_CHANGED); } else if host.injected_idle_at_pass_end() { @@ -255,7 +261,8 @@ impl ControlChannel { return; } // `ui.accessTree` takes no window: it reads the main window's tree. - let Some(update) = WindowHost::of(ctx).access_tree(egui::ViewportId::ROOT) else { return }; + let Some(tree) = WindowHost::of(ctx).access_tree(egui::ViewportId::ROOT) else { return }; + let update = tree.update(); let nodes: Vec = update .nodes .iter() @@ -313,7 +320,7 @@ impl ControlChannel { pub fn finish_captures(&mut self, finished: Vec, write: &mut crate::screenshot::PngWriter<'_>) { for f in finished { let reply = match f.result { - Ok(image) => screenshot_reply(f.token, image, f.path.as_deref(), write), + Ok(image) => screenshot_reply(f.token, image, f.region, f.geometry, f.path.as_deref(), write), Err(e) => json!({"ok": false, "error": e}), }; if let Some(tx) = f.reply { diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs index 62fc0b268b..398c917c57 100644 --- a/crates/automation/src/dialogs.rs +++ b/crates/automation/src/dialogs.rs @@ -12,6 +12,9 @@ use serde_json::{Value, json}; use crate::protocol::Params; +/// The most `fields` one `ui.dialog.set` call takes. +pub const MAX_DIALOG_FIELDS: usize = 256; + /// The open dialogs, the top one last: `{id, parent, key, fields}`, `null` for a missing parent, key or fields. Ids /// are 64-bit hashes, so they are listed as decimal strings, which every JSON reader keeps exact. pub fn inspect(host: &DialogHost) -> Value { @@ -30,14 +33,15 @@ pub fn inspect(host: &DialogHost) -> Value { /// Runs a `ui.dialog.*` method on `host`; `None` when `method` is not one of them. /// -/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]). +/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field, +/// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]). /// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field /// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it. /// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape /// answer gives that answer, with its tag; any other dialog closes with its children with Cancel. pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option> { let fields: &[&str] = match method { - "ui.dialog.set" => &["dialog", "field", "value"], + "ui.dialog.set" => &["dialog", "field", "value", "fields"], "ui.dialog.confirm" => &["dialog", "choice"], "ui.dialog.cancel" => &["dialog"], _ => return None, @@ -50,10 +54,18 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field let read = Params(¶ms); let id = dialog_id(host, ¶ms)?; match method { - "ui.dialog.set" => { - let field = read.str_field("field")?.ok_or("missing `field`")?; - host.set_json_field(ctx, id, field, params.get("value").cloned().unwrap_or(Value::Null))?; - } + "ui.dialog.set" => match params.get("fields") { + Some(list) => { + if params.get("field").is_some() || params.get("value").is_some() { + return Err("`fields` takes the place of `field` and `value`".to_owned()); + } + host.set_json_fields(ctx, id, &field_list(list)?)?; + } + None => { + let field = read.str_field("field")?.ok_or("missing `field`")?; + host.set_json_field(ctx, id, field, params.get("value").cloned().unwrap_or(Value::Null))?; + } + }, "ui.dialog.confirm" => { if let Some(choice) = params.get("choice") { host.set_json_field(ctx, id, "choice", choice.clone())?; @@ -81,6 +93,21 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field Ok(Value::Null) } +/// The `(field, value)` pairs of a `fields` list, checked whole before anything is set; a missing `value` is `null`. +fn field_list(list: &Value) -> Result, String> { + let items = list.as_array().ok_or("`fields` is not a list")?; + if items.len() > MAX_DIALOG_FIELDS { + return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len())); + } + items + .iter() + .map(|item| { + let field = item.get("field").and_then(Value::as_str).ok_or("an item of `fields` has no string `field`")?; + Ok((field.to_owned(), item.get("value").cloned().unwrap_or(Value::Null))) + }) + .collect() +} + /// The open dialog `params.dialog` names: the id `inspect` lists, as a decimal string or a number, or `"top"` for the /// top dialog of the stack. pub fn dialog_id(host: &DialogHost, params: &Value) -> Result { diff --git a/crates/automation/src/dock.rs b/crates/automation/src/dock.rs new file mode 100644 index 0000000000..4b8bcbcd49 --- /dev/null +++ b/crates/automation/src/dock.rs @@ -0,0 +1,47 @@ +//! `ui.dock.apply`: one dock action applied to the app's workspace, and the workspace's `ui.inspect` listing. + +use std::hash::Hash; + +use craft_behavior::dock::{Action, Workspace}; +use craft_ui::docking::PanelSpecs; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// `ui.dock.apply {action}`: deserializes one dock action and applies it to `workspace` with the permissions `specs` +/// gives, as the dock area does. It returns `Ok({applied: [...]})`, the panels the action closed, in group order; an +/// error is the dock error's text. `None` for any other method. +pub fn dock_method( + workspace: &mut Workspace

, + specs: &impl PanelSpecs

, + locked: bool, + method: &str, + params: &Value, +) -> Option> { + if method != "ui.dock.apply" { + return None; + } + Some(apply(workspace, specs, locked, params)) +} + +fn apply( + workspace: &mut Workspace

, + specs: &impl PanelSpecs

, + locked: bool, + params: &Value, +) -> Result { + let params = Params(params).only(None, &["action"])?; + let action = params.get("action").cloned().ok_or("missing `action`")?; + let action: Action

= serde_json::from_value(action).map_err(|e| format!("`action` is not a dock action: {e}"))?; + let applied = workspace.apply(action, locked, |panel| specs.permissions(panel)).map_err(|e| e.to_string())?; + let applied = serde_json::to_value(applied).map_err(|e| e.to_string())?; + Ok(json!({ "applied": applied })) +} + +/// The `dock` field of the app's one `ui.inspect`: the workspace as JSON. +pub fn inspect(workspace: &Workspace

) -> Value { + // A panel id that cannot be written lists the dock as null rather than failing the whole `ui.inspect`. + serde_json::to_value(workspace).unwrap_or(Value::Null) +} diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs new file mode 100644 index 0000000000..0d97d9d8e3 --- /dev/null +++ b/crates/automation/src/files.rs @@ -0,0 +1,50 @@ +//! `ui.pick`: answers the next file picker of a running app. + +use std::fmt::Display; +use std::path::PathBuf; + +use craft_host::{FileError, Files, Picked}; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// The fields of `ui.pick`, of which a request names exactly one. +const FIELDS: [&str; 4] = ["files", "folder", "save", "cancel"]; + +/// `None` for any method other than `ui.pick`. `ui.pick` takes exactly one of `{files: [path, ..]}`, `{folder: path}`, +/// `{save: path}` or `{cancel: true}` and answers through `Files::answer_next` with `Picked::Paths` or `Cancelled`. +/// Paths are taken as given; the service settles them as it would a panel's answer. +pub fn pick_method(files: &dyn Files, method: &str, params: &Value) -> Option> { + (method == "ui.pick").then(|| pick(files, params)) +} + +fn pick(files: &dyn Files, params: &Value) -> Result { + let params = Params(params).only(None, &FIELDS)?; + let read = Params(¶ms); + let given: Vec<&str> = FIELDS.iter().copied().filter(|field| params.get(*field).is_some()).collect(); + let [field] = given.as_slice() else { return Err(refused("give exactly one field")) }; + let picked = match *field { + "files" => Picked::Paths(paths(params.get("files"))?), + "cancel" => match read.bool_field("cancel").map_err(refused)? { + Some(true) => Picked::Cancelled, + _ => return Err(refused("cancel must be true")), + }, + one => Picked::Paths(vec![PathBuf::from(read.str_field(one).map_err(refused)?.ok_or_else(|| refused(format!("missing `{one}`")))?)]), + }; + files.answer_next(picked).map_err(|e| match e { + FileError::Unsupported => "this window's file service takes no automated answers".to_owned(), + other => other.to_string(), + })?; + Ok(json!({"answered": "next"})) +} + +/// `files` as a non-empty list of paths. +fn paths(files: Option<&Value>) -> Result, String> { + let list = files.and_then(Value::as_array).filter(|list| !list.is_empty()); + let paths = list.and_then(|list| list.iter().map(|path| path.as_str().map(PathBuf::from)).collect::>>()); + paths.ok_or_else(|| refused("files must be a non-empty array of path strings")) +} + +fn refused(why: impl Display) -> String { + format!("{why}; ui.pick takes exactly one of: {}", FIELDS.join(", ")) +} diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 853e3cd03f..97a14d3103 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -3,7 +3,10 @@ //! Drive a running Craft app from tests, agents and the CLI, and record and play actions. //! //! [`actions`] and [`ui::actions`] build on every target: the recorded-action list, its player -//! and the Actions panel; so do the agent settings in [`agents`]. The rest is desktop only. +//! and the Actions panel; so do the agent settings in [`agents`] and, with `ui`, the control +//! channel, its screenshots, synthetic input and the access-tree lookups (a web page feeds +//! [`control::ControlChannel`] from its own request queue). The server, client, token files, +//! profiler and trace are desktop only. //! //! A transport thread ([`server`], or a channel in tests) turns each JSON line into a //! [`control::ControlRequest`]; the UI thread drains them between frames through @@ -21,12 +24,18 @@ pub mod agents; #[cfg(feature = "ui")] pub mod ui; +#[cfg(feature = "ui")] +pub mod access; #[cfg(not(target_arch = "wasm32"))] pub mod args; #[cfg(feature = "ui")] pub mod control; -#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +#[cfg(feature = "ui")] pub mod dialogs; +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod dock; +#[cfg(feature = "ui")] +pub mod files; #[cfg(not(target_arch = "wasm32"))] pub mod profiler; pub mod protocol; @@ -38,17 +47,18 @@ pub mod security; pub mod synthetic; #[cfg(not(target_arch = "wasm32"))] pub mod trace; +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod window; #[cfg(not(target_arch = "wasm32"))] pub mod client; #[cfg(all(feature = "ui", not(target_arch = "wasm32")))] pub mod server; -#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +#[cfg(feature = "ui")] pub use control::{ControlChannel, ControlRequest, ControlResponse, Dispatch, Reply}; -#[cfg(not(target_arch = "wasm32"))] pub use protocol::REPLY_DEADLINE; -#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +#[cfg(feature = "ui")] pub use screenshot::Captures; #[cfg(not(target_arch = "wasm32"))] pub use security::AutomationError; diff --git a/crates/automation/src/screenshot.rs b/crates/automation/src/screenshot.rs index 292ecab600..2b37383a8e 100644 --- a/crates/automation/src/screenshot.rs +++ b/crates/automation/src/screenshot.rs @@ -1,7 +1,8 @@ //! `ui.screenshot`: bounded, cancellable capture requests over [`WindowHost::screenshot`]. //! //! The slot correlates one capture with one image. This queue owns what the slot leaves to the -//! app: request identity (token, output path, reply, the viewport it shoots), deadlines and +//! app: request identity (token, output path, reply, the viewport it shoots and the region of it, +//! refused at admission when outside the window and cropped in [`screenshot_reply`]), deadlines and //! settling, the admission budget ([`MAX_PENDING`] requests, [`MAX_IMAGE_BYTES`] per image, //! [`MAX_TOTAL_BYTES`] in all), the document identity fixed at admission, each viewport's geometry //! epoch recorded at issue so an image is saved only for the layout it was rendered from (a size, @@ -18,13 +19,16 @@ use std::collections::HashMap; use std::sync::Arc; use std::sync::mpsc::Sender; -use web_time::{Duration, Instant}; +use std::time::Duration; use base64::Engine as _; use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost}; -use egui::{ColorImage, ViewportId}; +use egui::{ColorImage, Rect, ViewportId}; +use serde_json::Value; +use web_time::Instant; use crate::control::ControlResponse; +use crate::protocol::Params; /// Requests outstanding at once (issued, completed, waiting for geometry or waiting to be issued). pub const MAX_PENDING: usize = 4; @@ -146,6 +150,7 @@ pub struct PendingCapture { token: u64, viewport: ViewportId, path: Option, + region: Option, reply: Option>, deadline: Instant, ready_at: Instant, @@ -178,6 +183,10 @@ pub struct Finished { pub token: u64, /// File to write the PNG to; `None` inlines it in the reply. pub path: Option, + /// The part of the window to crop the image to, in points; `None` keeps the whole window. + pub region: Option, + /// The layout the image was captured from; the crop and the reply's `pixels_per_point` read it. + pub geometry: CaptureGeometry, /// Where to send the answer. pub reply: Option>, /// The captured image, or the error text for the reply. @@ -185,9 +194,17 @@ pub struct Finished { } impl Finished { - /// A finished request for `token`: `result` answers `reply`, and an image is written to `path` when given. - pub fn new(token: u64, path: Option, reply: Option>, result: Result, String>) -> Self { - Self { token, path, reply, result } + /// A finished request for `token`: `result` answers `reply`, and an image is written to `path` when given, + /// cropped to `region` as `geometry` scales it. + pub fn new( + token: u64, + path: Option, + region: Option, + geometry: CaptureGeometry, + reply: Option>, + result: Result, String>, + ) -> Self { + Self { token, path, region, geometry, reply, result } } } @@ -198,6 +215,8 @@ pub struct ScreenshotRequest { pub token: u64, /// Where to write the PNG, when the reply is a file. pub path: Option, + /// The part of the window to capture, in points; `None` captures the whole window. + pub region: Option, /// The viewport to capture. pub viewport: ViewportId, /// Where the reply goes. @@ -209,9 +228,9 @@ pub struct ScreenshotRequest { } impl ScreenshotRequest { - /// A request for `viewport` answered on `reply`: no file, no document, no settle delay. + /// A request for the whole of `viewport` answered on `reply`: no file, no document, no settle delay. pub fn new(token: u64, viewport: ViewportId, reply: Sender) -> Self { - Self { token, path: None, viewport, reply, document: None, settle_ms: 0.0 } + Self { token, path: None, region: None, viewport, reply, document: None, settle_ms: 0.0 } } } @@ -220,6 +239,7 @@ struct WaitingAdmit { token: u64, viewport: ViewportId, path: Option, + region: Option, reply: Sender, deadline: Instant, settle_ms: f64, @@ -312,17 +332,19 @@ impl Captures { /// `the viewport is not capturable ({w}×{h} points at {ppp} px/pt, texture side {side})`, /// `a {N} MiB screenshot is over the {MAX_IMAGE_BYTES / 1 MiB} MiB per-image limit` (`N` the /// expected bytes / 1 MiB, integer division), or - /// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`. + /// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`, or + /// `screenshot {token} failed: the region must lie inside the {w}×{h}-point window`. The budget is reserved for + /// the whole window, region or not: the slot retains the whole image until it is cropped. /// While the viewport's geometry is not recorded the request waits. pub fn admit(&mut self, request: ScreenshotRequest, now: Instant) -> Result<(), (Sender, String)> { - let ScreenshotRequest { token, path, viewport, reply, document, settle_ms } = request; + let ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms } = request; if self.records.iter().any(|r| r.token == token) || self.waiting.iter().any(|w| w.token == token) { return Err((reply, format!("screenshot token {token} is already pending"))); } if self.pending() >= MAX_PENDING { return Err((reply, format!("too many screenshots pending (at most {MAX_PENDING})"))); } - let request = WaitingAdmit { token, viewport, path, reply, deadline: now + DEADLINE, settle_ms, document }; + let request = WaitingAdmit { token, viewport, path, region, reply, deadline: now + DEADLINE, settle_ms, document }; match self.windows.get(&viewport).copied() { None => { self.waiting.push(request); @@ -335,7 +357,7 @@ impl Captures { /// Queues `request` at `geometry` and `epoch`, what its viewport's window recorded. fn admit_with_geometry(&mut self, request: WaitingAdmit, geometry: CaptureGeometry, epoch: u64) -> Result<(), (Sender, String)> { - let WaitingAdmit { token, viewport, path, reply, deadline, settle_ms, document } = request; + let WaitingAdmit { token, viewport, path, region, reply, deadline, settle_ms, document } = request; // The request's clock started when it arrived. let arrived = deadline - DEADLINE; if self.records.iter().any(|r| r.token == token) { @@ -348,6 +370,9 @@ impl Captures { Ok(bytes) => bytes, Err(e) => return Err((reply, e)), }; + if let Err(e) = check_region(token, region, &geometry) { + return Err((reply, e)); + } if let Err(e) = aggregate_budget(self.reserved_bytes(), expected) { return Err((reply, e)); } @@ -357,6 +382,7 @@ impl Captures { token, viewport, path, + region, reply: Some(reply), deadline, ready_at: arrived + Duration::from_secs_f64(settle / 1000.0), @@ -538,6 +564,9 @@ impl Captures { finished.push(Finished { token: w.token, path: w.path, + region: w.region, + // No geometry was recorded for a waiting request; the result is an error, so nothing reads it. + geometry: CaptureGeometry::new([0.0, 0.0], 0), reply: Some(w.reply), result: Err(format!("screenshot {} cancelled: {reason}", w.token)), }); @@ -549,6 +578,8 @@ impl Captures { finished.push(Finished { token: r.token, path: r.path.take(), + region: r.region, + geometry: r.geometry, reply: r.reply.take(), result: Err(format!("screenshot {} cancelled: {reason}", r.token)), }); @@ -580,11 +611,23 @@ fn aggregate_budget(others: usize, expected: usize) -> Result<(), String> { Ok(()) } +/// Whether `region` lies inside the window of `geometry`: the request is refused otherwise, never cropped to a +/// smaller image than it asked for. `None` (the whole window) always fits. +fn check_region(token: u64, region: Option, geometry: &CaptureGeometry) -> Result<(), String> { + let Some(region) = region else { return Ok(()) }; + let [width, height] = geometry.size_points; + if region.min.x >= 0.0 && region.min.y >= 0.0 && region.max.x <= width && region.max.y <= height { + return Ok(()); + } + Err(format!("screenshot {token} failed: the region must lie inside the {width}×{height}-point window")) +} + /// Finalise a request at a new geometry: recheck the per-image and aggregate limits (excluding -/// its old reservation), take the new reservation and restart settling. +/// its old reservation) and that its region still fits, take the new reservation and restart settling. fn revalidate_reservation(r: &mut PendingCapture, others: usize, geometry: CaptureGeometry, epoch: u64) -> Result<(), String> { let expected = image_budget(&geometry)?; aggregate_budget(others, expected)?; + check_region(r.token, r.region, &geometry)?; r.reserved_bytes = expected; r.geometry = geometry; r.epoch = epoch; @@ -597,7 +640,7 @@ fn finish(r: &mut PendingCapture, result: Result, String>) -> Fi if let Some(slot) = r.slot.take() { slot.cancel(); } - Finished { token: r.token, path: r.path.take(), reply: r.reply.take(), result } + Finished { token: r.token, path: r.path.take(), region: r.region, geometry: r.geometry, reply: r.reply.take(), result } } /// The returned image must be the issued viewport (within a pixel) or a uniform renderer fit @@ -678,40 +721,127 @@ pub fn encode_png(width: usize, height: usize, rgba: &[u8]) -> Result, S /// authorized workspace. `Err` is the reply's error text. pub type PngWriter<'a> = dyn FnMut(&str, &[u8]) -> Result<(), String> + 'a; -/// The reply for a finished image: -/// - an image over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows): +/// A validated `ui.screenshot`: where the PNG goes and which part of the window it shows. +#[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct ScreenshotParams { + /// File to write the PNG to, or `None` to inline it. + pub path: Option, + /// The part of the window to capture as `[x0, y0, x1, y1]` in points, finite and ordered; `None` captures the + /// whole window. + pub region: Option, +} + +impl ScreenshotParams { + /// `{path?, region?}`, no other fields. `path` is a string; `region` is `[x0, y0, x1, y1]` in points, four finite + /// numbers with `x0 < x1` and `y0 < y1`: ``"region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and + /// y0 < y1"`` otherwise. Whether it lies inside the window is checked at admission, against the window's geometry. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["path", "region"])?; + let p = Params(&p); + let path = p.str_field("path")?.map(str::to_owned); + let region = p.0.get("region").map(region_param).transpose()?; + Ok(ScreenshotParams { path, region }) + } +} + +/// `region`: `[x0, y0, x1, y1]`, finite and ordered. +fn region_param(region: &Value) -> Result { + const SHAPE: &str = "region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and y0 < y1"; + let number = |v: &Value| v.as_f64().map(|n| n as f32).filter(|n| n.is_finite()); + let corners = match region.as_array().map(Vec::as_slice) { + Some([x0, y0, x1, y1]) => number(x0).zip(number(y0)).zip(number(x1).zip(number(y1))), + _ => None, + }; + corners + .filter(|((x0, y0), (x1, y1))| x0 < x1 && y0 < y1) + .map(|((x0, y0), (x1, y1))| Rect::from_min_max(egui::pos2(x0, y0), egui::pos2(x1, y1))) + .ok_or_else(|| SHAPE.into()) +} + +/// The pixel columns and rows `[x0, y0, x1, y1)` of `region` in an image of `size` captured at `geometry`. The image +/// scale is `size / geometry.size_points`, never `pixels_per_point`: a renderer that fitted the surface to its +/// texture side returns a smaller image of the same layout. Edges round to the nearest pixel and are clamped to the +/// image; `None` when nothing of the region is left or the geometry has no area. +fn crop_pixels(region: Rect, geometry: &CaptureGeometry, size: [usize; 2]) -> Option<[usize; 4]> { + let [width, height] = geometry.size_points; + if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) { + return None; + } + let (sx, sy) = (size[0] as f32 / width, size[1] as f32 / height); + // `as usize` saturates: a negative or NaN edge is 0, an edge past the image is clamped below. + let px = |v: f32, scale: f32, max: usize| ((v * scale).round() as usize).min(max); + let [x0, x1] = [px(region.min.x, sx, size[0]), px(region.max.x, sx, size[0])]; + let [y0, y1] = [px(region.min.y, sy, size[1]), px(region.max.y, sy, size[1])]; + (x0 < x1 && y0 < y1).then_some([x0, y0, x1, y1]) +} + +/// The reply for a finished image, cropped to `region` (in points; `None` keeps the whole image) at the scale of the +/// image to `geometry`, the layout it was captured from: +/// - a region with no pixels left in the image: +/// `{"ok": false, "error": "screenshot {token} failed: the region has no pixels in the captured image"}`; +/// - a crop over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows): /// `{"ok": false, "error": "screenshot {token} failed: the image exceeds the {MAX_IMAGE_BYTES / 1 MiB} MiB encode budget"}`; -/// - no `path`: `{"ok": true, "result": {"base64": , "mime": "image/png", "width", "height"}}`, -/// with no size limit beyond the encode budget; +/// - no `path`: `{"ok": true, "result": {"base64": , "mime": "image/png", "width", "height", +/// "pixels_per_point"}}`, with no size limit beyond the encode budget; /// - a `path`: the PNG goes to `write(path, bytes)`, the app's file authority (limited to its /// authorized workspace), and the reply is -/// `{"ok": true, "result": {"path", "width", "height"}}`; +/// `{"ok": true, "result": {"path", "width", "height", "pixels_per_point"}}`; /// - an encode or write error `e`: `{"ok": false, "error": e}`. /// +/// `width` and `height` are the crop's pixels; `pixels_per_point` is `geometry`'s, the window's scale. /// Flatten the pixels to RGBA and drop the image before encoding, so the two copies don't overlap. -pub fn screenshot_reply(token: u64, image: Arc, path: Option<&str>, write: &mut PngWriter<'_>) -> ControlResponse { +pub fn screenshot_reply( + token: u64, + image: Arc, + region: Option, + geometry: CaptureGeometry, + path: Option<&str>, + write: &mut PngWriter<'_>, +) -> ControlResponse { let [w, h] = image.size; - let Some(bytes) = w.checked_mul(h).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else { + let crop = match region { + None => Some([0, 0, w, h]), + Some(region) => crop_pixels(region, &geometry, [w, h]), + }; + let Some([x0, y0, x1, y1]) = crop.filter(|[x0, y0, x1, y1]| x0 < x1 && y0 < y1) else { + return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the region has no pixels in the captured image")}); + }; + let (cw, ch) = (x1 - x0, y1 - y0); + let Some(bytes) = cw.checked_mul(ch).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else { return serde_json::json!({ "ok": false, "error": format!("screenshot {token} failed: the image exceeds the {} MiB encode budget", MAX_IMAGE_BYTES / (1 << 20)), }); }; let mut rgba = Vec::with_capacity(bytes); - rgba.extend(image.pixels.iter().flat_map(|c| c.to_array())); + for y in y0..y1 { + let row = y.checked_mul(w).and_then(|start| image.pixels.get(start + x0..start + x1)); + let Some(row) = row else { + return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the image has fewer pixels than its size")}); + }; + rgba.extend(row.iter().flat_map(|c| c.to_array())); + } drop(image); - let png = match encode_png(w, h, &rgba) { + let png = match encode_png(cw, ch, &rgba) { Ok(png) => png, Err(e) => return serde_json::json!({"ok": false, "error": e}), }; + let ppp = geometry.pixels_per_point; let Some(path) = path else { return serde_json::json!({ "ok": true, - "result": {"base64": base64::engine::general_purpose::STANDARD.encode(png), "mime": "image/png", "width": w, "height": h}, + "result": { + "base64": base64::engine::general_purpose::STANDARD.encode(png), + "mime": "image/png", + "width": cw, + "height": ch, + "pixels_per_point": ppp, + }, }); }; match write(path, &png) { - Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": w, "height": h}}), + Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": cw, "height": ch, "pixels_per_point": ppp}}), Err(e) => serde_json::json!({"ok": false, "error": e}), } } diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index b294c15ddf..259d2f3cb2 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -271,11 +271,15 @@ fn token_conflict() -> AutomationError { AutomationError::BadRequest("use either a control token or a control token file, not both".into()) } +/// The most a Windows token file read takes: a token, its newline and room for stray whitespace. +#[cfg(windows)] +const TOKEN_FILE_MAX_BYTES: u64 = 4096; + /// Validates what was opened, not just the name: the file must be a regular file that no other /// local principal can read, so a group- or world-readable token is refused rather than trusted. fn read_token_file(path: &Path) -> Result { let io = |e: std::io::Error| AutomationError::Io(format!("{}: {e}", path.display())); - let mut file = std::fs::File::open(path).map_err(io)?; + let file = std::fs::File::open(path).map_err(io)?; let meta = file.metadata().map_err(io)?; if !meta.is_file() { return Err(AutomationError::Io(format!("{}: control token file is not a regular file", path.display()))); @@ -291,7 +295,25 @@ fn read_token_file(path: &Path) -> Result { ))); } } - let token = std::io::read_to_string(&mut file).map_err(io)?; + // A Windows file inherits its folder's access list, so the owner and the access list are read with the contents + // through one handle: nothing swapped in at the path between the check and the read gets through. + + #[cfg(windows)] + let token = { + use craft_platform::owner_only; + drop(file); + let me = owner_only::current_user_sid().map_err(io)?; + let (sddl, bytes) = owner_only::read_with_sddl(path, TOKEN_FILE_MAX_BYTES).map_err(io)?; + if let Some(problem) = owner_only::foreign_access(&sddl, &me) { + return Err(AutomationError::Io(format!( + "{}: control token file can be reached by others: {problem}; restrict it to its owner", + path.display() + ))); + } + String::from_utf8(bytes).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))? + }; + #[cfg(not(windows))] + let token = std::io::read_to_string(&file).map_err(io)?; let token = token.trim().to_owned(); validate_token(&token)?; Ok(token) @@ -309,6 +331,17 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { options.mode(0o600); } let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; + // On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token + // is written, and a file that cannot be restricted is removed rather than left for the token to go into later. + #[cfg(windows)] + { + use craft_platform::owner_only; + if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) { + drop(file); + let _ = std::fs::remove_file(path); + return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display()))); + } + } writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } @@ -317,10 +350,12 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { /// validated. Neither given: a generated token. A `token_file` that exists is read: it must be a /// regular file (`I/O: : control token file is not a regular file`) and on Unix have no /// group or other permission bits (`I/O: : control token file is readable by group or -/// others (mode {mode & 0o777:o}); restrict it to its owner (e.g. chmod 600)`), and its trimmed -/// content is validated. A missing one is created with a generated token (parent directories -/// created, `create_new`, mode 0600 on Unix, the token and a newline); losing that create race to -/// another process reads the winner's file instead. +/// others (mode {mode & 0o777:o}); restrict it to its owner (e.g. chmod 600)`), on Windows be +/// owned by the user with an access list of the user and SYSTEM only (`I/O: : control token +/// file can be reached by others: ; restrict it to its owner`), and its trimmed content is +/// validated. A missing one is created with a generated token (parent directories created, +/// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a +/// newline); losing that create race to another process reads the winner's file instead. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { if supplied.is_some() && token_file.is_some() { return Err(token_conflict()); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 875d84ed72..c6808156d7 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -1,7 +1,7 @@ //! The loopback JSON-lines TCP transport: one request per line, one reply per line. -use std::io::{BufReader, Write}; -use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::io::{BufReader, Read, Write}; +use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; @@ -56,7 +56,8 @@ pub fn listen(port: u16, token: String, host: WindowHost) -> std::io::Result<(Re /// Serves a listener bound earlier (an app's `--control`, bound before its window opens) until the /// returned [`Listening`] is dropped: authenticates each connection with `token`, forwards its -/// requests to the receiver and wakes the root window through `host`. The app prints +/// requests to the receiver and wakes the root window through `host`, which keeps each window's access tree +/// ([`WindowHost::keep_access_tree`]) for [`crate::access`]. The app prints /// `control server listening on `. pub fn serve(listener: TcpListener, token: String, host: WindowHost) -> std::io::Result<(Receiver, Listening)> { serve_with_deadline(listener, token, host, AUTH_DEADLINE) @@ -73,6 +74,9 @@ pub fn serve_with_deadline( ) -> std::io::Result<(Receiver, Listening)> { 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 + // from before the first connection, so the first request already finds it. + host.keep_access_tree(); let stop = Arc::new(AtomicBool::new(false)); let stopped = Arc::clone(&stop); let accept = std::thread::Builder::new().name("control server".into()).spawn(move || { @@ -85,6 +89,7 @@ pub fn serve_with_deadline( let Some(permit) = limiter.try_acquire() else { let _ = configure_stream(&stream); let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})); + close_after_reply(&stream); continue; }; let tx = tx.clone(); @@ -175,4 +180,27 @@ fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, break; } } + close_after_reply(&out); +} + +/// How long a closing connection's leftover input is read and dropped ([`close_after_reply`]). +const CLOSE_LINGER: Duration = Duration::from_millis(250); + +/// Closes `stream` after its last reply without resetting it: the write side ends first, so the client reads the +/// reply and then the end of the stream, and what the client still sends is read and dropped until it closes too, for +/// at most [`CLOSE_LINGER`]. A socket closed with input unread is reset instead, and the client loses the reply +/// (Linux) or reads the reset where the end of the stream should be (Windows). +fn close_after_reply(mut stream: &TcpStream) { + let _ = stream.shutdown(Shutdown::Write); + let deadline = motion::now() + CLOSE_LINGER; + let mut sink = [0; 1024]; + loop { + let left = deadline.saturating_duration_since(motion::now()); + if left.is_zero() || stream.set_read_timeout(Some(left)).is_err() { + return; + } + if matches!(stream.read(&mut sink), Ok(0) | Err(_)) { + return; + } + } } diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 96024d958c..bea9c8d5a5 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,10 +1,11 @@ -//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, -//! `ui.type`, `ui.ime` and `ui.capsLock`. +//! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`, +//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], //! [`WindowHost::inject_key`], [`WindowHost::inject_release`], [`WindowHost::inject_text`], -//! [`WindowHost::inject_ime`]), one step per pass, so a move, a press, a release, a key's down and up and each +//! [`WindowHost::inject_ime`], [`WindowHost::inject_files`], [`WindowHost::inject_access`]), one step per pass, so a +//! move, a press, a release, a key's down and up and each //! composition step land on separate passes as real input does. A request is validated whole before anything of it is //! queued, so a refused one leaves no half-queued press. The host answers the //! waiting replies once [`WindowHost::injected_idle`] turns true ([`crate::control::ControlChannel::poll_input`]), and @@ -16,7 +17,15 @@ //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application //! maps to the screen through its canvas ([`DocumentMap`]). Document-coordinate `ui.pointer` events are the -//! application's own method: they drive its tool host, not the window. +//! application's own method: they drive its tool host, not the window. With `control: {name, role?, within?, index?}` +//! a point is the centre of that control's rect, `x` and `y` an offset from it ([`access::Target`]). +//! +//! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action +//! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a +//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a +//! drag is `ui.click {hold}`, `ui.move` and `ui.release`. + +use std::path::PathBuf; use craft_behavior::PointerButton; use craft_keymap::{Key, Mods}; @@ -24,6 +33,7 @@ use craft_ui::runtime::windows::{Released, WindowHost}; use egui::{Pos2, Vec2, ViewportId, pos2, vec2}; use serde_json::Value; +use crate::access::{self, NodeTarget, inject_click, inject_context_menu, inject_focus}; use crate::protocol::{BUTTONS, KEY_MODIFIERS, Params}; /// Most clicks one `ui.click` may ask for (`count`). @@ -53,46 +63,80 @@ pub const NOT_FINITE: &str = "the point must be finite"; /// when no canvas shows a document. Applications without documents pass `&|_, _| None`. pub type DocumentMap<'a> = &'a dyn Fn(usize, Pos2) -> Option; -/// A point of a request: screen points, or document points the application maps. -#[derive(Clone, Copy, Debug, PartialEq)] +/// A point of a request: screen points, document points the application maps, or an offset from a named control. +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum At { /// Screen points. Screen(Pos2), /// Document points on page `page` (0 when the request names none). Document(Pos2, usize), + /// An offset from the centre of the rect of the control `target` names. + #[non_exhaustive] + Control { + /// The control. + target: access::Target, + /// The offset from the rect's centre. + offset: Vec2, + }, } impl At { - /// `x` and `y`, each defaulting to 0, in the space `coordinates` names (`screen`, the default, or `document`). + /// `x` and `y`, each defaulting to 0, in the space `coordinates` names (`screen`, the default, or `document`); with + /// `control` they are an offset in points from the control's centre, and `coordinates` is refused. fn from_params(p: &Params<'_>) -> Result { let range = Some((-MAX_SCREEN_POINT, MAX_SCREEN_POINT)); let x = p.number_in("x", "x", range)?.unwrap_or(0.0) as f32; let y = p.number_in("y", "y", range)?.unwrap_or(0.0) as f32; + if let Some(control) = p.0.get("control") { + if p.0.get("coordinates").is_some() { + return Err("`coordinates` and `control` exclude each other".into()); + } + return Ok(Self::Control { target: access::Target::from_params(control)?, offset: vec2(x, y) }); + } + Self::in_space(p, pos2(x, y)) + } + + /// `x` and `y`, both required, in the space `coordinates` names (`screen`, the default, or `document`). + fn required(p: &Params<'_>) -> Result { + let range = Some((-MAX_SCREEN_POINT, MAX_SCREEN_POINT)); + let x = p.number_in("x", "x", range)?.ok_or_else(|| "missing `x`".to_owned())? as f32; + let y = p.number_in("y", "y", range)?.ok_or_else(|| "missing `y`".to_owned())? as f32; + Self::in_space(p, pos2(x, y)) + } + + fn in_space(p: &Params<'_>, pos: Pos2) -> Result { Ok(match p.choice("coordinates", "coordinates", &["screen", "document"])?.unwrap_or("screen") { - "document" => Self::Document(pos2(x, y), p.uint_field("page")?.map_or(0, |page| usize::try_from(page).unwrap_or(usize::MAX))), - _ => Self::Screen(pos2(x, y)), + "document" => Self::Document(pos, p.uint_field("page")?.map_or(0, |page| usize::try_from(page).unwrap_or(usize::MAX))), + _ => Self::Screen(pos), }) } /// The screen point, through `map` for a document point; [`NO_DOCUMENT`] when the map has none, and - /// [`OFF_SCREEN`] when it maps beyond [`MAX_SCREEN_POINT`]; a point that is not finite is [`NOT_FINITE`]. - pub fn resolve(self, map: DocumentMap<'_>) -> Result { + /// [`OFF_SCREEN`] when it maps beyond [`MAX_SCREEN_POINT`]; a point that is not finite is [`NOT_FINITE`]. A control + /// point is the centre of the rect `controls` gives it plus the offset, or the error `controls` gives. + pub fn resolve(&self, map: DocumentMap<'_>, controls: access::ControlMap<'_>) -> Result { match self { - Self::Screen(at) if at.x.is_finite() && at.y.is_finite() => Ok(at), + Self::Control { target, offset } => Ok(controls(target)?.center() + *offset), + Self::Screen(at) if at.x.is_finite() && at.y.is_finite() => Ok(*at), Self::Screen(_) => Err(NOT_FINITE.to_owned()), Self::Document(at, _) if !(at.x.is_finite() && at.y.is_finite()) => Err(NOT_FINITE.to_owned()), Self::Document(at, page) => { - let on_screen = map(page, at).ok_or_else(|| NO_DOCUMENT.to_owned())?; + let on_screen = map(*page, *at).ok_or_else(|| NO_DOCUMENT.to_owned())?; let within = |v: f32| v.is_finite() && f64::from(v.abs()) <= MAX_SCREEN_POINT; if within(on_screen.x) && within(on_screen.y) { Ok(on_screen) } else { Err(OFF_SCREEN.to_owned()) } } } } + + /// [`At::resolve`] against the controls of the access tree the host kept for `viewport`. + fn place(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result { + self.resolve(map, &|target| target.rect(host, viewport)) + } } /// The point fields every pointer request takes. -const POINT: [&str; 4] = ["x", "y", "coordinates", "page"]; +const POINT: [&str; 5] = ["x", "y", "coordinates", "page", "control"]; /// The modifier fields ([`crate::protocol::KEY_MODIFIERS`], top-level or under `modifiers`). const MODIFIERS: [&str; 5] = ["modifiers", "shift", "alt", "command", "ctrl"]; @@ -117,12 +161,44 @@ fn key(p: &Params<'_>) -> Result, String> { p.choice("key", "key", &[])?.map(|name| Key::parse(name).ok_or_else(|| format!("unknown key `{name}`"))).transpose() } +/// Where a `ui.click` goes. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ClickTarget { + /// A position. + At(At), + /// A node of the access tree. + Node(NodeTarget), +} + +/// A validated `ui.focus`: moves the focus to a node of the access tree. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct Focus { + /// The node that takes the focus. + pub target: NodeTarget, +} + +impl Focus { + /// `{id | label}`: the node to focus, exactly one of the two, no other fields (``"missing `id` or `label`"``). + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["id", "label"])?; + NodeTarget::from_params(&p)?.map(|target| Focus { target }).ok_or_else(|| "missing `id` or `label`".into()) + } + + /// Queues the focus request for the node in `viewport`; a node the kept tree does not have as one reported, + /// enabled, focusable node is refused ([`crate::access::resolve`]). + pub fn inject(&self, host: &WindowHost, viewport: ViewportId) -> Result<(), String> { + inject_focus(host, viewport, &self.target) + } +} + /// A validated `ui.click`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Click { - /// Target position. - pub at: At, + /// Where the click goes: a position or a node of the access tree. + pub target: ClickTarget, /// The button pressed. pub button: PointerButton, /// Number of clicks (2 is a double click). @@ -134,30 +210,63 @@ pub struct Click { } impl Click { - /// `{x?, y?, coordinates?, button?, count?, hold?, modifiers…}`, no other fields (`Params::only`). `button` - /// defaults to `left`. `count` is an unsigned integer, default 1; over [`MAX_CLICKS`] is - /// ``"`count` must be at most 256 (got {count})"``. Other errors are the `Params` validators'. + /// `{x?, y?, coordinates?, button?, count?, hold?, modifiers…}` for a point, or `{id | label, button?}` for a node + /// of the access tree ([`NodeTarget::from_params`]); no other fields (`Params::only`). `button` defaults to + /// `left`. `count` is an unsigned integer, default 1; over [`MAX_CLICKS`] is + /// ``"`count` must be at most 256 (got {count})"``. A node is clicked by its own action, so with one only the + /// primary button (its click) and the secondary one (its context menu) are allowed, and a point, `count` above 1, + /// `hold` and held modifiers are refused. Other errors are the `Params` validators'. pub fn from_params(params: &Value) -> Result { - let p = only(params, &["button", "count", "hold"])?; + let p = only(params, &["button", "count", "hold", "id", "label"])?; let p = Params(&p); let count = p.uint_field("count")?.unwrap_or(1); if count > MAX_CLICKS { return Err(format!("`count` must be at most {MAX_CLICKS} (got {count})")); } - Ok(Self { - at: At::from_params(&p)?, - button: button(&p)?.unwrap_or(PointerButton::Primary), - count, - mods: p.modifiers(&KEY_MODIFIERS)?, - hold: p.bool_field("hold")?.unwrap_or(false), - }) + let pressed = button(&p)?; + let mods = p.modifiers(&KEY_MODIFIERS)?; + let hold = p.bool_field("hold")?.unwrap_or(false); + if let Some(node) = NodeTarget::from_params(p.0)? { + if POINT.iter().any(|field| p.0.get(field).is_some()) { + return Err("a click names a node (`id` or `label`) or a point (`x`, `y`), not both".into()); + } + if count > 1 { + return Err("`count` goes with a point, not a node".into()); + } + if hold { + return Err("`hold` goes with a point, not a node".into()); + } + if !mods.is_none() { + return Err("modifiers go with a point, not a node".into()); + } + let button = match pressed { + None | Some(PointerButton::Primary) => PointerButton::Primary, + Some(PointerButton::Secondary) => PointerButton::Secondary, + Some(_) => return Err("a node takes a primary or a secondary click, not the middle button".into()), + }; + return Ok(Self { target: ClickTarget::Node(node), button, count: 1, mods, hold: false }); + } + Ok(Self { target: ClickTarget::At(At::from_params(&p)?), button: pressed.unwrap_or(PointerButton::Primary), count, mods, hold }) } - /// Queues a move to the target, then `count` presses and releases of the button, in `viewport`. + /// Queues a move to the point, then `count` presses and releases of the button, in `viewport`; for a node, its + /// click, or its context menu for the secondary button, once the kept tree has it as one reported, enabled node + /// that declares the action ([`crate::access::resolve`]). pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - let count = u32::try_from(self.count).unwrap_or(u32::MAX); - host.inject_click(viewport, self.at.resolve(map)?, self.button, count, self.mods, self.hold); - Ok(()) + match &self.target { + ClickTarget::At(at) => { + let count = u32::try_from(self.count).unwrap_or(u32::MAX); + host.inject_click(viewport, at.place(host, viewport, map)?, self.button, count, self.mods, self.hold); + Ok(()) + } + ClickTarget::Node(node) => { + if matches!(self.button, PointerButton::Secondary) { + inject_context_menu(host, viewport, node) + } else { + inject_click(host, viewport, node) + } + } + } } } @@ -174,12 +283,12 @@ pub struct Move { } impl Move { - /// `{x?, y?, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`]. + /// `{x, y, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`]. pub fn from_params(params: &Value) -> Result { let p = only(params, &["rest"])?; let p = Params(&p); Ok(Self { - at: At::from_params(&p)?, + at: At::required(&p)?, mods: p.modifiers(&KEY_MODIFIERS)?, rest: p.number_in("rest", "rest", Some((0.0, MAX_REST)))?.unwrap_or(0.0), }) @@ -187,11 +296,15 @@ impl Move { /// Queues the move in `viewport`. pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - host.inject_move(viewport, self.at.resolve(map)?, self.mods, self.rest); + let at = self.at.place(host, viewport, map)?; + host.inject_move(viewport, at, self.mods, self.rest); Ok(()) } } +/// The most notches one `ui.wheel` turn in lines may ask for, either way. +pub const MAX_NOTCHES: f32 = 100.0; + /// A validated `ui.wheel`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -200,23 +313,33 @@ pub struct Wheel { pub at: At, /// The scroll in points, as egui reports it (positive `y` scrolls towards the content's top). pub delta: Vec2, + /// Whether `delta` is in points or in whole notches of lines. + pub unit: egui::MouseWheelUnit, /// Modifiers held from the turn on. pub mods: Mods, } impl Wheel { - /// `{x?, y?, coordinates?, dx?, dy?, modifiers…}`, no other fields; `dx` and `dy` are points, default 0. + /// `{x?, y?, coordinates?, dx?, dy?, unit?, modifiers…}`, no other fields; `dx` and `dy` are default 0, in points + /// or, with `unit: "lines"`, in whole notches (rounded, at most [`MAX_NOTCHES`] either way). `unit` defaults to + /// `"points"`. pub fn from_params(params: &Value) -> Result { - let p = only(params, &["dx", "dy"])?; + let p = only(params, &["dx", "dy", "unit"])?; let p = Params(&p); let dx = p.number_in("dx", "dx", None)?.unwrap_or(0.0) as f32; let dy = p.number_in("dy", "dy", None)?.unwrap_or(0.0) as f32; - Ok(Self { at: At::from_params(&p)?, delta: vec2(dx, dy), mods: p.modifiers(&KEY_MODIFIERS)? }) + let notches = |turn: f32| turn.round().clamp(-MAX_NOTCHES, MAX_NOTCHES); + let (unit, delta) = match p.choice("unit", "unit", &["points", "lines"])?.unwrap_or("points") { + "lines" => (egui::MouseWheelUnit::Line, vec2(notches(dx), notches(dy))), + _ => (egui::MouseWheelUnit::Point, vec2(dx, dy)), + }; + Ok(Self { at: At::from_params(&p)?, delta, unit, mods: p.modifiers(&KEY_MODIFIERS)? }) } /// Queues the move and the turn in `viewport`. pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - host.inject_wheel(viewport, self.at.resolve(map)?, self.delta, self.mods); + let at = self.at.place(host, viewport, map)?; + host.inject_wheel(viewport, at, self.delta, self.unit, self.mods); Ok(()) } } @@ -250,7 +373,7 @@ impl KeyPress { } /// A validated `ui.release`. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Release { /// Where the release happens; where the pointer is when absent. @@ -260,10 +383,10 @@ pub struct Release { } impl Release { - /// `{button?, key?, x?, y?, coordinates?}`, no other fields. With neither `button` nor `key` everything held is - /// released, the modifiers too; both is ``"`button` and `key` exclude each other"``. + /// `{button?, key?, x?, y?, coordinates?, page?, control?}`, no other fields. With neither `button` nor `key` everything + /// held is released, the modifiers too; both is ``"`button` and `key` exclude each other"``. pub fn from_params(params: &Value) -> Result { - let p = Params(params).only(None, &["button", "key", "x", "y", "coordinates", "page"])?; + let p = Params(params).only(None, &["button", "key", "x", "y", "coordinates", "page", "control"])?; let p = Params(&p); let released = match (button(&p)?, key(&p)?) { (Some(_), Some(_)) => return Err("`button` and `key` exclude each other".into()), @@ -271,13 +394,13 @@ impl Release { (None, Some(key)) => Released::Key(key), (None, None) => Released::All, }; - let at = (p.0.get("x").is_some() || p.0.get("y").is_some()).then(|| At::from_params(&p)).transpose()?; + let at = ["x", "y", "control"].iter().any(|field| p.0.get(*field).is_some()).then(|| At::from_params(&p)).transpose()?; Ok(Self { at, released }) } /// Queues the release in `viewport`. pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - let at = self.at.map(|at| at.resolve(map)).transpose()?; + let at = self.at.as_ref().map(|at| at.place(host, viewport, map)).transpose()?; host.inject_release(viewport, at, self.released); Ok(()) } @@ -303,6 +426,8 @@ pub fn caps_lock_from_params(params: &Value) -> Result, String> { pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Option> { Some(match method { "ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)), + "ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)), + "ui.drop" => drop_files(params, host, viewport, map), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), @@ -314,6 +439,32 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V }) } +/// `ui.drop {paths, hover_only?, x?, y?, coordinates?}`: hovers the files `paths` names (a non-empty array of +/// strings) over the point, where the pointer is when neither `x` nor `y` is given, and drops them in the following +/// step unless `hover_only`. The point is mapped as every request's is; a drop carries no modifiers, so a held one is +/// refused. +fn drop_files(params: &Value, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + const PATHS: &str = "paths must be a non-empty array of strings"; + let p = only(params, &["paths", "hover_only"])?; + let p = Params(&p); + if !p.modifiers(&KEY_MODIFIERS)?.is_none() { + return Err("`ui.drop` takes no modifiers".into()); + } + let paths: Vec = match p.0.get("paths") { + None => return Err("missing `paths`".into()), + Some(Value::Array(items)) => items.iter().map(|item| item.as_str().map(PathBuf::from)).collect::>().ok_or(PATHS)?, + Some(_) => return Err(PATHS.into()), + }; + if paths.is_empty() { + return Err(PATHS.into()); + } + let hover_only = p.bool_field("hover_only")?.unwrap_or(false); + let at = (p.0.get("x").is_some() || p.0.get("y").is_some() || p.0.get("control").is_some()).then(|| At::from_params(&p)).transpose()?; + let at = at.map(|at| at.place(host, viewport, map)).transpose()?; + host.inject_files(viewport, at, paths, !hover_only); + Ok(()) +} + /// A validated `ui.type`: `{text}`, a string. fn text(params: &Value) -> Result { let p = Params(params).only(None, &["text"])?; diff --git a/crates/automation/src/ui/actions/body.rs b/crates/automation/src/ui/actions/body.rs index 19dcfca8a7..a38f637be5 100644 --- a/crates/automation/src/ui/actions/body.rs +++ b/crates/automation/src/ui/actions/body.rs @@ -17,7 +17,7 @@ use craft_ui::runtime::env::{Env, Label}; use egui::{Id, Response, Ui}; use super::menu::OpenMenu; -use super::panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanelState, Session}; +use super::panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanelState, Session, StepCells}; use super::rows::{ActionRows, DIALOG_COLUMN, INCLUDE_COLUMN, NAME_COLUMN, build_row, cells}; use super::words::ActionsWords; use crate::actions::{ActionList, moved_index}; @@ -32,6 +32,8 @@ pub(super) struct Body<'a> { pub(super) env: &'a Env, /// The id the tree's list shows under, which its drags carry as `ListDrag::list`. pub(super) list_id: Id, + /// Which step cells the rows show. + pub(super) step_cells: StepCells, } /// Where a moved row goes. @@ -82,8 +84,9 @@ pub struct ActionMove { pub(super) struct BodyOutput { pub(super) events: Vec, pub(super) response: Response, - /// The selection the list ended on, for the caller to store after the container; `None` when the body did not show the tree. - pub(super) selected: Option>, + /// The selected row and the range of sets the list ended on, for the caller to store after the container; `None` + /// when the body did not show the tree. + pub(super) selected: Option<(Option, Vec)>, } /// The part of the panel above the footer: the empty notice, Button Mode's buttons or the tree. @@ -149,19 +152,24 @@ fn show_tree(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState, sessio let recording = host.and_then(|host| host.recording()); let rows = ActionRows::build(list, state, host); let order = rows.keys(); - let mut selection = Selection::new(state.selected.iter().cloned().collect(), state.selected.clone(), state.selected.clone()); + let items = if state.selected_sets.is_empty() { + state.selected.iter().cloned().collect() + } else { + state.selected_sets.iter().cloned().map(ActionSelection::Set).collect() + }; + let mut selection = Selection::new(items, state.selected.clone(), state.selected.clone()); if let Some(index) = rename.filter(|_| editable) { request_rename(ui.ctx(), list_id, &ActionSelection::Action(index)); } - let columns = vec![ - ColumnSpec::toggle(INCLUDE_COLUMN, Label::Empty, ToggleColumn::sweepable()), - ColumnSpec::toggle(DIALOG_COLUMN, Label::Empty, ToggleColumn::sweepable()).icon(IconId::new("note")), - ColumnSpec::new(NAME_COLUMN, Label::Empty, ColumnWidth::fill(1.0)), - ]; + let mut columns = vec![ColumnSpec::toggle(INCLUDE_COLUMN, Label::Empty, ToggleColumn::sweepable())]; + if body.step_cells == StepCells::IncludeAndDialog { + columns.push(ColumnSpec::toggle(DIALOG_COLUMN, Label::Empty, ToggleColumn::sweepable()).icon(IconId::new("note"))); + } + columns.push(ColumnSpec::new(NAME_COLUMN, Label::Empty, ColumnWidth::fill(1.0))); let mut widget = List::new(words.name.clone()) .id(list_id) .tree(true) - .select(SelectMode::Single) + .select(SelectMode::Multi) .allow_empty(true) .space(SpaceAction::ToggleCell) .deletable(true) @@ -224,17 +232,37 @@ fn show_tree(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState, sessio } } CollectionEvent::Delete(keys) if editable => { - events.extend(keys.first().and_then(|key| delete_event(key, recording.is_some()))); + if state.selected_sets.is_empty() { + events.extend(keys.first().and_then(|key| delete_event(key, recording.is_some()))); + } else if recording.is_none() { + events.push(ActionsEvent::DeleteSets(state.selected_sets.clone())); + } } CollectionEvent::ContextMenu(request) => session.menu = OpenMenu::opened(request, list, host), _ => {} } } - let mut selected = selection.items.first().cloned(); + let (mut selected, sets) = kept(list, &selection); for (source, to) in &moves { selected = selected.map(|selected| remapped(selected, source, to)); } - BodyOutput { events, response: out.response, selected: Some(selected) } + BodyOutput { events, response: out.response, selected: Some((selected, sets)) } +} + +/// The selection the panel keeps after the list applied this pass's input: the lead row, and the range of sets in list +/// order when the lead and the range's other end (the anchor) are both set rows. The list's range runs over the shown +/// rows, so one across an expanded set holds that set's action rows too; only the set rows are kept. A lead that is an +/// action or step, or a set reached from one of those, is the whole selection. A range of fewer than two sets is none. +fn kept(list: &ActionList, selection: &Selection) -> (Option, Vec) { + let lead = selection.lead.clone().filter(|lead| selection.items.contains(lead)); + let range = matches!((&lead, &selection.anchor), (Some(ActionSelection::Set(_)), Some(ActionSelection::Set(_)))); + let sets: Vec = if range { + let chosen = |set: &str| selection.items.iter().any(|key| matches!(key, ActionSelection::Set(name) if name == set)); + list.sets().into_iter().filter(|set| chosen(set)).map(str::to_owned).collect() + } else { + Vec::new() + }; + (lead, if sets.len() > 1 { sets } else { Vec::new() }) } /// The `Delete` event for `selected`: a step always; a set or an action not while recording. diff --git a/crates/automation/src/ui/actions/menu.rs b/crates/automation/src/ui/actions/menu.rs index ed1e728371..74add10436 100644 --- a/crates/automation/src/ui/actions/menu.rs +++ b/crates/automation/src/ui/actions/menu.rs @@ -1,4 +1,4 @@ -//! The panel menu's commands and the row context menus (Keyboard Shortcuts, Color; Save Set…). +//! The panel menu's commands and the row context menus. use craft_keymap::Platform; use craft_ui::contract::{CommandSet, ContextMenuRequest, Props as _, Show as _, ShowContainer as _}; @@ -6,6 +6,7 @@ use craft_ui::display::Divider; use craft_ui::list::label_color_label; use craft_ui::menu::{Menu, MenuItem, PanelRow}; use craft_ui::runtime::commands::{CommandRef, CommandState}; +use craft_ui::runtime::env::Label; use egui::{Response, Ui}; use super::body::{Body, delete_event}; @@ -276,7 +277,7 @@ pub fn panel_rows(facts: ActionsMenuFacts, offered: &dyn Fn(ActionsPanelCommands /// The shortcut as the context menu has made it so far. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct PendingShortcut { - /// 0 for none, else 1..=12. + /// 0 for none, else 1..=15. key: u8, shift: bool, command: bool, @@ -291,7 +292,7 @@ impl PendingShortcut { /// The menu a context request opened, kept until the next request. #[derive(Clone, Debug)] pub(super) enum OpenMenu { - /// A set's menu: Save Set…. + /// A set's menu. Set(String), /// An action's menu, with the shortcut as the menu has made it from the host's. Action { index: usize, shortcut: PendingShortcut }, @@ -318,34 +319,58 @@ impl OpenMenu { } /// Shows the menu the last request chose, hanging from `opener` (the list), and reports what its -/// rows ran: -/// - On an action: Keyboard Shortcuts (a caption), None and F1 to F12 as radio rows, then Shift and -/// Command (Ctrl off macOS) check rows, enabled only with a key; the check rows keep the menu -/// open so both can be ticked, and each tick is reported as it is made with the shortcut as it -/// stands. A separator, then Color: a submenu of None, Red, Orange, Yellow, Green, Blue, Violet -/// and Gray with the current one marked. -/// - On a set: Save Set…. +/// rows ran. Rows that start or change something are off while an action plays or records, as the +/// footer's are; Delete follows the footer's Delete. +/// - On an action: Play and Record; Duplicate and Delete; Action Options… and Batch…. Then +/// Keyboard Shortcuts (a caption), None and F1 to F15 as radio rows, then Shift and Command (Ctrl +/// off macOS) check rows, enabled only with a key; the check rows keep the menu open so both can +/// be ticked, and each tick is reported as it is made with the shortcut as it stands. Last Color: +/// a submenu of None, Red, Orange, Yellow, Green, Blue, Violet and Gray with the current one +/// marked. +/// - On a set: New Action…, New Set…, Duplicate Set and Delete Set; Set Options…; Save Set…. pub(super) fn show_menu(ui: &mut Ui, body: &Body<'_>, opener: &Response, session: &mut Session) -> Vec { - let Body { list, words, list_words, .. } = *body; + let Body { list, host, words, list_words, .. } = *body; + let recording = host.is_some_and(|host| host.recording().is_some()); + let playing = host.is_some_and(|host| host.playing()); + let idle = !recording && !playing; + let hosted = host.is_some(); + let deletable = |row: &ActionSelection| delete_event(row, recording).filter(|_| !playing); let mut events = Vec::new(); match session.menu.as_mut() { None => {} Some(OpenMenu::Set(name)) => { + let set = ActionSelection::Set(name.clone()); Menu::context(words.row_menu.clone(), opener).show(ui, |ui, _| { - if MenuItem::new(words.save_set.clone()).show(ui).ran { - events.push(ActionsEvent::Save { set: Some(name.clone()) }); - } + let events = &mut events; + event_row(ui, events, &words.menu_new_action, (hosted && idle).then_some(ActionsEvent::NewAction)); + event_row(ui, events, &words.menu_new_set, idle.then_some(ActionsEvent::NewSet)); + event_row(ui, events, &words.duplicate_set, idle.then(|| ActionsEvent::Duplicate(set.clone()))); + event_row(ui, events, &words.delete_set, deletable(&set)); + Divider::horizontal().show(ui); + event_row(ui, events, &words.set_options, Some(ActionsEvent::SetOptions(name.clone()))); + Divider::horizontal().show(ui); + event_row(ui, events, &words.save_set, Some(ActionsEvent::save(Some(name.clone())))); }); } Some(OpenMenu::Action { index, shortcut }) => { let (action, current) = (*index, list.action(*index).map(|held| held.color).unwrap_or_default()); + let selection = ActionSelection::Action(action); Menu::context(words.row_menu.clone(), opener).show(ui, |ui, _| { + event_row(ui, &mut events, &words.menu_play, (hosted && idle).then(|| ActionsEvent::play(action, 0))); + event_row(ui, &mut events, &words.menu_record, (hosted && idle).then(|| ActionsEvent::begin_recording(Some(action)))); + Divider::horizontal().show(ui); + event_row(ui, &mut events, &words.duplicate, idle.then(|| ActionsEvent::Duplicate(selection.clone()))); + event_row(ui, &mut events, &words.delete, deletable(&selection)); + Divider::horizontal().show(ui); + event_row(ui, &mut events, &words.action_options, Some(ActionsEvent::ActionOptions(action))); + event_row(ui, &mut events, &words.batch, Some(ActionsEvent::Batch(action))); + Divider::horizontal().show(ui); MenuItem::new(words.keyboard_shortcuts.clone()).enabled(false).show(ui); if MenuItem::new(words.none.clone()).radio_mark(shortcut.key == 0).show(ui).ran { shortcut.key = 0; events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); } - for key in 1..=12u8 { + for key in 1..=15u8 { if MenuItem::new(format!("F{key}")).radio_mark(shortcut.key == key).show(ui).ran { shortcut.key = key; events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); @@ -375,3 +400,10 @@ pub(super) fn show_menu(ui: &mut Ui, body: &Body<'_>, opener: &Response, session } events } + +/// A row of a row menu, enabled while it has an event, which it reports when it runs. +fn event_row(ui: &mut Ui, events: &mut Vec, label: &Label, event: Option) { + if MenuItem::new(label.clone()).enabled(event.is_some()).show(ui).ran { + events.extend(event); + } +} diff --git a/crates/automation/src/ui/actions/mod.rs b/crates/automation/src/ui/actions/mod.rs index d8a30be9f9..1c9e113e08 100644 --- a/crates/automation/src/ui/actions/mod.rs +++ b/crates/automation/src/ui/actions/mod.rs @@ -23,7 +23,9 @@ mod words; pub use body::{ActionMove, ActionPlace}; pub use menu::{ActionsMenuAction, ActionsMenuFacts, ActionsPanelCommands, panel_rows}; -pub use panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanel, ActionsPanelOutput, ActionsPanelState, ActionsSettings, ShortcutChoice}; +pub use panel::{ + ActionSelection, ActionsEvent, ActionsHost, ActionsPanel, ActionsPanelOutput, ActionsPanelState, ActionsSettings, ShortcutChoice, StepCells, +}; pub use prompt::LibraryPrompt; pub use rows::{DIALOG_COLUMN, INCLUDE_COLUMN}; pub use words::ActionsWords; diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs index 179ff8a17b..ecdef774e6 100644 --- a/crates/automation/src/ui/actions/panel.rs +++ b/crates/automation/src/ui/actions/panel.rs @@ -100,13 +100,27 @@ pub struct ActionsPanelState { pub selected: Option, /// The expanded actions, by name (names are unique, so expansion survives moves). pub expanded: BTreeSet, + /// The sets a shift-click selected, from the current set to the clicked one, in the set order; empty when there is + /// no range. + pub selected_sets: Vec, +} + +/// Which step cells the rows show. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum StepCells { + /// The include cell and the dialog cell. + #[default] + IncludeAndDialog, + /// The include cell only: the dialog column is left out of the cells and the list's columns. + Include, } /// A function-key shortcut chosen in the context menu (Photoshop's Action Options). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ShortcutChoice { - /// F1 to F12: 1..=12. + /// F1 to F15: 1..=15. pub key: u8, /// Shift is part of the shortcut. pub shift: bool, @@ -115,7 +129,7 @@ pub struct ShortcutChoice { } impl ShortcutChoice { - /// Function key `key` (1 to 12) with the given modifiers. + /// Function key `key` (1 to 15) with the given modifiers. pub const fn new(key: u8, shift: bool, command: bool) -> Self { Self { key, shift, command } } @@ -126,7 +140,7 @@ impl ShortcutChoice { self.chord().display(Platform::current()) } - /// The shortcut as a keymap chord; a key above 12 is taken as F12. + /// The shortcut as a keymap chord; a key outside 1..=15 is taken as F12. fn chord(&self) -> Chord { let key = match self.key { 1 => Key::F1, @@ -140,6 +154,9 @@ impl ShortcutChoice { 9 => Key::F9, 10 => Key::F10, 11 => Key::F11, + 13 => Key::F13, + 14 => Key::F14, + 15 => Key::F15, _ => Key::F12, }; Chord::new(Mods { cmd: self.command, shift: self.shift, ..Mods::NONE }, key) @@ -217,6 +234,8 @@ pub enum ActionsEvent { InsertStop, /// Batch… with this action (the app's dialog). Batch(usize), + /// Action Options… from an action's menu: the app's dialog for this action's name, set, function key and colour. + ActionOptions(usize), /// Load Actions… (the app's file dialog). Load, /// Clear All Actions: the app asks with [`LibraryPrompt::ClearAll`](super::LibraryPrompt) and @@ -237,6 +256,8 @@ pub enum ActionsEvent { /// Duplicate this row ([`ActionList::duplicate_action`], [`ActionList::duplicate_step`], /// [`ActionList::duplicate_set`]): from the menu row or a row dropped on New Action. Duplicate(ActionSelection), + /// Delete with a range of sets selected: the range, in one event, so the app asks one question. + DeleteSets(Vec), /// Record Again: replace step `step` of `action` with a new recording /// ([`ActionList::replace_step`]). #[non_exhaustive] @@ -359,7 +380,9 @@ impl Default for Session { /// all); a double click on an action's name renames it, elsewhere on an action it plays it. The /// cells sweep down their column as one gesture. A drag moves an action (into or out of a set) /// or a step (within or between actions), or drops it on the footer's Delete. Right-click on an -/// action opens Keyboard Shortcuts and Color; on a set, Save Set…. +/// action or a set selects it and opens its menu: on an action Play, Record, Duplicate, Delete, +/// Action Options…, Batch…, Keyboard Shortcuts and Color; on a set New Action…, New Set…, +/// Duplicate Set, Delete Set, Set Options… and Save Set…. /// - **Keys**: the rows are one Tab stop: arrows move, Left and Right close and open, Enter plays /// an action or toggles a set, Space toggles the include cell, F2 renames, Delete deletes the /// selection (not an action while recording), Cmd/Ctrl+] and [ move the row, Shift to the ends. The footer @@ -376,12 +399,13 @@ pub struct ActionsPanel<'a> { host: Option<&'a dyn ActionsHost>, rename: Option, enabled: bool, + step_cells: StepCells, } impl<'a> ActionsPanel<'a> { /// A panel over `list` with `state`. pub fn new(state: &'a mut ActionsPanelState, list: &'a ActionList) -> Self { - Self { state, list, host: None, rename: None, enabled: true } + Self { state, list, host: None, rename: None, enabled: true, step_cells: StepCells::default() } } /// The app's side; without one, steps show their command ids and nothing records or plays. @@ -397,6 +421,12 @@ impl<'a> ActionsPanel<'a> { self } + /// Which step cells the rows show. + pub fn step_cells(mut self, cells: StepCells) -> Self { + self.step_cells = cells; + self + } + /// Whether the panel takes input (default true). pub fn enabled(mut self, enabled: bool) -> Self { self.enabled = enabled; @@ -406,7 +436,7 @@ impl<'a> ActionsPanel<'a> { /// Draws the tree (or the buttons) and the footer, and reports this pass's events in order: /// the list's, the cells', the context menu's, the footer's. pub fn show(self, ui: &mut Ui) -> ActionsPanelOutput { - let ActionsPanel { state, list, host, rename, enabled } = self; + let ActionsPanel { state, list, host, rename, enabled, step_cells } = self; let env = Env::of(ui); let words = env.words::(); let list_words = env.words::(); @@ -414,7 +444,7 @@ impl<'a> ActionsPanel<'a> { let settings_before = state.settings.clone(); let events = RefCell::new(Vec::new()); let state = RefCell::new(state); - let body = Body { list, host, words: &words, list_words: &list_words, env: &env, list_id }; + let body = Body { list, host, words: &words, list_words: &list_words, env: &env, list_id, step_cells }; let shown = Stack::new() .fill() @@ -436,8 +466,10 @@ impl<'a> ActionsPanel<'a> { let mut reported = Vec::new(); if let Some((body_events, selected)) = shown.inner { reported = body_events; - if let Some(selected) = selected { - state.borrow_mut().selected = selected; + if let Some((row, sets)) = selected { + let mut state = state.borrow_mut(); + state.selected = row; + state.selected_sets = sets; } } reported.extend(events.into_inner()); diff --git a/crates/automation/src/ui/actions/rows.rs b/crates/automation/src/ui/actions/rows.rs index 2319e3021d..41f1af45cc 100644 --- a/crates/automation/src/ui/actions/rows.rs +++ b/crates/automation/src/ui/actions/rows.rs @@ -11,7 +11,7 @@ use craft_ui::primitives::IconSpec; use craft_ui::runtime::env::Label; use super::body::Body; -use super::panel::{ActionSelection, ActionsHost, ActionsPanelState}; +use super::panel::{ActionSelection, ActionsHost, ActionsPanelState, StepCells}; use crate::actions::{ActionInclude, ActionList}; /// The include column: a toggle on action rows (every step) and step rows. @@ -145,6 +145,7 @@ impl ItemSource for ActionRows<'_> { (ActionSelection::Action(index), column) if *column == INCLUDE_COLUMN => { self.list.action(*index).is_some_and(|action| action.include() == ActionInclude::All) } + (ActionSelection::Set(name), column) if *column == INCLUDE_COLUMN => matches!(set_include(self.list, name), Some(ToggleState::On)), _ => match self.recorded_step(at) { Some((action, step)) if *column == INCLUDE_COLUMN => self.list.action(action).is_some_and(|held| held.step_enabled(step)), Some((action, step)) if *column == DIALOG_COLUMN => self.list.action(action).is_some_and(|held| held.dialogs.contains(&step)), @@ -158,11 +159,20 @@ impl ItemSource for ActionRows<'_> { match &row.key { ActionSelection::Action(index) => *column == INCLUDE_COLUMN && self.list.action(*index).is_some_and(|action| !action.steps.is_empty()), ActionSelection::Step(..) => self.recorded_step(at).is_some(), - ActionSelection::Set(_) => false, + ActionSelection::Set(name) => *column == INCLUDE_COLUMN && set_include(self.list, name).is_some(), } } } +/// The include mark of the set `name` over its actions that have steps: on when every one is fully included, off when +/// none is, mixed otherwise; `None` when no action of the set has a step. +fn set_include(list: &ActionList, name: &str) -> Option { + let mut marks = + list.actions().iter().filter(|action| action.set.as_deref() == Some(name) && !action.steps.is_empty()).map(|action| action.include()); + let first = marks.next()?; + Some(if marks.all(|mark| mark == first) { include_state(first) } else { ToggleState::Mixed }) +} + fn include_state(include: ActionInclude) -> ToggleState { match include { ActionInclude::All => ToggleState::On, @@ -224,10 +234,10 @@ pub(super) fn build_row(body: &Body<'_>, state: &ActionsPanelState, key: &Action } } -/// The toggle cells of a row: the include cell of an action with steps and of a recorded step, the -/// dialog cell of a recorded step. +/// The toggle cells of a row: the include cell of an action or set with steps and of a recorded step, the +/// dialog cell of a recorded step unless the panel leaves the dialog column out. pub(super) fn cells(body: &Body<'_>, key: &ActionSelection) -> Vec { - let Body { list, words, .. } = *body; + let Body { list, words, step_cells, .. } = *body; let include = |state: ToggleState| ToggleCell::check(INCLUDE_COLUMN, state, words.include.clone()).tooltip(words.include_tooltip.clone()); match key { ActionSelection::Action(index) => match list.action(*index) { @@ -245,10 +255,14 @@ pub(super) fn cells(body: &Body<'_>, key: &ActionSelection) -> Vec { ) .tooltip(words.dialog_tooltip.clone()); dialog.check_box = true; - vec![include(ToggleState::of(action.step_enabled(*step))), dialog] + let mut cells = vec![include(ToggleState::of(action.step_enabled(*step)))]; + if step_cells == StepCells::IncludeAndDialog { + cells.push(dialog); + } + cells } _ => Vec::new(), }, - ActionSelection::Set(_) => Vec::new(), + ActionSelection::Set(name) => set_include(list, name).map_or_else(Vec::new, |state| vec![include(state)]), } } diff --git a/crates/automation/src/ui/actions/stories.rs b/crates/automation/src/ui/actions/stories.rs index e2b754c6b0..b5f7ebd939 100644 --- a/crates/automation/src/ui/actions/stories.rs +++ b/crates/automation/src/ui/actions/stories.rs @@ -5,7 +5,7 @@ use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use super::mock::{FakeActionsHost, action, list_of, sample_list, step}; -use super::{ActionSelection, ActionsPanel, ActionsPanelState, ShortcutChoice}; +use super::{ActionSelection, ActionsPanel, ActionsPanelState, ShortcutChoice, StepCells}; use crate::actions::{ActionColor, ActionList}; /// The sample list with Sharpen open and selected, one step off, and a shortcut on it. @@ -43,6 +43,33 @@ fn actions_panel_button_mode(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).show(ui).into() } +/// The include variant: step rows without the dialog cell, and set rows with an include cell, one of them mixed. +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_include_cells(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let mut blur = action("Blur", Some("Effects"), &["blur", "mask"]); + blur.disabled.insert(1); + let list = list_of(vec![blur, action("Glow", Some("Effects"), &["glow"]), action("Levels", Some("Basics"), &["levels", "curves"])]); + let mut state = ActionsPanelState::default(); + state.expanded.insert("Blur".to_owned()); + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).step_cells(StepCells::Include).show(ui).into() +} + +/// A range of three sets selected, as a Shift-click from the first to the last leaves it. +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_set_range(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let list = list_of(vec![ + action("Blur", Some("Effects"), &["blur"]), + action("Levels", Some("Basics"), &["levels"]), + action("Glow", Some("Finish"), &["glow"]), + ]); + let mut state = ActionsPanelState { + selected: Some(ActionSelection::Set("Finish".to_owned())), + selected_sets: ["Effects", "Basics", "Finish"].map(str::to_owned).to_vec(), + ..ActionsPanelState::default() + }; + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).show(ui).into() +} + #[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] fn actions_panel_empty(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { let mut state = ActionsPanelState::default(); diff --git a/crates/automation/src/ui/actions/words.rs b/crates/automation/src/ui/actions/words.rs index 745edf3746..c2f9ecc2ab 100644 --- a/crates/automation/src/ui/actions/words.rs +++ b/crates/automation/src/ui/actions/words.rs @@ -39,6 +39,16 @@ craft_ui::words! { /// The panel menu's submenu-free title of the row menu. row_menu: "actions.rowMenu" = "Action"; save_set: "actions.saveSet" = "Save Set…"; + menu_new_action: "actions.menuNewAction" = "New Action…"; + menu_new_set: "actions.menuNewSet" = "New Set…"; + duplicate_set: "actions.duplicateSet" = "Duplicate Set"; + delete_set: "actions.deleteSet" = "Delete Set"; + set_options: "actions.setOptions" = "Set Options…"; + menu_play: "actions.menuPlay" = "Play"; + menu_record: "actions.menuRecord" = "Record"; + duplicate: "actions.duplicate" = "Duplicate"; + action_options: "actions.actionOptions" = "Action Options…"; + batch: "actions.batch" = "Batch…"; keyboard_shortcuts: "actions.keyboardShortcuts" = "Keyboard Shortcuts"; /// The shortcut menu's "no shortcut" row. none: "actions.none" = "None"; diff --git a/crates/automation/src/window.rs b/crates/automation/src/window.rs new file mode 100644 index 0000000000..ae5af54dae --- /dev/null +++ b/crates/automation/src/window.rs @@ -0,0 +1,25 @@ +//! `ui.window`: window commands through the framework's one window-command path. + +use craft_ui::runtime::windows::{WindowAction, WindowHost}; +use egui::ViewportId; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// `ui.window {maximized: bool}` sends `WindowAction::SetMaximized` through `WindowHost::act` and returns `Ok({})`, or +/// `Err` when `act` returns false (no window commands, as on wasm). `None` for any other method. It keeps no state. +pub fn window_method(host: &WindowHost, viewport: ViewportId, method: &str, params: &Value) -> Option> { + if method != "ui.window" { + return None; + } + Some(run(host, viewport, params)) +} + +fn run(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result { + let params = Params(params).only(None, &["maximized"])?; + let maximized = Params(¶ms).bool_field("maximized")?.ok_or("missing `maximized`")?; + if !host.act(viewport, WindowAction::SetMaximized(maximized)) { + return Err("this platform has no window commands".to_owned()); + } + Ok(json!({})) +} diff --git a/crates/automation/tests/it/access.rs b/crates/automation/tests/it/access.rs new file mode 100644 index 0000000000..96d050d5a3 --- /dev/null +++ b/crates/automation/tests/it/access.rs @@ -0,0 +1,268 @@ +//! Named controls through the protocol (`control` targets, `ui.find`), `ui.inspect` over the window's kept access +//! tree, and `ui.click` and `ui.focus` on a node it names: tree order and filters, what an open modal hides, a click, +//! a context menu and a focus reaching their widget, and the targets refused before anything is queued. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +use craft_automation::access::{AMBIGUOUS, NO_CONTROL, NO_TREE, NodeTarget, access_method, inspect, resolve}; +use craft_automation::synthetic::input_method; +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::dialog::Dialog; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::runtime::egui::access::Declared; +use craft_ui::runtime::egui::injected::hook_without_pass; +use craft_ui::runtime::windows::WindowHost; +use craft_ui::sections::{DialogRole, FooterButton}; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::TextField; +use egui::{Pos2, ViewportId}; +use serde_json::{Value, json}; + +/// Two buttons and a text field named "Name", with the clicks each button got and where the pointer was. +struct Rig { + fx: Fixture, + host: WindowHost, + clicks: Rc<[Cell; 2]>, + pointer: Rc>>, +} + +impl Rig { + fn new(names: [&'static str; 2]) -> Self { + let clicks: Rc<[Cell; 2]> = Rc::default(); + let pointer = Rc::new(Cell::new(None)); + let text = RefCell::new(String::new()); + let (seen, at) = (clicks.clone(), pointer.clone()); + let fx = Fixture::new(move |ui| { + for (n, name) in names.iter().enumerate() { + if clicked(&Button::new(*name).show(ui)) { + seen[n].set(seen[n].get() + 1); + } + } + TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui); + at.set(ui.input(|input| input.pointer.latest_pos())); + }); + let host = WindowHost::of(fx.ctx()); + Self { fx, host, clicks, pointer } + } + + /// The same, after the host kept its first access tree. + fn kept(names: [&'static str; 2]) -> Self { + let mut rig = Self::new(names); + rig.host.keep_access_trees(); + rig.fx.idle(2); + rig + } + + /// Sends `method`; when it is accepted, runs frames until the host has processed the input. + fn send(&mut self, method: &str, params: Value) -> Result<(), String> { + input_method(method, ¶ms, &self.host, ViewportId::ROOT, &|_, _| None).expect("an input method")?; + for _ in 0..32 { + self.fx.frame(Vec::new()); + if self.host.injected_idle() { + break; + } + } + assert!(self.host.injected_idle(), "{method} was processed"); + self.fx.frame(Vec::new()); + Ok(()) + } + + fn find(&self, params: Value) -> Result { + access_method("ui.find", ¶ms, &self.host, ViewportId::ROOT).expect("an access method") + } + + fn counts(&self) -> [u32; 2] { + [self.clicks[0].get(), self.clicks[1].get()] + } +} + +/// A click `{control: {name}}` presses that button and no other, also for a text field named by its label, and +/// `ui.find` reports where the control is. +#[trial] +fn a_click_on_a_named_control_lands_on_it() { + let mut rig = Rig::kept(["Save", "Cancel"]); + rig.send("ui.click", json!({"control": {"name": "Save"}})).expect("valid"); + assert_eq!(rig.counts(), [1, 0]); + rig.send("ui.click", json!({"control": {"name": "Cancel:"}})).expect("valid"); + assert_eq!(rig.counts(), [1, 1], "a trailing colon of the name is ignored"); + + let field = rig.find(json!({"name": "Name"})).expect("the field is found"); + assert_eq!(field["enabled"], json!(true)); + assert_eq!(field["focused"], json!(false)); + let rect: Vec = field["rect"].as_array().expect("a rect").iter().map(|v| v.as_f64().expect("a number")).collect(); + rig.send("ui.click", json!({"control": {"name": "Name"}})).expect("valid"); + let at = rig.pointer.get().expect("the pointer arrived"); + let (x, y) = (f64::from(at.x), f64::from(at.y)); + assert!(x >= rect[0] && x <= rect[0] + rect[2] && y >= rect[1] && y <= rect[1] + rect[3], "{at:?} lies in {rect:?}"); + assert_eq!(rig.find(json!({"name": "Name"})).expect("found")["focused"], json!(true), "the click focused the field"); +} + +/// A name two controls share needs an `index`; an unknown name matches none; neither queues anything. Before the +/// first kept pass there is no tree to look in. +#[trial] +fn an_ambiguous_or_missing_name_queues_nothing() { + let mut early = Rig::new(["Go", "Go"]); + assert_eq!(early.send("ui.click", json!({"control": {"name": "Go"}})), Err(NO_TREE.to_owned())); + assert_eq!(early.find(json!({"name": "Go"})), Err(NO_TREE.to_owned())); + + let mut rig = Rig::kept(["Go", "Go"]); + let ambiguous = rig.send("ui.click", json!({"control": {"name": "Go"}})).expect_err("two match"); + assert!(ambiguous.starts_with(AMBIGUOUS), "{ambiguous}"); + let missing = rig.send("ui.click", json!({"control": {"name": "Stop"}})).expect_err("none matches"); + assert!(missing.starts_with(NO_CONTROL), "{missing}"); + assert!(rig.host.injected_idle(), "nothing was queued"); + assert_eq!(rig.counts(), [0, 0]); + + rig.send("ui.click", json!({"control": {"name": "Go", "index": 1}})).expect("valid"); + assert_eq!(rig.counts(), [0, 1], "index 1 is the second in reading order"); +} + +/// The listed widgets of `params`, from the window's kept tree. +fn listed(host: &WindowHost, params: Value) -> Value { + inspect(host, ViewportId::ROOT, ¶ms).expect("an inspect reply") +} + +/// The labels of a reply's widgets, in its order. +fn labels(reply: &Value) -> Vec { + reply["widgets"].as_array().into_iter().flatten().filter_map(|w| w["label"].as_str().map(str::to_owned)).collect() +} + +/// The widget of a reply labelled `label`. +fn widget<'a>(reply: &'a Value, label: &str) -> &'a Value { + reply["widgets"].as_array().into_iter().flatten().find(|w| w["label"] == label).unwrap_or_else(|| panic!("{label} is listed: {reply}")) +} + +/// Where `label` sits in `order`. +fn place(order: &[String], label: &str) -> usize { + order.iter().position(|l| l == label).unwrap_or_else(|| panic!("{label} is listed in {order:?}")) +} + +/// Every reported node is listed once in tree order with its state, the root left out; `query`, `role` and `focused` +/// keep a subset, `limit` cuts the list but not the count; a node behind an open modal is neither listed nor +/// resolved, and the modal's own buttons are. +#[trial] +fn inspect_lists_reported_nodes_in_tree_order_with_their_filters() { + let open = Rc::new(Cell::new(false)); + let (shown, name) = (open.clone(), Rc::new(RefCell::new(String::from("Draft")))); + let mut fx = Fixture::new(move |ui| { + Button::new("Open").show(ui); + Button::new("Save").show(ui); + Button::new("Archive").enabled(false).show(ui); + TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui); + let mut now = shown.get(); + Dialog::new("Options").opened(Bind::bound(&mut now)).buttons([FooterButton::new("Apply", DialogRole::Accept)]).show(ui, |_, _| {}); + shown.set(now); + }); + let host = WindowHost::of(fx.ctx()); + host.keep_access_tree(); + fx.settle(); + + let all = listed(&host, json!({})); + let order = labels(&all); + assert!(place(&order, "Open") < place(&order, "Save") && place(&order, "Save") < place(&order, "Archive"), "tree order: {order:?}"); + let widgets = all["widgets"].as_array().expect("a widget list"); + assert_eq!(all["count"].as_u64(), Some(widgets.len() as u64), "{all}"); + assert_eq!(all["truncated"], false); + assert!(widgets.iter().all(|w| w["depth"].as_u64().is_some_and(|depth| depth >= 1)), "the root is not listed: {all}"); + let ids: Vec<&str> = widgets.iter().filter_map(|w| w["id"].as_str()).collect(); + assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "each node once: {ids:?}"); + let (save, archive) = (widget(&all, "Save"), widget(&all, "Archive")); + assert!(save["enabled"] == true && save["clickable"] == true, "{save}"); + assert!(archive["enabled"] == false, "{archive}"); + let rect = |w: &Value| w["rect"].as_array().map(|r| r.iter().filter_map(Value::as_f64).collect::>()).expect("a rect"); + assert!(rect(widget(&all, "Open"))[3] <= rect(save)[1] + 0.5, "Open lies above Save"); + + let queried = listed(&host, json!({"query": "SAV"})); + assert!(labels(&queried).contains(&"Save".to_owned()) && !labels(&queried).contains(&"Open".to_owned()), "{queried}"); + let buttons = listed(&host, json!({"role": "button"})); + assert!(["Open", "Save", "Archive"].iter().all(|label| labels(&buttons).contains(&(*label).to_owned())), "{buttons}"); + assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["role"].as_str().is_some_and(|role| role.eq_ignore_ascii_case("button")))); + let fields = listed(&host, json!({"role": "textinput"})); + assert_eq!(fields["count"], 1, "the one text field, its role matched ignoring case: {fields}"); + assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != fields["widgets"][0]["id"]), "the field is no button"); + + let (focused, unfocused) = (listed(&host, json!({"focused": true})), listed(&host, json!({"focused": false}))); + assert_eq!(focused["count"].as_u64().unwrap_or(0) + unfocused["count"].as_u64().unwrap_or(0), all["count"].as_u64().unwrap_or(0)); + assert!(focused["widgets"].as_array().into_iter().flatten().all(|w| w["focused"] == true), "{focused}"); + + let first = listed(&host, json!({"limit": 1})); + assert_eq!(first["widgets"].as_array().map(Vec::len), Some(1)); + assert_eq!((first["count"].clone(), first["truncated"].clone()), (all["count"].clone(), json!(true))); + assert_eq!(first["widgets"][0], all["widgets"][0], "the limit keeps the first in tree order"); + assert!(inspect(&host, ViewportId::ROOT, &json!({"nodes": true})).is_err(), "an unknown field is refused"); + + open.set(true); + fx.idle(30); + let tree = host.access_tree_view(ViewportId::ROOT).expect("the kept tree"); + let behind = listed(&host, json!({})); + assert!(!labels(&behind).contains(&"Open".to_owned()), "a node behind the modal is not listed: {behind}"); + assert!(labels(&behind).contains(&"Apply".to_owned()), "the modal's own button is: {behind}"); + assert!(resolve(&tree, &NodeTarget::Label("Open".into()), Declared::Click).is_err(), "nor is it resolved"); + assert!(resolve(&tree, &NodeTarget::Label("apply".into()), Declared::Click).is_ok(), "a label matches ignoring case"); +} + +/// A click by label activates its button once; a secondary click opens the node's context menu; a focus by the id +/// `ui.inspect` lists moves the key focus there. A missing, ambiguous, disabled or undeclared target is refused and +/// queues nothing. +#[trial] +fn click_and_focus_by_label_or_id_reach_the_widget_and_refuse_what_they_cannot_name() { + let saves = Rc::new(Cell::new(0)); + let (counted, name) = (saves.clone(), Rc::new(RefCell::new(String::new()))); + let mut fx = Fixture::new(move |ui| { + if Button::new("Save").show(ui).clicked() { + counted.set(counted.get() + 1); + } + let layer = Button::new("Layer").show(ui); + Menu::context("Layer menu", &layer).show(ui, |ui, _| { + MenuItem::new("Delete layer").show(ui); + }); + Button::new("Copy").id_salt("first copy").show(ui); + Button::new("Copy").id_salt("second copy").show(ui); + Button::new("Archive").enabled(false).show(ui); + TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui); + }); + let (host, ctx) = (WindowHost::of(fx.ctx()), fx.ctx().clone()); + host.keep_access_tree(); + fx.settle(); + let none = |_: usize, _: Pos2| None; + let send = |fx: &mut Fixture, method: &str, params: Value| { + input_method(method, ¶ms, &host, ViewportId::ROOT, &none).expect("an input method").expect("a target it can name"); + fx.run_injected().settle(); + }; + + send(&mut fx, "ui.click", json!({"label": "save"})); + assert_eq!(saves.get(), 1, "the click by label activated Save once"); + + let field = listed(&host, json!({"role": "TextInput"}))["widgets"][0]["id"].clone(); + assert!(field.is_string(), "the text field is listed with its id"); + let before = listed(&host, json!({"focused": true})); + assert!(before["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != field), "the field has no focus yet: {before}"); + send(&mut fx, "ui.focus", json!({"id": field})); + let focused = listed(&host, json!({"focused": true})); + assert_eq!(focused["widgets"].as_array().map(|w| w.iter().map(|w| w["id"].clone()).collect::>()), Some(vec![field]), "{focused}"); + + // Refused while no popup is open, so each is refused for what it names, not for a covered window. + let refused = [ + ("ui.click", json!({"label": "Nothing here"})), + ("ui.click", json!({"id": "1"})), + ("ui.click", json!({"label": "copy"})), + ("ui.click", json!({"label": "Archive"})), + ("ui.click", json!({"label": "Save", "button": "secondary"})), + ("ui.focus", json!({"label": "Nothing here"})), + ]; + for (method, params) in refused { + let answer = input_method(method, ¶ms, &host, ViewportId::ROOT, &none); + assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}"); + assert!(host.injected_idle(), "{method} {params} left nothing waiting"); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing"); + } + fx.settle(); + assert_eq!(saves.get(), 1, "no refused request clicked"); + + assert_eq!(listed(&host, json!({"query": "Delete layer"}))["count"], 0, "the menu starts closed"); + send(&mut fx, "ui.click", json!({"label": "Layer", "button": "secondary"})); + assert!(listed(&host, json!({"query": "Delete layer"}))["count"].as_u64().is_some_and(|n| n >= 1), "the context menu opened"); + assert_eq!(saves.get(), 1, "nothing else was clicked"); +} diff --git a/crates/automation/tests/it/actions.rs b/crates/automation/tests/it/actions.rs index f017fd4f9a..8046137005 100644 --- a/crates/automation/tests/it/actions.rs +++ b/crates/automation/tests/it/actions.rs @@ -5,7 +5,9 @@ use std::rc::Rc; use craft_automation::actions::ActionList; use craft_automation::ui::actions::mock::{FakeActionsHost, action, list_of}; -use craft_automation::ui::actions::{ActionMove, ActionPlace, ActionSelection, ActionsEvent, ActionsPanel, ActionsPanelState, INCLUDE_COLUMN}; +use craft_automation::ui::actions::{ + ActionMove, ActionPlace, ActionSelection, ActionsEvent, ActionsPanel, ActionsPanelState, INCLUDE_COLUMN, StepCells, +}; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Key, Modifiers, Pos2, Ui, Vec2}; @@ -29,16 +31,20 @@ fn app(list: ActionList) -> App { App { state: ActionsPanelState::default(), list, host: FakeActionsHost::prefixed("Run "), events: Vec::new() } } -fn show(ui: &mut Ui, app: &mut App) { +fn show(ui: &mut Ui, app: &mut App, cells: StepCells) { let App { state, list, host, events } = app; - let out = ActionsPanel::new(state, list).host(&*host).show(ui); + let out = ActionsPanel::new(state, list).host(&*host).step_cells(cells).show(ui); events.extend(out.events); } fn rig(app: App) -> (Fixture, Shared) { + rig_cells(app, StepCells::default()) +} + +fn rig_cells(app: App, cells: StepCells) -> (Fixture, Shared) { let shared = Rc::new(RefCell::new(app)); let shown = Rc::clone(&shared); - let mut fixture = Fixture::new(move |ui| show(ui, &mut shown.borrow_mut())); + let mut fixture = Fixture::new(move |ui| show(ui, &mut shown.borrow_mut(), cells)); fixture.room(PANEL); fixture.settle(); (fixture, shared) @@ -248,3 +254,96 @@ fn actions_panel_menu_offers_the_library_commands() { let events: Vec<_> = [C::ClearAll, C::Reset, C::Replace].into_iter().map(|c| c.run(&mut panel, &list, idle)).collect(); assert_eq!(events, [ActionsEvent::ClearAll, ActionsEvent::Reset, ActionsEvent::Replace].map(|event| Some(ActionsMenuAction::Event(event)))); } + +/// A step row has an include and a dialog cell, or with `StepCells::Include` the include cell only; a set row with steps +/// has an include cell whose press reports a toggle of the set, and a set without steps has none. +#[trial] +fn a_set_row_has_an_include_cell_and_the_include_variant_has_no_dialog_column() { + let mut shown = app(two_sets()); + shown.state.expanded.insert("First".into()); + let (fixture, _) = rig(shown); + assert!(fixture.by_label("Include in playback: Run b").is_some(), "a step row has its include cell"); + assert!(fixture.by_label("Show dialog during playback: Run b").is_some(), "and its dialog cell"); + + let mut list = two_sets(); + list.new_set("Hollow").unwrap(); + let mut shown = app(list); + shown.state.expanded.insert("First".into()); + let (mut fixture, shared) = rig_cells(shown, StepCells::Include); + assert!(fixture.by_label("Include in playback: Run b").is_some(), "the include cell stays"); + assert!(fixture.by_label("Show dialog during playback: Run b").is_none(), "the dialog cell is left out"); + assert!(fixture.by_label("Include in playback: Hollow").is_none(), "a set with no steps has no include cell"); + + let cell = node(&fixture, "Include in playback: Alpha"); + click(&mut fixture, cell.center()); + let toggled = take(&shared).into_iter().any(|event| { + matches!(event, ActionsEvent::Toggle(craft_ui::contract::SweepStep::Flip(edit)) + if edit.key == ActionSelection::Set("Alpha".into()) && edit.column == INCLUDE_COLUMN) + }); + assert!(toggled, "a press on a set's include cell reports a toggle of the set"); +} + +/// Shift on a later set row selects the sets between, across an expanded set's action rows; Delete reports the range in +/// one event; a click on an action clears the range. +#[trial] +fn shift_clicking_a_set_selects_the_range_and_delete_reports_it_once() { + let list = list_of(vec![ + action("Loose", None, &["a"]), + action("First", Some("Alpha"), &["b"]), + action("Second", Some("Beta"), &["c"]), + action("Third", Some("Gamma"), &["d"]), + ]); + let (mut fixture, shared) = rig(app(list)); + let (first, last) = (node(&fixture, "Alpha").center(), node(&fixture, "Gamma").center()); + click(&mut fixture, first); + fixture.hold(Modifiers::SHIFT); + click(&mut fixture, last); + fixture.hold(Modifiers::NONE); + let names = ["Alpha", "Beta", "Gamma"].map(str::to_owned).to_vec(); + assert_eq!(shared.borrow().state.selected_sets, names, "the sets between, in list order, not the actions among them"); + + take(&shared); + fixture.key(Key::Delete, Modifiers::NONE).idle(2); + let events = take(&shared); + let deletes: Vec<_> = events.iter().filter(|event| matches!(event, ActionsEvent::Delete(_) | ActionsEvent::DeleteSets(_))).collect(); + assert_eq!(deletes, [&ActionsEvent::DeleteSets(names)], "one event for the range"); + + let row = node(&fixture, "First").center(); + click(&mut fixture, row); + assert!(shared.borrow().state.selected_sets.is_empty(), "a click on an action ends the range"); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Action(1))); +} + +/// A right-click at `pos`, with the pointer moved there first. +fn right_click(fixture: &mut Fixture, pos: Pos2) { + fixture.frame(vec![pointer::moved(pos)]); + fixture.frame(vec![pointer::secondary(pos, true)]); + fixture.frame(vec![pointer::secondary(pos, false)]); + fixture.idle(2); +} + +/// What the row `item` of the menu a right-click on `row` opens reports. +fn menu_ran(fixture: &mut Fixture, shared: &Shared, row: &str, item: &str) -> Vec { + let at = node(fixture, row).center(); + right_click(fixture, at); + let at = node(fixture, item).center(); + click(fixture, at); + take(shared) +} + +/// A right-click on an action or a set selects it and opens its menu, whose rows report their event for that row; +/// Play reports nothing while an action plays. +#[trial] +fn a_rows_menu_selects_the_row_and_reports_its_rows_for_it() { + let (mut fixture, shared) = rig(app(two_sets())); + assert_eq!(menu_ran(&mut fixture, &shared, "First", "Action Options…"), [ActionsEvent::ActionOptions(1)]); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Action(1)), "the right-click selects the action"); + assert_eq!(menu_ran(&mut fixture, &shared, "Second", "Duplicate"), [ActionsEvent::Duplicate(ActionSelection::Action(2))]); + assert_eq!(menu_ran(&mut fixture, &shared, "Alpha", "Delete Set"), [ActionsEvent::Delete(ActionSelection::Set("Alpha".into()))]); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Set("Alpha".into())), "the right-click selects the set"); + + let mut playing = app(two_sets()); + playing.host.playing = true; + let (mut fixture, shared) = rig(playing); + assert_eq!(menu_ran(&mut fixture, &shared, "First", "Play"), [], "Play is off while an action plays"); +} diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index 5191dabc7d..913d02d16a 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -1,4 +1,4 @@ -//! `ControlChannel` deadlines and the loopback server's limits. +//! `ControlChannel` deadlines and the loopback server's limits: connections, request size, authentication. use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; @@ -8,7 +8,7 @@ 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_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; +use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; use craft_automation::server; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; @@ -123,6 +123,70 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { assert!(rx.try_recv().is_err(), "nothing was dispatched"); } +/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error. +fn is_closed(reader: &mut impl BufRead) -> bool { + let mut line = String::new(); + matches!(reader.read_line(&mut line), Ok(0)) +} + +/// 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 connect = || { + let stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let reader = BufReader::new(stream.try_clone().expect("cloned")); + (stream, reader) + }; + // Unauthenticated, so each holds its place until it closes or the authentication deadline passes. + let mut open: Vec = (0..MAX_CONNECTIONS).map(|_| connect().0).collect(); + + let (_extra, mut reader) = connect(); + let refused = read_json(&mut reader).expect("a refusal"); + assert_eq!(refused, json!({"id": null, "ok": false, "error": "connection limit reached"})); + assert!(is_closed(&mut reader), "the refused connection is closed"); + + 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)); + }; + assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}"); + assert!(rx.try_recv().is_err(), "nothing was dispatched"); + drop(open); +} + +/// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the +/// connection closes at once, without waiting for the deadline and without dispatching anything: a client cannot keep +/// guessing on one connection. +#[trial] +fn a_refused_first_frame_closes_the_connection() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let wrong = "f".repeat(TOKEN.len()); + for (first, id) in [("not json".to_owned(), Value::Null), (json!({"id": 4, "method": "auth", "params": {"token": wrong}}).to_string(), json!(4))] + { + 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, "{first}").expect("written"); + assert_eq!(read_json(&mut reader).expect("a refusal"), json!({"id": id, "ok": false, "error": "authentication required"}), "{first}"); + // The server may already have closed while this is written. + let _ = writeln!(stream, "{}", json!({"id": 5, "method": "auth", "params": {"token": TOKEN}})); + assert!(is_closed(&mut reader), "{first}: the connection is closed, the second guess unanswered"); + } + assert!(rx.try_recv().is_err(), "nothing was dispatched"); +} + /// A web page can reach loopback: a browser `POST` whose body is a valid `auth` line is refused at its request line /// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. #[trial] @@ -371,3 +435,60 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() { assert_eq!(after["result"], "still serving"); handler.join().expect("handler ran"); } + +/// Ported from WordCraft (#7317). A request that is complete JSON but ends at EOF with no newline (the client wrote it +/// 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 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"); + }); + let (mut stream, mut reader) = authenticated(server.addr); + stream.write_all(json!({"id": 3, "method": "test.once"}).to_string().as_bytes()).expect("written"); + stream.shutdown(std::net::Shutdown::Write).expect("shut down"); + let reply = read_json(&mut reader).expect("a reply"); + 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"); +} + +/// Ported from WordCraft (#7317). Connections that never authenticate cannot fill the server: past the limit a new +/// one is refused, and a slot freed by a closed connection is admitted again. +#[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"); + 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| { + let stream = TcpStream::connect(addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + read_json(&mut BufReader::new(stream)) + }; + let reply = refused(server.addr).expect("a refusal"); + assert_eq!(reply["ok"], false); + 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)); + } + assert!(rx.try_recv().is_err()); +} diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index 1763a90f72..ad6986f096 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -1,6 +1,6 @@ //! `ui.dialog.*` on typed dialogs through one generic path. -use craft_automation::dialogs::{dialog_method, inspect}; +use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect}; use craft_ui::contract::{Bind, SaveKey}; use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt}; use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; @@ -124,6 +124,41 @@ fn param_dialog_automation_follows_its_rows() { assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom"))); } +/// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that +/// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread. +#[trial] +fn a_field_list_sets_every_field_or_none_and_has_a_limit() { + let ctx = Context::default(); + let mut host = DialogHost::new(); + host.open(HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| { + ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1,"method":"spin|zoom"}"#)).values(Bind::bound(fields)) + })); + let id = inspect(&host)[0]["id"].clone(); + let fields = |host: &DialogHost| inspect(host)[0]["fields"].clone(); + let set = |host: &mut DialogHost, params: Value| call(host, &ctx, "ui.dialog.set", params); + + let listed = json!([{"field": "radius", "value": 4.5}, {"field": "method", "value": "zoom"}]); + assert_eq!(set(&mut host, json!({"dialog": id, "fields": listed})), Ok(Value::Null)); + let settled = fields(&host); + assert_eq!((settled["radius"].as_f64(), &settled["method"]), (Some(4.5), &json!("zoom"))); + + let refused = json!([{"field": "radius", "value": 9}, {"field": "radius", "value": 5000}, {"field": "method", "value": "spin"}]); + assert!(set(&mut host, json!({"dialog": id, "fields": refused})).is_err_and(|e| e.contains("radius"))); + assert_eq!(fields(&host), settled, "a refusal in the middle sets nothing"); + + let too_many: Vec = (0..=MAX_DIALOG_FIELDS).map(|_| json!({"field": "radius", "value": 2})).collect(); + assert!(set(&mut host, json!({"dialog": id, "fields": too_many})).is_err()); + assert_eq!(fields(&host), settled, "a list over the limit sets nothing"); + + let unnamed = json!([{"field": "radius", "value": 9}, {"value": 1}]); + assert!(set(&mut host, json!({"dialog": id, "fields": unnamed})).is_err()); + assert_eq!(fields(&host), settled, "an item without a field sets nothing"); + + let both = json!({"dialog": id, "field": "radius", "value": 9, "fields": [{"field": "radius", "value": 8}]}); + assert!(set(&mut host, both).is_err()); + assert_eq!(fields(&host), settled, "`field` beside `fields` sets nothing"); +} + /// `"top"` names the top dialog of the stack: a child over its parent takes the field, the parent keeps its own; with /// nothing open the request says so. #[trial] diff --git a/crates/automation/tests/it/dock.rs b/crates/automation/tests/it/dock.rs new file mode 100644 index 0000000000..91e1fa97f0 --- /dev/null +++ b/crates/automation/tests/it/dock.rs @@ -0,0 +1,65 @@ +//! `ui.dock.apply` on a workspace, with the host's permissions and lock. + +use craft_automation::dock::{dock_method, inspect}; +use craft_behavior::DockSide; +use craft_behavior::dock::{Action, DockError, DockPlacement, Layout, Node, PanelState, Permissions, Workspace}; +use craft_ui::contract::PlainData; +use craft_ui::docking::{PanelSpec, PanelSpecs}; +use craft_ui::testing::trial; +use serde_json::{Value, json}; + +/// Two panels, the first protected as a canvas is. +#[derive(PlainData)] +struct Panels; + +impl PanelSpecs for Panels { + fn spec(&self, panel: &u8) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } + + fn permissions(&self, panel: &u8) -> Permissions { + if *panel == 1 { Permissions::PROTECTED } else { Permissions::ALL } + } +} + +fn call(workspace: &mut Workspace, locked: bool, params: Value) -> Result { + dock_method(workspace, &Panels, locked, "ui.dock.apply", ¶ms).expect("a ui.dock method") +} + +/// A JSON action applies to the workspace with the host's permissions and lock; a refused one replies the dock error +/// and changes nothing, and `inspect` lists the workspace. +#[trial] +fn a_dock_action_from_json_applies_to_the_workspace() { + let mut workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![1u8, 2], 0)), Vec::new())); + assert_eq!(workspace.layout().panel_state(&2), PanelState::Open); + + assert_eq!(call(&mut workspace, false, json!({"action": {"Activate": {"panel": 2}}})), Ok(json!({"applied": []}))); + assert_eq!(workspace.layout().panel_state(&2), PanelState::Front, "the activate action brings panel 2 to the front"); + + let before = workspace.clone(); + assert_eq!( + call(&mut workspace, false, json!({"action": Action::close(1u8)})), + Err(DockError::NotAllowed.to_string()), + "the host's permissions protect panel 1" + ); + assert_eq!(workspace, before, "a refused action leaves the workspace as it was"); + assert!(call(&mut workspace, false, json!({"action": Action::activate(1u8), "panel": 1})).is_err(), "an unknown key is refused"); + assert!(call(&mut workspace, false, json!({})).is_err(), "a missing action is refused"); + assert!(call(&mut workspace, false, json!({"action": {"Activate": {}}})).is_err()); + assert_eq!(workspace, before); + + let split = Action::move_beside(2u8, 1, DockPlacement::Split(DockSide::End)); + assert_eq!(call(&mut workspace, true, json!({"action": split})), Err(DockError::NotAllowed.to_string()), "a locked workspace refuses a move"); + assert_eq!(workspace, before); + assert_eq!(call(&mut workspace, true, json!({"action": Action::activate(1u8)})), Ok(json!({"applied": []})), "a locked workspace activates"); + assert_eq!(workspace.layout().panel_state(&1), PanelState::Front); + + assert_eq!(call(&mut workspace, false, json!({"action": Action::close(2u8)})), Ok(json!({"applied": [2]})), "the reply lists the closed panel"); + assert_eq!(workspace.layout().panel_state(&2), PanelState::Hidden); + + assert!(dock_method(&mut workspace, &Panels, false, "ui.dock.close", &json!({})).is_none()); + + let listed = inspect(&workspace); + assert_eq!(serde_json::from_value::>(listed).ok(), Some(workspace.clone()), "inspect lists the whole workspace"); + assert_eq!(workspace.layout().panels(), vec![&1]); +} diff --git a/crates/automation/tests/it/files.rs b/crates/automation/tests/it/files.rs new file mode 100644 index 0000000000..6efa12062a --- /dev/null +++ b/crates/automation/tests/it/files.rs @@ -0,0 +1,71 @@ +//! `ui.pick` at the protocol boundary. + +use std::path::PathBuf; + +use craft_automation::files::pick_method; +use craft_host::{Files, NoPickFiles, PickRequest, Picked, ScriptedFiles}; +use craft_ui::testing::trial; +use serde_json::{Value, json}; + +fn call(files: &dyn Files, params: Value) -> Result { + pick_method(files, "ui.pick", ¶ms).expect("ui.pick is the pick method") +} + +fn path(p: &str) -> PathBuf { + PathBuf::from(p) +} + +/// Each field reaches the service as its `Picked`; with picks on screen the oldest is answered; a bad request is +/// refused with the field list and answers nothing; a service that takes no automated answers says so. +#[trial] +fn ui_pick_answers_the_next_picker_and_refuses_bad_params() { + let answered = Ok(json!({"answered": "next"})); + let files = ScriptedFiles::new(); + assert_eq!(call(&files, json!({"files": ["/w/a.pdf", "/w/b.pdf"]})), answered); + assert_eq!(call(&files, json!({"folder": "/w/out"})), answered); + assert_eq!(call(&files, json!({"save": "/w/c.pdf"})), answered); + assert_eq!(call(&files, json!({"cancel": true, "files": null})), answered, "a null field is omitted"); + let picked: Vec = (0..4) + .map(|_| { + let id = files.pick(PickRequest::open("document")); + files.take_answer(id).expect("a queued answer comes at once") + }) + .collect(); + assert_eq!( + picked, + [ + Picked::Paths(vec![path("/w/a.pdf"), path("/w/b.pdf")]), + Picked::Paths(vec![path("/w/out")]), + Picked::Paths(vec![path("/w/c.pdf")]), + Picked::Cancelled + ] + ); + + let held = ScriptedFiles::held(); + let oldest = held.pick(PickRequest::open("first")); + let newest = held.pick(PickRequest::open("second")); + assert_eq!(call(&held, json!({"files": ["/w/first.pdf"]})), answered); + assert_eq!(held.take_answer(oldest), Some(Picked::Paths(vec![path("/w/first.pdf")])), "the oldest open pick is answered"); + assert_eq!(held.take_answer(newest), None); + assert_eq!(held.open(), 1); + + for bad in [ + json!({"files": ["/w/a.pdf"], "save": "/w/b.pdf"}), + json!({}), + json!({"files": []}), + json!({"files": ["/w/a.pdf", 3]}), + json!({"save": 3}), + json!({"cancel": false}), + json!({"path": "/w/a.pdf"}), + ] { + let error = call(&files, bad.clone()).expect_err("refused"); + assert!(error.contains("files, folder, save, cancel"), "{bad}: {error}"); + } + assert_eq!(call(&files, json!({"folder": "/w/after"})), answered); + let id = files.pick(PickRequest::folder("export")); + assert_eq!(files.take_answer(id), Some(Picked::Paths(vec![path("/w/after")])), "no refused request queued an answer"); + + let unsupported = call(&NoPickFiles::default(), json!({"cancel": true})).expect_err("a service without automated answers refuses"); + assert!(!unsupported.contains("files, folder, save, cancel"), "an unsupported service is not a field-list refusal: {unsupported}"); + assert!(pick_method(&files, "ui.click", &json!({})).is_none()); +} diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index 047ef22da7..1637690af8 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -2,9 +2,12 @@ // Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +pub(crate) mod access; pub(crate) mod actions; pub(crate) mod agents; pub(crate) mod control; pub(crate) mod dialogs; +pub(crate) mod dock; +pub(crate) mod files; pub(crate) mod screenshot; pub(crate) mod synthetic; diff --git a/crates/automation/tests/it/screenshot.rs b/crates/automation/tests/it/screenshot.rs index 56b9fa63ab..e9f06c409e 100644 --- a/crates/automation/tests/it/screenshot.rs +++ b/crates/automation/tests/it/screenshot.rs @@ -1,5 +1,6 @@ //! `Captures`: admission budgets, settling, deadlines, cancellation, document identity, the -//! geometry epoch per viewport, the window a capture names, and the image checks. +//! geometry epoch per viewport, the window a capture names, the image checks, and the region a +//! reply is cropped to. use std::cell::RefCell; use std::sync::Arc; @@ -396,6 +397,98 @@ fn the_image_must_match_the_issued_viewport() { } } +/// The first pixel of a PNG, decoded. +fn first_pixel(png: &[u8]) -> [u8; 4] { + let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().expect("a PNG"); + let mut pixels = vec![0; reader.output_buffer_size()]; + reader.next_frame(&mut pixels).expect("a frame"); + [pixels[0], pixels[1], pixels[2], pixels[3]] +} + +/// A region is checked against the window at admission (and again when the layout changed before issue) and refused +/// when it does not lie inside; the whole window is reserved for it. The reply crops it at the image's own scale to +/// the window, so a fitted image is cropped at its fit, and both reply shapes carry the window's point scale. +#[trial] +fn a_region_is_cropped_at_the_image_scale_and_one_outside_the_window_is_refused() { + use craft_automation::control::ControlChannel; + use craft_automation::screenshot::ScreenshotParams; + use serde_json::json; + + let params = |value| ScreenshotParams::from_params(&value); + let region = Rect::from_min_max(Pos2::new(10.0, 5.0), Pos2::new(60.0, 30.0)); + assert_eq!(params(json!({"path": "a.png", "region": [10, 5, 60, 30]})).map(|p| (p.path, p.region)), Ok((Some("a.png".to_owned()), Some(region)))); + for bad in [json!({"region": [60, 5, 10, 30]}), json!({"region": [10, 5, 60]}), json!({"region": [10, 5, 60, "30"]}), json!({"zoom": 2})] { + assert!(params(bad.clone()).is_err(), "{bad} is refused"); + } + + let ctx = Context::default(); + let now = motion::now(); + let (_transport, requests) = channel(); + let mut control = ControlChannel::new(requests); + let mut g = geometry(100.0, 50.0); + g.pixels_per_point = 2.0; + control.captures.note_geometry(ViewportId::ROOT, g); + let request = |token: u64, region: Rect| { + let (tx, rx) = channel(); + let mut request = ScreenshotRequest::new(token, ViewportId::ROOT, tx); + request.region = Some(region); + (request, rx) + }; + + let (outside, _) = request(1, Rect::from_min_max(Pos2::new(90.0, 40.0), Pos2::new(110.0, 60.0))); + let e = control.captures.admit(outside, now).map_err(|(_, e)| e).expect_err("outside the window"); + assert!(e.contains("inside"), "{e}"); + assert_eq!(control.captures.pending(), 0); + + let (inside, rx) = request(2, region); + control.captures.admit(inside, now).map_err(|(_, e)| e).expect("inside the window"); + assert_eq!(control.captures.reserved_bytes(), 200 * 100 * 4, "the whole window is reserved"); + let mut picture = ColorImage::filled([200, 100], Color32::BLUE); + picture.pixels[10 * 200 + 20] = Color32::RED; + issue_one(&mut control.captures, &ctx, now).complete(Arc::new(picture)); + let finished = control.captures.drain(now, None); + let mut written = Vec::new(); + control.finish_captures(finished, &mut |_, bytes| { + written = bytes.to_vec(); + Ok(()) + }); + let reply = rx.try_recv().expect("a reply"); + assert_eq!((reply["result"]["width"].clone(), reply["result"]["height"].clone()), (json!(100), json!(50)), "{reply}"); + assert_eq!(reply["result"]["pixels_per_point"], 2.0); + assert!(written.is_empty(), "no path, no file"); + use base64::Engine as _; + let png = base64::engine::general_purpose::STANDARD.decode(reply["result"]["base64"].as_str().expect("an inline PNG")).expect("base64"); + assert_eq!(first_pixel(&png), Color32::RED.to_array(), "the crop starts at the region's corner at two pixels per point"); + + // A fitted surface: 600×300 points through a 400-pixel texture side come back as 400×200. + let mut fitted = geometry(600.0, 300.0); + fitted.max_texture_side = 400; + control.captures.note_geometry(ViewportId::ROOT, fitted); + let (mut half, rx) = request(3, Rect::from_min_max(Pos2::new(300.0, 150.0), Pos2::new(600.0, 300.0))); + half.path = Some("half.png".into()); + control.captures.admit(half, now).map_err(|(_, e)| e).expect("inside the window"); + issue_one(&mut control.captures, &ctx, now).complete(filled([400, 200], Color32::WHITE)); + let finished = control.captures.drain(now, None); + control.finish_captures(finished, &mut |path, bytes| { + assert_eq!(path, "half.png"); + written = bytes.to_vec(); + Ok(()) + }); + let reply = rx.try_recv().expect("a reply"); + assert_eq!((reply["result"]["width"].clone(), reply["result"]["height"].clone()), (json!(200), json!(100)), "{reply}"); + assert_eq!(reply["result"]["pixels_per_point"], 1.0); + assert!(!written.is_empty(), "the PNG went to the writer"); + + // A region that a shrink before issue leaves outside is refused then, not cut to a smaller picture. + let (late, _reply) = request(4, region); + control.captures.admit(late, now).map_err(|(_, e)| e).expect("inside the window"); + control.captures.note_geometry(ViewportId::ROOT, geometry(40.0, 20.0)); + let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, now, None); + assert!(callbacks.is_empty(), "nothing is captured for it"); + assert!(finished.len() == 1 && error(&finished[0]).contains("inside"), "refused at issue"); + assert_eq!(control.captures.pending(), 0); +} + const ROOT_SIZE: Vec2 = Vec2::new(800.0, 600.0); const CHILD_SIZE: Vec2 = Vec2::new(400.0, 300.0); diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 494cc848dd..ee2c484f6c 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -5,7 +5,8 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::synthetic::{At, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::access::NO_TREE; +use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -339,7 +340,8 @@ fn queued_input_is_withdrawn_when_its_target_changes() { } /// An unknown field, a wrong type, an unknown name, too many clicks or a point too far out refuses the whole request -/// before any of it is queued: no half-queued press or held key is left behind. +/// before any of it is queued: no half-queued press or held key is left behind. A node target takes no point, repeat, +/// hold, modifier or button but the secondary one, and names exactly one of `id` and `label`. #[trial] fn bad_input_params_are_refused_before_anything_is_queued() { let mut rig = Rig::new(); @@ -352,21 +354,90 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.click", json!({"x": 10, "button": "thumb"})), ("ui.click", json!({"x": 10, "hold": true, "count": MAX_CLICKS + 1})), ("ui.click", json!({"x": far, "hold": true})), - ("ui.move", json!({"x": 10, "nudge": 1})), - ("ui.move", json!({"x": 10, "rest": "long"})), - ("ui.move", json!({"x": 10, "coordinates": "page"})), - ("ui.move", json!({"y": -far})), + ("ui.move", json!({"x": 10, "y": 10, "nudge": 1})), + ("ui.move", json!({"x": 10, "y": 10, "rest": "long"})), + ("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})), + ("ui.move", json!({"x": 10, "y": -far})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), ("ui.ime", json!({"preedit": "ab", "cursor": [1, 9]})), + ("ui.click", json!({"x": 10, "y": 10, "label": "Save"})), + ("ui.click", json!({"label": "Save", "count": 2})), + ("ui.click", json!({"label": "Save", "hold": true})), + ("ui.click", json!({"label": "Save", "shift": true})), + ("ui.click", json!({"label": "Save", "button": "middle"})), + ("ui.click", json!({"id": "12", "button": "middle"})), + ("ui.click", json!({"id": "twelve"})), + ("ui.focus", json!({"id": "12", "label": "Save"})), + ("ui.focus", json!({})), + ("ui.drop", json!({"paths": []})), + ("ui.drop", json!({"paths": ["a.pdf"], "alt": true})), ]; - for (method, params) in refused { - let answer = input_method(method, ¶ms, &host, ViewportId::ROOT, &map); + for (method, params) in &refused { + let answer = input_method(method, params, &host, ViewportId::ROOT, &map); assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}"); assert!(host.injected_idle(), "{method} {params} left nothing waiting"); assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing"); } + // This window keeps no access tree, so a node request is refused there whatever it says; its parameters alone + // refuse the node rows, and the secondary button, a node's context menu, is allowed. + for (method, params) in refused.iter().filter(|(_, params)| params.get("id").is_some() || params.get("label").is_some() || params == &json!({})) { + let by_params = if *method == "ui.focus" { Focus::from_params(params).is_err() } else { Click::from_params(params).is_err() }; + assert!(by_params, "{method} {params} is refused by its parameters"); + } + assert!(Click::from_params(&json!({"label": "Save", "button": "secondary"})).is_ok()); +} + +/// A key whose press moves the focus (Tab from one field to the next) still has its release carried out: the release +/// is not cancelled as input whose focus changed, no key stays down, and the waiter is answered as processed. The +/// framework takes the Tab press it acts on out of egui's input, so egui's fields never read it. +#[trial] +fn a_key_release_is_carried_out_after_its_press_moves_focus() { + use craft_automation::control::{ControlChannel, ControlRequest, Reply}; + + let passes: Rc>> = Rc::default(); + let rects = Rc::new(Cell::new([Rect::NOTHING; 2])); + let (seen, shown) = (passes.clone(), rects.clone()); + let (first, second) = (Rc::new(RefCell::new(String::new())), Rc::new(RefCell::new(String::new()))); + let fx = Fixture::new(move |ui| { + let a = TextField::new("First", Bind::bound(&mut *first.borrow_mut())).show(ui).response.rect; + let b = TextField::new("Second", Bind::bound(&mut *second.borrow_mut())).show(ui).response.rect; + shown.set([a, b]); + seen.borrow_mut().push(ui.input(|i| Seen { any_key_down: !i.keys_down.is_empty(), events: i.events.clone(), ..Seen::default() })); + }); + let mut rig = Rig { fx, passes }; + rig.fx.settle(); + let at = rects.get()[0].center(); + rig.send("ui.click", json!({"x": at.x, "y": at.y})); + let before = rig.fx.focused(); + assert!(before.is_some(), "the click focused the first field"); + + let (_transport, requests) = std::sync::mpsc::channel(); + let mut channel = ControlChannel::new(requests); + let host = rig.host(); + rig.take(); + input_method("ui.key", &json!({"key": "Tab"}), &host, ViewportId::ROOT, &map).expect("a method").expect("valid"); + let (req, reply) = ControlRequest::new("ui.key", json!({"key": "Tab"})); + channel.settle(req, Reply::AfterInput, None, 0.0); + let mut answer = None; + for _ in 0..32 { + rig.fx.frame(Vec::new()); + channel.poll_input(&host); + answer = reply.try_recv().ok(); + if answer.is_some() { + break; + } + } + rig.fx.frame(Vec::new()); + + let answer = answer.expect("the waiter is answered"); + assert_eq!(answer["ok"], true, "processed, not cancelled: {answer}"); + assert!(rig.fx.focused().is_some() && rig.fx.focused() != before, "the press moved the focus"); + let passes = rig.take(); + let tab = |event: &Event| matches!(event, Event::Key { key: Key::Tab, pressed: true, .. }); + assert!(!passes.iter().any(|pass| pass.events.iter().any(tab)), "the Tab press the framework took reaches no field in egui"); + assert!(passes.last().is_some_and(|pass| !pass.any_key_down), "no key stays down"); } /// `ui.ime` queues behind the input before it: typed text, then the composition with its converted segment, then @@ -415,10 +486,50 @@ fn ui_ime_reaches_a_focused_text_field_as_a_preedit_then_a_commit_in_order() { /// A NaN or infinite point of a request is an error at the request, in either coordinate space, not a panic in the pass. #[trial] fn a_point_that_is_not_finite_is_refused() { + let no_controls = &|_: &_| Err(NO_TREE.to_owned()); for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { for at in [At::Screen(pos2(bad, 1.0)), At::Screen(pos2(1.0, bad)), At::Document(pos2(bad, 1.0), 0)] { - assert_eq!(at.resolve(&|_, p| Some(p)), Err(NOT_FINITE.to_owned()), "{at:?}"); + assert_eq!(at.resolve(&|_, p| Some(p), no_controls), Err(NOT_FINITE.to_owned()), "{at:?}"); } } - assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_, _| None), Ok(pos2(3.0, 4.0))); + assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_, _| None, no_controls), Ok(pos2(3.0, 4.0))); +} + +/// `ui.wheel` in lines queues whole notches in the line unit, clamped; without `unit` the turn is in points; an +/// unknown unit is refused. +#[trial] +fn a_wheel_in_lines_turns_by_notches() { + fn turn(rig: &mut Rig, params: Value) -> (egui::MouseWheelUnit, egui::Vec2) { + rig.send("ui.wheel", params); + rig.take() + .into_iter() + .flat_map(|pass| pass.events) + .find_map(|event| match event { + Event::MouseWheel { unit, delta, .. } => Some((unit, delta)), + _ => None, + }) + .expect("a pass saw the turn") + } + let mut rig = Rig::new(); + assert_eq!(turn(&mut rig, json!({"x": 30, "y": 20, "dy": 2.4, "unit": "lines"})), (egui::MouseWheelUnit::Line, egui::vec2(0.0, 2.0))); + assert_eq!(turn(&mut rig, json!({"dy": 500, "unit": "lines"})).1, egui::vec2(0.0, 100.0), "notches are clamped"); + assert_eq!(turn(&mut rig, json!({"dy": 2.4})), (egui::MouseWheelUnit::Point, egui::vec2(0.0, 2.4))); + let refused = input_method("ui.wheel", &json!({"dy": 1, "unit": "pages"}), &rig.host(), ViewportId::ROOT, &map); + assert!(matches!(refused, Some(Err(_))), "{refused:?}"); + assert!(rig.host().injected_idle(), "the refused turn queued nothing"); +} + +/// `ui.move` requires both `x` and `y`: omitting either coordinate refuses the request before anything is queued +/// instead of silently moving to 0 on the missing axis. +#[trial] +fn ui_move_refuses_a_missing_coordinate() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + for params in [json!({"x": 1}), json!({"y": 1}), json!({})] { + let answer = input_method("ui.move", ¶ms, &host, ViewportId::ROOT, &map); + assert!(matches!(answer, Some(Err(_))), "ui.move {params} is refused: {answer:?}"); + assert!(host.injected_idle(), "ui.move {params} left nothing waiting"); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "ui.move {params} queued nothing"); + } } diff --git a/crates/behavior/src/canvas/mod.rs b/crates/behavior/src/canvas/mod.rs index 9ff5c9fb3b..0851e9509e 100644 --- a/crates/behavior/src/canvas/mod.rs +++ b/crates/behavior/src/canvas/mod.rs @@ -8,9 +8,9 @@ mod view; pub mod zoom; pub use history::{ViewHistory, ViewPlace}; -pub use units::{RulerUnits, Ticks}; +pub use units::{RulerUnits, TickLabels, Ticks}; pub use view::{CanvasView, resize_cursor}; -pub use zoom::ZoomLadder; +pub use zoom::{ZoomFloor, ZoomScheme}; /// A canvas body's mapping from canvas coordinates to its layer: `screen = canvas * scale + offset`. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/behavior/src/canvas/units.rs b/crates/behavior/src/canvas/units.rs index a9ddbf6937..946e0d0aba 100644 --- a/crates/behavior/src/canvas/units.rs +++ b/crates/behavior/src/canvas/units.rs @@ -2,6 +2,8 @@ //! lives here; the text of a distance or a tick is written by craft-ui over `Env::units`, so no second number //! formatter exists. +use std::ops::RangeInclusive; + /// How a ruler divides its unit at a zoom. #[derive(Clone, Copy, Debug)] #[non_exhaustive] @@ -19,8 +21,20 @@ pub enum Ticks { Custom(fn(f64) -> (f64, u32)), } -/// The ruler unit of one document axis: its size and its ticks. Rulers label their ticks with it; guides use it for -/// the readout of a drag, their AccessKit values and Shift's snap to the ticks. +/// How a ruler writes the number at a labelled tick. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum TickLabels { + /// PhotoCraft's: the distance from the zero point with no minus sign, a step under 1 with at least two decimals + /// (`2.50`, `0.30`, `1.0000` on a sixteenth-inch ruler). + #[default] + Distance, + /// VectorCraft's: the signed position, with only the decimals the tick needs (`-2.5`, `0.3`, `1`). + Signed, +} + +/// The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it; +/// guides use it for the readout of a drag, their AccessKit values and Shift's snap to the ticks. #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub struct RulerUnits { @@ -28,6 +42,8 @@ pub struct RulerUnits { pub per_doc: f64, /// How the ticks are spaced. pub ticks: Ticks, + /// How the labelled ticks are written. + pub labels: TickLabels, } impl Ticks { @@ -38,9 +54,16 @@ impl Ticks { } impl RulerUnits { - /// Ruler units of `per_doc` per document unit, spaced by `ticks`. + /// Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`]. pub const fn new(per_doc: f64, ticks: Ticks) -> Self { - Self { per_doc, ticks } + Self { per_doc, ticks, labels: TickLabels::Distance } + } + + /// The units with their ticks written as `labels`. + #[must_use] + pub const fn with_labels(mut self, labels: TickLabels) -> Self { + self.labels = labels; + self } /// Whole document pixels. @@ -78,22 +101,31 @@ impl RulerUnits { (position - zero) * self.per_doc } - /// The 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), a smaller one at least two (PhotoCraft's - /// `0.50`), more when it has them (0.025). - pub fn label_decimals(&self, step: f64) -> usize { - match self.ticks { + /// 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, - _ if step.abs() < 1.0 => step_decimals(step).max(2), + _ if step.abs() < 1.0 && self.labels == TickLabels::Distance => step_decimals(step).max(2), _ => step_decimals(step), + }; + match self.labels { + TickLabels::Distance => most..=most, + TickLabels::Signed => 0..=most, } } /// The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`: - /// the distance without a minus sign left of or above the zero point (PhotoCraft's `ruler_label`), rounded when - /// the ticks are whole. + /// under [`TickLabels::Distance`] the distance without a minus sign left of or above the zero point (PhotoCraft's + /// `ruler_label`), under [`TickLabels::Signed`] the value itself; rounded when the ticks are whole. pub fn label_value(&self, value: f64, step: f64) -> f64 { - if self.label_decimals(step) == 0 { value.abs().round() } else { value.abs() } + let value = match self.labels { + TickLabels::Distance => value.abs(), + TickLabels::Signed => value, + }; + if *self.label_decimals(step).end() == 0 { value.round() } else { value } } } diff --git a/crates/behavior/src/canvas/zoom.rs b/crates/behavior/src/canvas/zoom.rs index d4d7533303..00fca12994 100644 --- a/crates/behavior/src/canvas/zoom.rs +++ b/crates/behavior/src/canvas/zoom.rs @@ -1,4 +1,4 @@ -//! Zoom rules as pure functions on a [`CanvasView`]: Photoshop's zoom range and Zoom In / Zoom Out ladder, Fit on +//! Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zoom In / Zoom Out rungs, Fit on //! Screen and Fill Screen, a zoom about a point and the anchors of wheel zoom. //! //! Zoom levels here are **device zoom**: device pixels per document unit, so 1 is 100 % at any interface scale. @@ -7,7 +7,7 @@ //! `zoom` back into its own view type. //! //! Every way of setting the zoom (wheel, Zoom tool, menu, zoom field, navigator, automation) clamps through -//! [`ZoomLadder::clamp`], so no control can pull the zoom into a narrower range of its own. +//! [`ZoomScheme::clamp`], so no control can pull the zoom into a narrower range of its own. use super::view::CanvasView; use emath::{Pos2, Rect as ScreenRect, Vec2 as ScreenVec}; @@ -18,92 +18,145 @@ use std::ops::RangeInclusive; const RUNG_TOLERANCE_UP: f64 = 1.001; const RUNG_TOLERANCE_DOWN: f64 = 0.999; -/// Photoshop's zoom range and the Zoom In / Zoom Out ladder, measured on Photoshop 25.4: up to -/// 12800 %, down to where the document's shorter side is 2 px on screen (no lower than 0.1 % for -/// a ladder step). A ladder step goes from any zoom to the next rung (880 %: in to 1200 %, out to -/// 800 %). -pub struct ZoomLadder; +/// Photoshop's Zoom In / Zoom Out rungs (1 = 100 %), measured on Photoshop 25.4. +const PHOTOSHOP_RUNGS: [f64; 33] = [ + 0.001, + 0.002, + 0.003, + 0.004, + 0.005, + 0.007, + 0.01, + 0.015, + 0.02, + 0.03, + 0.04, + 0.05, + 0.0625, + 1.0 / 12.0, + 0.125, + 1.0 / 6.0, + 0.25, + 1.0 / 3.0, + 0.5, + 2.0 / 3.0, + 1.0, + 2.0, + 3.0, + 4.0, + 5.0, + 6.0, + 7.0, + 8.0, + 12.0, + 16.0, + 32.0, + 64.0, + 128.0, +]; -impl ZoomLadder { - /// 12800 %. - pub const MAX: f64 = 128.0; +/// The least zoom: the document's shorter side that many device pixels, or a fixed zoom in scheme units. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub enum ZoomFloor { + /// The document's shorter side is this many device pixels. + ShorterSide(f64), + /// A fixed zoom in scheme units. + Fixed(f64), +} - /// Zoom In / Zoom Out rungs (1 = 100 %). - pub const STEPS: [f64; 33] = [ - 0.001, - 0.002, - 0.003, - 0.004, - 0.005, - 0.007, - 0.01, - 0.015, - 0.02, - 0.03, - 0.04, - 0.05, - 0.0625, - 1.0 / 12.0, - 0.125, - 1.0 / 6.0, - 0.25, - 1.0 / 3.0, - 0.5, - 2.0 / 3.0, - 1.0, - 2.0, - 3.0, - 4.0, - 5.0, - 6.0, - 7.0, - 8.0, - 12.0, - 16.0, - 32.0, - 64.0, - 128.0, - ]; +/// A zoom range and its Zoom In and Out rungs in scheme units (1 = its 100 %); `hundred` is the device zoom of +/// 100 %. A step goes from any zoom to the next rung (880 %: in to 1200 %, out to 800 %). +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct ZoomScheme { + /// The Zoom In and Out rungs, lowest first. + pub rungs: &'static [f64], + /// The greatest zoom. + pub max: f64, + /// The least zoom. + pub floor: ZoomFloor, + /// The device zoom of 100 %. + pub hundred: f64, +} - /// The lowest zoom for a document of `size` units: its shorter side 2 device pixels. An empty - /// size (a view before its first frame) gives the lowest rung. - pub fn min(size: Size) -> f64 { - match size.width.min(size.height) { - short if short.is_finite() && short > 0.0 => (2.0 / short).min(Self::MAX), - _ => Self::STEPS[0], +impl ZoomScheme { + /// Photoshop's: 33 rungs, up to 12800 %, the shorter side 2 px at the least. + pub const PHOTOSHOP: ZoomScheme = ZoomScheme { rungs: &PHOTOSHOP_RUNGS, max: 128.0, floor: ZoomFloor::ShorterSide(2.0), hundred: 1.0 }; + + /// Illustrator's: 26 stops from 3.13 % to 64000 %. + pub const ILLUSTRATOR: ZoomScheme = ZoomScheme { + rungs: &[ + 0.0313, 0.0417, 0.0625, 0.0833, 0.125, 0.1667, 0.25, 0.3333, 0.5, 0.6667, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 24.0, 32.0, + 48.0, 64.0, 128.0, 256.0, 640.0, + ], + max: 640.0, + floor: ZoomFloor::Fixed(0.0313), + hundred: 1.0, + }; + + /// The scheme with `device` as the device zoom of 100 %. + pub const fn with_hundred(self, device: f64) -> Self { + ZoomScheme { hundred: device, ..self } + } + + /// The least device zoom for a document of `size`. An empty size (a view before its first frame) gives the lowest + /// rung. + pub fn min(&self, size: Size) -> f64 { + match self.floor { + ZoomFloor::ShorterSide(pixels) => match size.width.min(size.height) { + short if short.is_finite() && short > 0.0 => (pixels / short).min(self.max_device()), + _ => self.rungs.first().map_or(self.hundred, |rung| rung * self.hundred), + }, + ZoomFloor::Fixed(zoom) => zoom * self.hundred, } } - /// `zoom` within the range for a document of `size`; a zoom that is not a finite number - /// becomes 100 %. - pub fn clamp(zoom: f64, size: Size) -> f64 { - if zoom.is_finite() { zoom.min(Self::MAX).max(Self::min(size)) } else { 1.0 } + /// The greatest device zoom. + pub fn max_device(&self) -> f64 { + self.max * self.hundred } - /// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `zoom`: the next rung past it (a zoom - /// within 0.1 % of a rung counts as on it), within the document's range. - pub fn step(zoom: f64, dir: i32, size: Size) -> f64 { - Self::step_in_range(zoom, dir, Self::min(size)..=Self::MAX) + /// `device` within the range for a document of `size`; a zoom that is not a finite number becomes 100 %. + pub fn clamp(&self, device: f64, size: Size) -> f64 { + if device.is_finite() { device.min(self.max_device()).max(self.min(size)) } else { self.hundred } } - /// [`step`](Self::step) within an explicit range (a navigator or a zoom field with bounds of - /// its own). - pub fn step_in_range(zoom: f64, dir: i32, range: RangeInclusive) -> f64 { + /// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `device`: the next rung past it (a zoom within 0.1 % of a rung + /// counts as on it), within the document's range. + pub fn step(&self, device: f64, dir: i32, size: Size) -> f64 { + self.step_in_range(device, dir, self.min(size)..=self.max_device()) + } + + /// [`step`](Self::step) within an explicit range of device zoom (a navigator or a zoom field with bounds of its + /// own). + pub fn step_in_range(&self, device: f64, dir: i32, range: RangeInclusive) -> f64 { let (lo, hi) = range.into_inner(); - let z = if zoom.is_finite() { zoom.min(hi).max(lo) } else { 1.0 }; + let z = if device.is_finite() { device.min(hi).max(lo) } else { self.hundred }; + let rungs = self.rungs.iter().map(|rung| rung * self.hundred); let next = if dir > 0 { - Self::STEPS.iter().copied().find(|s| *s > z * RUNG_TOLERANCE_UP).unwrap_or(hi) + rungs.clone().find(|s| *s > z * RUNG_TOLERANCE_UP).unwrap_or(hi) } else { - Self::STEPS.iter().rev().copied().find(|s| *s < z * RUNG_TOLERANCE_DOWN).unwrap_or(z) + rungs.rev().find(|s| *s < z * RUNG_TOLERANCE_DOWN).unwrap_or(z) }; if next.is_finite() { next.min(hi).max(lo) } else { z } } - /// A zoom field's range in percent: the document's range widened to include `zoom` itself. - /// A field narrower than the zoom would clamp it and write it back every pass. - pub fn percent_range(zoom: f64, size: Size) -> RangeInclusive { - let z = if zoom.is_finite() { zoom } else { 1.0 }; - (Self::min(size).min(z) * 100.0)..=(Self::MAX.max(z) * 100.0) + /// A zoom field's range in percent: the document's range widened to include `device` itself. A field narrower than + /// the zoom would clamp it and write it back every pass. + pub fn percent_range(&self, device: f64, size: Size) -> RangeInclusive { + let z = if device.is_finite() { device } else { self.hundred }; + self.percent(self.min(size).min(z))..=self.percent(self.max_device().max(z)) + } + + /// `device` zoom as percent of the scheme's 100 %. + pub fn percent(&self, device: f64) -> f64 { + device / self.hundred * 100.0 + } + + /// The device zoom of `percent` of the scheme's 100 %. + pub fn device(&self, percent: f64) -> f64 { + percent / 100.0 * self.hundred } } @@ -113,9 +166,9 @@ pub fn device(view: &CanvasView, pixels_per_point: f32) -> f64 { } /// `view` at `device` zoom (1 = 100 %), clamped to the zoom range of a document of `size`, with its centre kept. -pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32) -> CanvasView { +pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> CanvasView { let mut next = *view; - next.zoom = CanvasView::points_per_unit(ZoomLadder::clamp(device, size), pixels_per_point); + next.zoom = CanvasView::points_per_unit(scheme.clamp(device, size), pixels_per_point); next } @@ -132,30 +185,30 @@ fn shown_extent(view: &CanvasView, size: Size) -> (f64, f64, f64, f64) { /// each side, never past 100 % (one document pixel per device pixel, so a 150 % display does not open /// documents magnified). `size` is in document units; the view's [`aspect`](CanvasView::aspect) and rotation /// are taken into account. -pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64) { - fit_up_to(view, size, pixels_per_point, 1.0, margin); +pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64, scheme: &ZoomScheme) { + fit_up_to(view, size, pixels_per_point, scheme.hundred, margin, scheme); } /// [`fit`] with the device zoom allowed up to `max_device` (1 = 100 %) instead of 100 %: a small document is /// magnified to fill the canvas, as Photoshop's Fit on Screen does. -pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64) { - fit_rect_up_to(view, Rect::from_origin_size(Point::ORIGIN, size), size, pixels_per_point, max_device, Vec2::new(margin, margin)); +pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64, scheme: &ZoomScheme) { + fit_rect_up_to(view, Rect::from_origin_size(Point::ORIGIN, size), size, pixels_per_point, max_device, Vec2::new(margin, margin), scheme); } /// Fit a part of the document on screen (an artboard, the selected layers' bounds): centre `rect`, in document /// units, and zoom so all of it shows inside `view.rect` less `margin.x` points at the left and right and `margin.y` -/// at the top and bottom, up to the zoom ceiling. +/// at the top and bottom, up to the scheme's greatest zoom. /// The zoom stays inside the range of a document of `size`; an empty `rect` zooms to that ceiling about its centre. -pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2) { - fit_rect_up_to(view, rect, size, pixels_per_point, ZoomLadder::MAX, margin); +pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2, scheme: &ZoomScheme) { + fit_rect_up_to(view, rect, size, pixels_per_point, scheme.max_device(), margin, scheme); } -fn fit_rect_up_to(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, max_device: f64, margin: Vec2) { +fn fit_rect_up_to(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, max_device: f64, margin: Vec2, scheme: &ZoomScheme) { let rect = rect.abs(); let (shown_w, shown_h, sin, cos) = shown_extent(view, rect.size()); let (bw, bh) = (shown_w * cos + shown_h * sin, shown_w * sin + shown_h * cos); let scale = ((f64::from(view.rect.width()) - 2.0 * margin.x) / bw).min((f64::from(view.rect.height()) - 2.0 * margin.y) / bh); - let device = ZoomLadder::clamp((scale * f64::from(pixels_per_point)).min(max_device), size); + let device = scheme.clamp((scale * f64::from(pixels_per_point)).min(max_device), size); view.zoom = CanvasView::points_per_unit(device, pixels_per_point); view.center = rect.center(); } @@ -170,12 +223,12 @@ pub fn wrapped_canvas(view: &CanvasView, document: Size, canvas: ScreenRect) -> /// Fill Screen: centre the document and zoom until it covers `view.rect`; one axis may extend /// past the canvas. -pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32) { +pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) { let (shown_w, shown_h, sin, cos) = shown_extent(view, size); let (rw, rh) = (f64::from(view.rect.width()), f64::from(view.rect.height())); // The canvas rectangle's extent along the document's axes, which the document must cover. let (ex, ey) = (rw * cos + rh * sin, rw * sin + rh * cos); - let device = ZoomLadder::clamp((ex / shown_w).max(ey / shown_h) * f64::from(pixels_per_point), size); + let device = scheme.clamp((ex / shown_w).max(ey / shown_h) * f64::from(pixels_per_point), size); view.zoom = CanvasView::points_per_unit(device, pixels_per_point); view.center = Point::new(size.width / 2.0, size.height / 2.0); } @@ -213,12 +266,12 @@ pub fn wheel_anchor(view: &CanvasView, screen: Pos2, size: Size) -> Pos2 { if nearest == d { screen } else { view.to_screen(nearest) } } -/// View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next ladder rung -/// ([`ZoomLadder::step`]), the view's centre unchanged. Returns whether the zoom changed (it does +/// View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next rung of the scheme +/// ([`ZoomScheme::step`]), the view's centre unchanged. Returns whether the zoom changed (it does /// not at a limit). -pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32) -> bool { +pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool { let current = device(view, pixels_per_point); - let next = ZoomLadder::step(current, dir, size); + let next = scheme.step(current, dir, size); let changed = next.is_finite() && (next / current - 1.0).abs() > 1e-9; if changed { view.zoom = CanvasView::points_per_unit(next, pixels_per_point); diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index fc2391ee2e..cb45db81a6 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -62,6 +62,11 @@ pub trait Codec { true } + /// Whether a paste the codec reads whole replaces the field's text, wherever the caret is. + fn whole_paste(&self, _pasted: &str) -> bool { + false + } + /// The text the field shows after committing `v`, which was parsed from `text`. fn normalise(&self, _text: &str, v: &Self::Value) -> String { self.format(v) @@ -103,6 +108,10 @@ impl Codec for &C { (**self).filter(c) } + fn whole_paste(&self, pasted: &str) -> bool { + (**self).whole_paste(pasted) + } + fn normalise(&self, text: &str, v: &Self::Value) -> String { (**self).normalise(text, v) } @@ -158,6 +167,9 @@ pub struct NumberCodec { custom: Option, /// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]). zoom: bool, + /// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]). + share: bool, + signed_zoom: bool, } impl fmt::Debug for NumberCodec { @@ -167,6 +179,8 @@ impl fmt::Debug for NumberCodec { .field("decimals", &self.decimals) .field("fixed", &self.fixed) .field("zoom", &self.zoom) + .field("share", &self.share) + .field("signed_zoom", &self.signed_zoom) .field("custom", &self.custom.is_some()) .finish() } @@ -179,7 +193,13 @@ impl PartialEq for NumberCodec { (Some(a), Some(b)) => Arc::ptr_eq(a, b), _ => false, }; - self.reader == other.reader && self.decimals == other.decimals && self.fixed == other.fixed && self.zoom == other.zoom && same_custom + self.reader == other.reader + && self.decimals == other.decimals + && self.fixed == other.fixed + && self.zoom == other.zoom + && self.share == other.share + && self.signed_zoom == other.signed_zoom + && same_custom } } @@ -213,7 +233,7 @@ const NUMBER_SAMPLE: &str = "0000.00"; impl NumberCodec { /// A codec reading with `reader` and writing at most `decimals` decimal places. pub fn new(reader: Reader, decimals: usize) -> Self { - NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false } + NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, share: false, signed_zoom: false } } /// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown @@ -230,8 +250,14 @@ impl NumberCodec { self } + /// Allow a leading minus in zoom input so the field can reject negative values instead of discarding the sign. + pub fn signed_zoom(mut self) -> Self { + self.signed_zoom = true; + self + } + /// The zoom reading of trimmed, non-empty `text`: the text before a second decimal separator, then `a/b` as a - /// percentage or a plain number. The filter keeps `+`, `-` and `*` out, so the reader's expressions never run. + /// percentage or a plain number. The filter keeps `+` and `*` out, so the reader's expressions never run. fn read_zoom(&self, text: &str) -> Result<(f64, ParseNote), NotAValue> { let separator = self.reader.decimal_separator(); let second = text.char_indices().filter(|&(_, c)| c == separator).nth(1).map(|(at, _)| at); @@ -239,6 +265,9 @@ impl NumberCodec { Some(at) => (&text[..at], true), None => (text, false), }; + if kept.strip_prefix('-').unwrap_or(kept).contains('-') { + return Err(NotAValue); + } let number = match kept.split_once('/') { Some((part, whole)) => { let part = self.reader.read(part, None)?; @@ -253,6 +282,14 @@ impl NumberCodec { Ok((number, ParseNote { cut, ..ParseNote::default() })) } + /// The same codec reading a lone percentage (`50%`, [`Reader::share`]) as that share of the value the edit + /// started from, as a size field does: every pass of the edit reads the same value. With no start value it is no + /// value, so it never applies as it is typed; it applies on commit. + pub fn share_of_start(mut self) -> Self { + self.share = true; + self + } + /// The same codec writing at most `decimals` decimal places. pub fn at_most(mut self, decimals: usize) -> Self { self.decimals = self.decimals.min(decimals); @@ -333,6 +370,11 @@ impl Codec for NumberCodec { if self.zoom { return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note)); } + if self.share + && let Some(share) = self.reader.share(trimmed) + { + return start.map(|start| (Some(start * share), ParseNote::default())).ok_or(NotAValue); + } match self.reader.read_tagged(text, *start) { Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })), Err(rejected) => { @@ -341,9 +383,9 @@ impl Codec for NumberCodec { } } - /// Zoom typing takes ASCII digits, `/` and the decimal separator; every other number field takes every character. + /// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character. fn filter(&self, c: char) -> bool { - !self.zoom || c.is_ascii_digit() || c == '/' || c == self.reader.decimal_separator() + !self.zoom || c.is_ascii_digit() || (self.signed_zoom && c == '-') || c == '/' || c == self.reader.decimal_separator() } fn sample(&self, _current: &Option) -> Cow<'_, str> { diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index af14c260b4..3b6a67f783 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -351,6 +351,8 @@ pub enum CursorPriority { DropTarget, /// A drag in progress. Drag, + /// Hides the pointer over everything, links included, while a presentation runs. + Hidden, } /// The winning request: the highest priority, the later request on a tie. diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 6f18bf113f..14a752fe9e 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -162,6 +162,44 @@ impl

Workspace

{ } impl Workspace

{ + /// Renames a panel in `layout`, `hidden` and `floated` (keys and anchors), keeping its place; all or nothing. + /// An edit: it moves the revision and keeps the generation. `MissingPanel` when `from` is in none of them, `DuplicatePanel` when `to` is + /// already there. + pub fn rename(&mut self, from: &P, to: P) -> Result<(), DockError> { + if !self.holds(from) { + return Err(DockError::MissingPanel); + } + if self.holds(&to) { + return Err(DockError::DuplicatePanel); + } + let swap = |panel: &mut P| { + if *panel == *from { + *panel = to.clone(); + } + }; + let mut proposed = self.clone(); + if let Some(root) = proposed.layout.root.as_mut() { + rename_in_tree(root, &swap); + } + for window in &mut proposed.layout.floating { + rename_in_column(&mut window.column, &swap); + } + for (panel, location) in proposed.hidden.iter_mut().chain(&mut proposed.floated) { + swap(panel); + rename_in_location(location, &swap); + } + proposed.validate()?; + let Workspace { layout, hidden, floated, .. } = proposed; + (self.layout, self.hidden, self.floated) = (layout, hidden, floated); + self.touch(); + Ok(()) + } + + /// Whether `panel` is in the layout or is the key of a hidden or floated record. + fn holds(&self, panel: &P) -> bool { + self.layout.contains(panel) || self.hidden.iter().chain(&self.floated).any(|(held, _)| held == panel) + } + /// Check the version, the layout, that every hidden panel is hidden once and absent /// from the layout and its record is bounded, and that the floated records are bounded and one per panel. pub fn validate(&self) -> Result<(), DockError> { @@ -585,6 +623,37 @@ fn dock_columns_mut

(root: &mut Node

) -> Vec<&mut Column

> { out } +/// Applies `swap` to every panel of `root`, walking the tree with a stack: a loaded tree can be deeper than the call +/// stack. +fn rename_in_tree

(root: &mut Node

, swap: &impl Fn(&mut P)) { + let mut visit = vec![root]; + while let Some(node) = visit.pop() { + match node { + Node::Split { first, second, .. } => { + visit.push(second); + visit.push(first); + } + Node::Tabs { panels, .. } => panels.iter_mut().for_each(swap), + Node::Stack { entries } => entries.iter_mut().for_each(|entry| swap(&mut entry.panel)), + Node::Dock { columns, .. } => columns.iter_mut().for_each(|column| rename_in_column(column, swap)), + } + } +} + +/// Applies `swap` to every panel of the groups of `column`. +fn rename_in_column

(column: &mut Column

, swap: &impl Fn(&mut P)) { + column.groups.iter_mut().for_each(|group| group.panels.iter_mut().for_each(swap)); +} + +/// Applies `swap` to the panels a location names: its anchor, its siblings and the tab it goes before. +fn rename_in_location

(location: &mut Location

, swap: &impl Fn(&mut P)) { + location.anchor.iter_mut().for_each(swap); + location.sibling.iter_mut().for_each(swap); + if let DockPlacement::Tab { before: Some(panel) } = &mut location.placement { + swap(panel); + } +} + /// Whether `panel` is in a floating window of `layout`. fn floats(layout: &Layout

, panel: &P) -> bool { matches!(layout.place(panel), Some(PanelPlace::Floating { .. })) diff --git a/crates/behavior/src/edit_history.rs b/crates/behavior/src/edit_history.rs index 0dd299939a..0b05d3c00c 100644 --- a/crates/behavior/src/edit_history.rs +++ b/crates/behavior/src/edit_history.rs @@ -1,11 +1,14 @@ //! `EditHistory`: the undo and redo of a dialog, a tool session or the keymap editor, fed by edit events. -use crate::value::{EditEvent, GestureId, Value}; +use crate::value::{EditEvent, GestureId, Mixed, Value}; use std::sync::Arc; /// Most steps a history keeps. const LIMIT: usize = 100; +/// How a value weighs under a history's budget. +type Weigh = fn(&T) -> usize; + /// Which way [`EditHistory::step`] goes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -21,6 +24,8 @@ pub enum Step { struct Entry { value: T, name: Arc, + /// The weight of `value` under the history's budget ([`EditHistory::with_budget`]). + weight: usize, } /// The gesture under way: its name, taken from its `Begin`. @@ -38,23 +43,50 @@ pub struct EditHistory { redo: Vec>, /// The value as of the latest step. settled: T, + /// The weight of `settled`; 0 without a budget. + settled_weight: usize, open: Option, + /// The most summed weight the undo steps keep, and how a value weighs. + budget: Option<(usize, Weigh)>, } impl EditHistory { /// A history that starts at `now`. pub fn new(now: &T) -> Self { - EditHistory { undo: Vec::new(), redo: Vec::new(), settled: now.clone(), open: None } + EditHistory { undo: Vec::new(), redo: Vec::new(), settled: now.clone(), settled_weight: 0, open: None, budget: None } } - /// Takes in one event. Events of a gesture other than the open one are ignored. + /// The undo steps' summed weight stays at or under `max`: after each push the oldest go first, the newest always + /// stays; each weight is measured once at push. Without a budget nothing changes. + #[must_use] + pub fn with_budget(mut self, max: usize, weight: fn(&T) -> usize) -> Self { + self.settled_weight = weight(&self.settled); + self.budget = Some((max, weight)); + self.trim(); + self + } + + /// Drops the oldest undo steps while their summed weight passes the budget; the newest stays. + fn trim(&mut self) { + let Some((max, _)) = self.budget else { return }; + let mut total = self.undo.iter().fold(0usize, |sum, entry| sum.saturating_add(entry.weight)); + let mut gone = 0; + while total > max && gone + 1 < self.undo.len() { + total = total.saturating_sub(self.undo[gone].weight); + gone += 1; + } + self.undo.drain(..gone); + } + + /// Takes in one event. Events of a gesture other than the open one are ignored. A concrete + /// before value captures changes made outside history since the preceding edit. pub fn record(&mut self, event: &EditEvent) { match event { EditEvent::Begin { id, label, .. } => self.open = Some(Open { id: *id, name: label.clone() }), EditEvent::Update { .. } => {} - EditEvent::Commit { id, after, .. } => { + EditEvent::Commit { id, before, after } => { if let Some(open) = self.open.take_if(|open| open.id == *id) { - self.push(after, open.name); + self.push(before, after, open.name); } } EditEvent::Cancel { id, .. } => { @@ -62,9 +94,9 @@ impl EditHistory { self.open = None; } } - EditEvent::Set { after, label, .. } => { + EditEvent::Set { before, after, label, .. } => { self.open = None; - self.push(after, label.clone()); + self.push(before, after, label.clone()); } } } @@ -74,15 +106,23 @@ impl EditHistory { self.open.is_some() } - fn push(&mut self, after: &T, name: Arc) { - if *after == self.settled { + fn push(&mut self, before: &Mixed, after: &T, name: Arc) { + let weight = match before.same() { + Some(value) => self.budget.map_or(0, |(_, weigh)| weigh(value)), + None => self.settled_weight, + }; + let before = before.same().unwrap_or(&self.settled).clone(); + self.settled = after.clone(); + self.settled_weight = self.budget.map_or(0, |(_, weigh)| weigh(after)); + if *after == before { return; } if self.undo.len() >= LIMIT { self.undo.remove(0); } - self.undo.push(Entry { value: std::mem::replace(&mut self.settled, after.clone()), name }); + self.undo.push(Entry { value: before, name, weight }); self.redo.clear(); + self.trim(); } /// Steps `now` back or forward. False when there is nowhere to go. An open gesture is abandoned. @@ -93,7 +133,8 @@ impl EditHistory { Step::Redo => (&mut self.redo, &mut self.undo), }; let Some(entry) = from.pop() else { return false }; - to.push(Entry { value: std::mem::replace(now, entry.value.clone()), name: entry.name }); + let weight = std::mem::replace(&mut self.settled_weight, entry.weight); + to.push(Entry { value: std::mem::replace(now, entry.value.clone()), name: entry.name, weight }); self.settled = entry.value; true } @@ -104,6 +145,7 @@ impl EditHistory { pub fn take_back(&mut self) -> Option { self.open = None; let entry = self.undo.pop()?; + self.settled_weight = entry.weight; self.settled = entry.value.clone(); Some(entry.value) } @@ -133,6 +175,17 @@ mod tests { EditEvent::set(Mixed::Same(before), after, "Fill".into(), None) } + #[test] + fn undo_restores_selection_changed_between_edits() { + let mut history = EditHistory::new(&(0, 0)); + history.record(&EditEvent::set(Mixed::Same((0, 1)), (1, 0), "Remove".into(), None)); + let mut now = (1, 0); + assert!(history.step(&mut now, Step::Undo)); + assert_eq!(now, (0, 1)); + assert!(history.step(&mut now, Step::Redo)); + assert_eq!(now, (1, 0)); + } + #[test] fn a_take_back_returns_the_earlier_value_keeps_redo_and_settles() { let mut history = EditHistory::new(&0); @@ -151,6 +204,52 @@ mod tests { assert_eq!(now, 0, "the undo takes the step before the one taken back"); } + fn weigh(value: &i32) -> usize { + usize::try_from(*value).unwrap_or(0) + } + + fn undo_weight(history: &EditHistory) -> usize { + history.undo.iter().map(|entry| entry.weight).sum() + } + + #[test] + fn a_weight_budget_drops_the_oldest_steps_and_keeps_the_newest() { + let mut history = EditHistory::new(&0).with_budget(10, weigh); + for (before, after) in [(0, 4), (4, 5), (5, 6)] { + history.record(&set(before, after)); + } + assert_eq!(history.undo.len(), 3, "weights 0, 4 and 5 fit"); + history.record(&set(6, 7)); + assert_eq!(history.undo.len(), 1, "the oldest went until the sum fit, the newest stayed"); + + let mut now = 7; + assert!(history.step(&mut now, Step::Undo)); + assert_eq!(now, 6); + assert!(!history.can_undo()); + assert!(history.step(&mut now, Step::Redo)); + assert_eq!((now, undo_weight(&history)), (7, 6), "the redo gave the step back with its own weight"); + + history.record(&set(7, 9)); + assert_eq!((history.undo.len(), undo_weight(&history)), (1, 7), "6 + 7 passes 10, the oldest went"); + + assert!(history.step(&mut now, Step::Undo)); + history.record(&set(7, 8)); + assert_eq!(history.redo_len(), 0, "a new step after an undo clears redo"); + assert_eq!(undo_weight(&history), 7); + + let mut long = EditHistory::new(&0).with_budget(usize::MAX, |_| 1); + for n in 0..120 { + long.record(&set(n, n + 1)); + } + assert_eq!(long.undo.len(), LIMIT, "the step limit still applies"); + + let mut free = EditHistory::new(&0); + for n in 0..3 { + free.record(&set(n, n + 1)); + } + assert_eq!((free.undo.len(), undo_weight(&free)), (3, 0), "without a budget nothing is trimmed or weighed"); + } + #[test] fn redo_len_counts_the_undone_steps_until_a_new_step() { let mut history = EditHistory::new(&0); diff --git a/crates/behavior/src/editor.rs b/crates/behavior/src/editor.rs index 7e9467f2c7..b15112b51e 100644 --- a/crates/behavior/src/editor.rs +++ b/crates/behavior/src/editor.rs @@ -87,7 +87,12 @@ pub enum EditorInput { /// An edit command from the command queue. Edit(EditCommand), /// Enter. - Newline, + #[non_exhaustive] + Newline { + /// Shift was held: an editor that gives Shift+Enter its own meaning (a line break within the paragraph) tells + /// it from a plain Enter. + shift: bool, + }, /// Tab. Tab, /// Shift+Tab, which reaches only a document canvas's editor part that keeps Tab. @@ -107,6 +112,11 @@ impl EditorInput { EditorInput::Delete { forward, by, shift } } + /// A `Newline`, with Shift held when `shift`. + pub const fn newline(shift: bool) -> Self { + EditorInput::Newline { shift } + } + /// A `DeleteSurrounding` of `before` and `after` characters. pub const fn delete_surrounding(before: usize, after: usize) -> Self { EditorInput::DeleteSurrounding { before, after, unit: SurroundingUnit::Chars } diff --git a/crates/behavior/src/focus.rs b/crates/behavior/src/focus.rs index e215a14fd8..e670e3b61a 100644 --- a/crates/behavior/src/focus.rs +++ b/crates/behavior/src/focus.rs @@ -1,5 +1,5 @@ -//! Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, focus after removal, the Escape order and the -//! focus-on-press kinds. The runtime's focus service feeds them facts and applies the result. +//! Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the focus-on-press kinds. The runtime's +//! focus service feeds them facts and applies the result. use crate::sense::Sense; @@ -86,14 +86,6 @@ pub fn key_owner(blocked: bool, present: &[OwnerClass]) -> KeyOwner { .map_or(KeyOwner::Class(OwnerClass::App), |class| KeyOwner::Class(*class)) } -/// The stop that takes focus when `focused` is no longer registered: the one after it in last pass's order -/// that is still registered, else the one before. `None` leaves the scope's initial stop to decide. -pub fn after_removal<'a, T: PartialEq>(last_order: &'a [T], focused: &T, registered: impl Fn(&T) -> bool) -> Option<&'a T> { - let at = last_order.iter().position(|stop| stop == focused)?; - let after = last_order[at + 1..].iter().find(|stop| registered(stop)); - after.or_else(|| last_order[..at].iter().rev().find(|stop| registered(stop))) -} - /// What the Escape of one pass reaches first. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] diff --git a/crates/behavior/src/frame_step.rs b/crates/behavior/src/frame_step.rs new file mode 100644 index 0000000000..a293d5a1ff --- /dev/null +++ b/crates/behavior/src/frame_step.rs @@ -0,0 +1,10 @@ +//! The step of one pass of motion: a Hand glide, a held Zoom press and an autoscroll integrate over it. + +/// 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. +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 153be1ffa5..7fa0422777 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -148,9 +148,11 @@ 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 one document unit. - pub fn size_ok(&self) -> bool { - self.rect.width() >= MIN_FRAME && self.rect.height() >= MIN_FRAME + /// 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 } /// The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on diff --git a/crates/behavior/src/geometry/mod.rs b/crates/behavior/src/geometry/mod.rs index 434fd68dfd..4e064fbfce 100644 --- a/crates/behavior/src/geometry/mod.rs +++ b/crates/behavior/src/geometry/mod.rs @@ -24,7 +24,7 @@ pub use lock::{ pub use marquee::{Constraint, MarqueeGesture, MarqueeRect, fixed_size_pixels, marquee_pixels, square_pixels}; pub use move_gesture::{ConstrainStyle, MoveGesture, MoveValue, StrokeLock}; pub use outside::outside_pieces; -pub use quad::{BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag}; +pub use quad::{BoxAllow, BoxDrag, BoxHandles, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag}; pub use selection_op::SelectionOperation; pub use snap::{ SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapSuspend, SnapTarget, SnapTargets, across_axis, coordinate_across, diff --git a/crates/behavior/src/geometry/quad.rs b/crates/behavior/src/geometry/quad.rs index 6b44078e0f..c61e76723d 100644 --- a/crates/behavior/src/geometry/quad.rs +++ b/crates/behavior/src/geometry/quad.rs @@ -97,6 +97,8 @@ pub enum ScaleRule { /// PhotoCraft's Use Legacy Free Transform, DesignCraft and VectorCraft: corners stretch freely /// and ⇧ keeps the proportions; edges stretch their one axis. Free, + /// Corners keep their proportions using the larger relative axis change; ⇧ frees them. + LargerAxis, /// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal, /// keeping the proportions; an edge stretches its one axis. Shape, @@ -203,6 +205,25 @@ pub struct BoxRules { /// minimum keeps a scale drag from flipping the box, and a side already shorter than it at /// the press keeps its length as its floor, so a click changes nothing. pub min_side: f64, + /// Which handles the box shows and takes keys and drags for. + pub handles: BoxHandles, + /// How far either side of a side's line a press grabs that side, in screen points, along the whole side and as + /// far past its ends: a paragraph frame whose edges rewrap it. Inside the box the band reaches at most a quarter of + /// the way across, so a narrow box keeps its middle. 0, the default, leaves each side its band outside the box. + pub edge_band: f32, +} + +/// Which handles of a box are shown. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum BoxHandles { + /// The four corners and the four sides. + #[default] + All, + /// The four corners. + Corners, + /// The right and left sides. + Sides, } impl Default for BoxRules { @@ -214,6 +235,8 @@ impl Default for BoxRules { allow: BoxAllow::default(), rotate_step: 15.0, min_side: 0.0, + handles: BoxHandles::default(), + edge_band: 0.0, } } } @@ -249,6 +272,28 @@ impl BoxRules { self } + /// The rules with `handles` as the handles the box shows. + pub fn with_handles(mut self, handles: BoxHandles) -> BoxRules { + self.handles = handles; + self + } + + /// The rules with each side grabbed within `points` of its line ([`edge_band`](Self::edge_band)). + pub fn with_edge_band(mut self, points: f32) -> BoxRules { + self.edge_band = points; + self + } + + /// Whether the box shows `part`: `Corners` shows the four corners and no side, `Sides` the right and left sides + /// and no corner. The inside, the outside and the reference point always show. + pub fn shows(&self, part: BoxPart) -> bool { + match (self.handles, part) { + (BoxHandles::Corners, BoxPart::Edge(_)) | (BoxHandles::Sides, BoxPart::Corner(_)) => false, + (BoxHandles::Sides, BoxPart::Edge(k)) => k % 2 == 1, + _ => true, + } + } + /// The mode drags follow: a mode the content refuses scales as Free Transform does. pub fn effective_mode(&self) -> TransformMode { let refused = match self.mode { @@ -262,14 +307,15 @@ impl BoxRules { /// Whether a drag of `part` changes the box: in Distort only the corners, the inside and the /// reference point; in Skew everything but the outside; the outside only where rotating is - /// allowed. A click outside a refused zone still applies the box (the overlay's rule). + /// allowed; and never a handle the box does not [show](Self::shows). A click outside a refused + /// zone still applies the box (the overlay's rule). pub fn allows(&self, part: BoxPart) -> bool { let by_mode = match self.effective_mode() { TransformMode::Distort => !matches!(part, BoxPart::Outside | BoxPart::Edge(_)), TransformMode::Skew => part != BoxPart::Outside, _ => true, }; - by_mode && (self.allow.rotate || part != BoxPart::Outside) + by_mode && (self.allow.rotate || part != BoxPart::Outside) && self.shows(part) } /// The modifiers a drag of `part` acts on, from the keys held: ⌘ is dropped on a corner or @@ -504,16 +550,22 @@ fn apply_drag(g: &Gesture, p: Point, mods: Mods, rules: &BoxRules) -> BoxState { } BoxState { quad, pivot: carry_pivot(q0, quad, c) } } - BoxPart::Corner(_) | BoxPart::Edge(_) => scale_drag(g, p, mods, rules.min_side).unwrap_or(BoxState { quad: q0, pivot: c }), + BoxPart::Corner(_) | BoxPart::Edge(_) => { + scale_drag(g, p, mods, rules.min_side, rules.scale == ScaleRule::LargerAxis).unwrap_or(BoxState { quad: q0, pivot: c }) + } } } /// A plain corner or edge drag: scaling in the box's own frame (the unit square through the /// homography), so rotated and skewed boxes scale along their axes. A proportional corner follows -/// the pointer's projection on the line from the anchor to the corner, so a distorted box scales -/// along its own diagonal; past the anchor the factor turns negative and the box flips. Each -/// scaled side keeps at least `min_side` ([`scale_floor`]). `None` for a collapsed box. -fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64) -> Option { +/// the pointer's projection on the diagonal, or the larger relative axis change when selected. Past the anchor +/// the factor turns negative and the box flips. Each scaled side keeps at least `min_side` +/// ([`scale_floor`]). `None` for a collapsed box. +fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64, larger_axis: bool) -> Option { + let p = match g.part { + BoxPart::Corner(i) => g.quad0[usize::from(i) % 4] + (p - g.start), + _ => p, + }; let h = Homography::unit_to_quad(g.quad0)?; let inv = h.inverse()?; let Point { x: u, y: v } = inv.apply(p); @@ -556,16 +608,14 @@ fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64) -> Option 1e-12 { + let k = if larger_axis { + if (ku - 1.0).abs() > (kv - 1.0).abs() { ku } else { kv } + } else if len2 > 1e-12 { let q = inv.apply(a + d * ((p - a).dot(d) / len2)); if (hu - au).abs() >= (hv - av).abs() { (q.x - au) / (hu - au) } else { (q.y - av) / (hv - av) } } else { diff --git a/crates/behavior/src/grid.rs b/crates/behavior/src/grid.rs index b9c1e5bfd2..bd782a0e9c 100644 --- a/crates/behavior/src/grid.rs +++ b/crates/behavior/src/grid.rs @@ -119,10 +119,11 @@ impl GridCursor { cursor } - /// A cursor for the sweep that asks each column for its least: every column but a `Fixed` one is placed as a - /// `Content` column whose cells measure in no bound along x, so each column measures its widest cell. + /// A cursor for the sweep that asks each column for its least: the cells of every `Content` and `Fill` column + /// measure in no bound along x, so each column measures its widest cell. A `Fill` column stays one, so a child + /// that fills its width measures its own width there, where a `Content` column would hold it and take none. pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self { - let mut cursor = Self::new(flow, &as_content(columns), gap, &GridMeasure::default()); + let mut cursor = Self::new(flow, columns, gap, &GridMeasure::default()); cursor.unbounded = true; cursor } @@ -185,7 +186,7 @@ impl GridCursor { let count = self.columns.len().max(1); let (column, _, _, top) = self.next_place(); let width = match self.columns.get(column) { - Some(ColumnWidth::Content) if self.unbounded => f32::INFINITY, + Some(ColumnWidth::Content | ColumnWidth::Fill { .. }) if self.unbounded => f32::INFINITY, Some(ColumnWidth::Content) => { // Every other column keeps at least its least: a column that fills keeps only that, and so does a // content column when each column measures alone. diff --git a/crates/behavior/src/hit.rs b/crates/behavior/src/hit.rs index 8fd12da309..d2cd1f848b 100644 --- a/crates/behavior/src/hit.rs +++ b/crates/behavior/src/hit.rs @@ -51,6 +51,15 @@ pub enum HitShape { /// The corners of the polygon cut out of `within`. polygon: Vec, }, + /// A shape with discs cut out of it: a widget part over a bounding-box handle leaves the handle's disc to the + /// handle. + #[non_exhaustive] + Excluding { + /// The shape the discs are cut out of. + shape: Box, + /// The discs cut out, each a centre and a radius. + holes: Vec<(Pos2, f32)>, + }, } impl HitShape { @@ -81,10 +90,16 @@ impl HitShape { HitShape::OutsidePolygon { within, polygon } } + /// `shape` without the discs `holes` (a centre and a radius each). + pub fn excluding(shape: HitShape, holes: Vec<(Pos2, f32)>) -> HitShape { + HitShape::Excluding { shape: Box::new(shape), holes } + } + /// The smallest rectangle around the shape. pub fn bounds(&self) -> Rect { match self { HitShape::Rect(rect) | HitShape::OutsidePolygon { within: rect, .. } => *rect, + HitShape::Excluding { shape, .. } => shape.bounds(), HitShape::Circle { center, radius } => Rect::from_center_size(*center, Vec2::splat(radius * 2.0)), HitShape::Segment { a, b } => Rect::from_two_pos(*a, *b), HitShape::Polyline { points, .. } | HitShape::Polygon(points) => { @@ -104,6 +119,10 @@ impl HitShape { HitShape::Polyline { points: line, closed, reach } => HitShape::Polyline { points: points(line), closed: *closed, reach: *reach }, HitShape::Polygon(polygon) => HitShape::Polygon(points(polygon)), HitShape::OutsidePolygon { within, polygon } => HitShape::OutsidePolygon { within: within.translate(by), polygon: points(polygon) }, + HitShape::Excluding { shape, holes } => HitShape::Excluding { + shape: Box::new(shape.translated(by)), + holes: holes.iter().map(|(center, radius)| (*center + by, *radius)).collect(), + }, } } @@ -130,6 +149,18 @@ impl HitShape { (HitShape::OutsidePolygon { within: area, polygon }, HitShape::OutsidePolygon { within: to_area, polygon: to_polygon }) => { HitShape::OutsidePolygon { within: rect(*area, *to_area), polygon: points(polygon, to_polygon) } } + (HitShape::Excluding { shape, holes }, HitShape::Excluding { shape: to_shape, holes: to_holes }) => { + let holes = if holes.len() == to_holes.len() { + holes + .iter() + .zip(to_holes) + .map(|((center, radius), (to_center, to_radius))| (pos(*center, *to_center), near(*radius, *to_radius))) + .collect() + } else { + holes.clone() + }; + HitShape::Excluding { shape: Box::new(shape.snapped(to_shape, within)), holes } + } _ => self.clone(), } } @@ -152,6 +183,7 @@ impl HitShape { || closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= reach) } HitShape::OutsidePolygon { within, polygon } => within.contains(point) && !inside_polygon(point, polygon), + HitShape::Excluding { shape, holes } => shape.hit_across(point, across) && !in_hole(holes, point), HitShape::Polygon(points) => { let bounds = self.bounds(); let small = bounds.width() < across || bounds.height() < across; @@ -174,10 +206,16 @@ impl HitShape { } HitShape::Polygon(points) => inside_polygon(point, points), HitShape::OutsidePolygon { within, polygon } => within.contains(point) && !inside_polygon(point, polygon), + HitShape::Excluding { shape, holes } => shape.hit(point) && !in_hole(holes, point), } } } +/// Whether `point` lies inside one of the discs `holes`. +fn in_hole(holes: &[(Pos2, f32)], point: Pos2) -> bool { + holes.iter().any(|(center, radius)| center.distance(point) <= *radius) +} + impl From for HitShape { fn from(rect: Rect) -> Self { HitShape::Rect(rect) @@ -271,6 +309,11 @@ pub struct Shape { pub local: bool, /// The least size across the hit area has, in points. pub min_across: f32, + /// The named stacking order: stacked parts of one priority rank by it before the nearest centre, the higher order + /// winning. + pub stacking: u32, + /// Whether a passed drag targets the arena root instead of the next shape. + pub drag_to_root: bool, } impl Shape { @@ -292,7 +335,7 @@ impl Shape { impl Shape { /// A shape of `owner` at stack `position`. pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option, priority: HitPriority, position: u32) -> Self { - Shape { shape, sense, owner, part, priority, position, local: false, min_across: 0.0 } + Shape { shape, sense, owner, part, priority, position, local: false, min_across: 0.0, stacking: 0, drag_to_root: false } } /// The hit area is at least `across` points wide and high. @@ -301,6 +344,12 @@ impl Shape { self } + /// The shape's stacking order among shapes of its priority: the higher order wins before the nearest centre. + pub const fn stacking(mut self, order: u32) -> Self { + self.stacking = order; + self + } + /// The shape lies in the body layer's space. pub const fn local(mut self, local: bool) -> Self { self.local = local; @@ -338,10 +387,12 @@ pub struct Winner { pub sense: Sense, /// Its shape lies in the body layer's space. pub local: bool, + /// A passed drag targets the arena root. + pub drag_to_root: bool, } -/// The winner among `shapes` at `point`: stack position first, then level, sub-level, the nearest centre, the last -/// registered. A press considers only shapes that sense a click or a drag. +/// The winner among `shapes` at `point`: stack position first, then level, sub-level, stacking order, the nearest +/// centre, the last registered. A press considers only shapes that sense a click or a drag. pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option> { resolve_mapped(shapes, point, what, |_| point) } @@ -356,12 +407,19 @@ pub fn resolve_mapped(shapes: &[Shape], point: Pos2, what: ResolveFo .filter(|(_, shape)| what == ResolveFor::Hover || shape.sense.takes_press()) .filter(|(_, shape)| shape.hits(at(shape))) .max_by(|(ia, a), (ib, b)| { - (a.position, a.priority.level, a.priority.sub) - .cmp(&(b.position, b.priority.level, b.priority.sub)) + (a.position, a.priority.level, a.priority.sub, a.stacking) + .cmp(&(b.position, b.priority.level, b.priority.sub, b.stacking)) .then_with(|| distance(b).partial_cmp(&distance(a)).unwrap_or(Ordering::Equal)) .then(ia.cmp(ib)) }) - .map(|(index, shape)| Winner { index, owner: shape.owner, part: shape.part, sense: shape.sense, local: shape.local }) + .map(|(index, shape)| Winner { + index, + owner: shape.owner, + part: shape.part, + sense: shape.sense, + local: shape.local, + drag_to_root: shape.drag_to_root, + }) } #[cfg(test)] @@ -398,6 +456,17 @@ mod tests { assert_eq!(owner(&tie), Some(2)); } + #[test] + fn stacked_parts_of_one_priority_rank_by_their_order_before_the_nearest_centre() { + let at = pos2(50.0, 50.0); + let owner = |shapes: &[Shape]| resolve(shapes, at, ResolveFor::Press).map(|w| w.owner); + let near = || shape(rect(40.0, 40.0, 20.0, 20.0), Sense::CLICK, 1, 0, HitLevel::Body, 0); + let far = || shape(rect(0.0, 0.0, 200.0, 200.0), Sense::CLICK, 2, 0, HitLevel::Body, 0); + assert_eq!(owner(&[far(), near()]), Some(1), "unstacked, the nearer centre wins"); + assert_eq!(owner(&[far().stacking(1), near()]), Some(2), "the higher stacking order wins though the press is nearer the other's centre"); + assert_eq!(owner(&[near().stacking(1), far().stacking(1)]), Some(1), "one order: the nearest centre decides"); + } + #[test] fn a_polyline_hits_within_its_own_reach_and_a_bad_reach_is_a_lines() { let points = vec![pos2(0.0, 0.0), pos2(100.0, 0.0)]; diff --git a/crates/behavior/src/hold_repeat.rs b/crates/behavior/src/hold_repeat.rs new file mode 100644 index 0000000000..40fba66260 --- /dev/null +++ b/crates/behavior/src/hold_repeat.rs @@ -0,0 +1,39 @@ +//! Steps due while a press is held, as a spinner button repeats. + +/// A press held on a spinner button, known by the pass time it began. It keeps nothing between passes: a pass builds it +/// from the press's own start time and asks how many repeats the pass owes, so a rerun pass (no time elapsed) owes none. +/// A different concept from `HoldZoom`, which zooms continuously at a rate. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HoldRepeat { + start: f64, +} + +impl HoldRepeat { + /// Seconds a press is held before the steps repeat. + pub const DELAY: f64 = 0.45; + + /// Seconds between repeated steps. + pub const INTERVAL: f64 = 0.06; + + /// A press that began at pass time `start`, in seconds. + pub const fn new(start: f64) -> Self { + HoldRepeat { start } + } + + /// How many repeat instants (`start + DELAY + k * INTERVAL`, `k >= 0`) lie at or before `at`. + fn reached(&self, at: f64) -> u32 { + let since = at - self.start - Self::DELAY; + if since < 0.0 { 0 } else { (since / Self::INTERVAL).floor() as u32 + 1 } + } + + /// The repeats due in the pass at `now` that follows another `elapsed` seconds after: the repeat instants in + /// `(now - elapsed, now]`. The step of the press itself is not counted. + pub fn due(&self, now: f64, elapsed: f64) -> u32 { + self.reached(now).saturating_sub(self.reached(now - elapsed)) + } + + /// The first repeat instant after `now`, the time to ask the next pass for while the press is held. + pub fn next_repeat(&self, now: f64) -> f64 { + self.start + Self::DELAY + f64::from(self.reached(now)) * Self::INTERVAL + } +} diff --git a/crates/behavior/src/item_layout.rs b/crates/behavior/src/item_layout.rs index 9c26a1c0e7..49bd039554 100644 --- a/crates/behavior/src/item_layout.rs +++ b/crates/behavior/src/item_layout.rs @@ -30,6 +30,12 @@ pub trait ItemLayout { /// The item under `point`. fn hit(&self, point: Pos2, offset: ScrollPos) -> Option; + /// The item whose drop area contains `point`. Layouts with visible gaps can include those in a drop area while + /// leaving them out of ordinary pointer hits. + fn drop_hit(&self, point: Pos2, offset: ScrollPos) -> Option { + self.hit(point, offset) + } + /// How arrow keys move through the items. fn nav(&self) -> NavShape; @@ -105,7 +111,8 @@ pub trait ItemLayout { /// Whether the items are as wide as they measure themselves. A layout that asks for widths places the items /// from their measured ideal and minimum widths (`set_width`), so every item must be built and measured: its - /// `visible` lists all items, and the collection does not virtualise it. + /// `visible` lists all items, and the collection does not virtualise it. Its items sit side by side, so where the + /// collection's width comes from its rows (a room that does not bound it) it is their ideal widths' sum. fn auto_widths(&self) -> bool { false } @@ -116,6 +123,10 @@ pub trait ItemLayout { /// The viewport and scroll offset the grid view describes. Layouts without a grid ignore it. fn set_view(&mut self, _viewport: Vec2, _offset: ScrollPos) {} + + /// Item `at` is as wide as it measured, `width` from the start edge, in a layout that gives every item one width; + /// `None` gives it that width again. Its rect and its hit test take the width. Layouts of other widths ignore it. + fn set_fit(&mut self, _at: usize, _width: Option) {} } /// Lines (rows or columns) with a default size, the lines whose size differs and their prefix sums, so the start @@ -342,12 +353,14 @@ pub struct SpanLayout { /// Whether the rows form a tree: arrows expand, collapse and step to the parent. pub tree: bool, rows: Option, + /// The rows as wide as they measured (`set_fit`), by position. + fits: BTreeMap, } impl SpanLayout { /// One row of `row_h` per entry of `source`, `width` wide, with no columns. pub fn new(source: &dyn DisplayOrder, width: f32, row_h: f32) -> Self { - Self { row_h, count: source.len(), width, columns: Vec::new(), tree: false, rows: None } + Self { row_h, count: source.len(), width, columns: Vec::new(), tree: false, rows: None, fits: BTreeMap::new() } } /// Rows as tall as `source` says: `Height` and `Rect` are the app's, `Aspect` follows the width, and `Auto` @@ -364,7 +377,12 @@ impl SpanLayout { row_h, ); let auto = hints.iter().map(|hint| matches!(hint, SizeHint::Auto)).collect(); - Self { row_h, count: hints.len(), width, columns: Vec::new(), tree: false, rows: Some(Sized { lines, auto }) } + Self { row_h, count: hints.len(), width, columns: Vec::new(), tree: false, rows: Some(Sized { lines, auto }), fits: BTreeMap::new() } + } + + /// The width of row `at`: the rows', or less where it is as wide as it measured. + fn width_of(&self, at: usize) -> f32 { + self.fits.get(&at).map_or(self.width, |fit| fit.min(self.width)) } fn top(&self, at: usize) -> f64 { @@ -416,16 +434,20 @@ impl ItemLayout for SpanLayout { fn rect(&self, at: usize, offset: ScrollPos) -> Rect { let top = (self.top(at) - offset.y) as f32; - Rect::from_min_size(Pos2::new(-(offset.x as f32), top), Vec2::new(self.width, self.height(at))) + Rect::from_min_size(Pos2::new(-(offset.x as f32), top), Vec2::new(self.width_of(at), self.height(at))) } fn hit(&self, point: Pos2, offset: ScrollPos) -> Option { let y = f64::from(point.y) + offset.y; - if let Some(rows) = &self.rows { - return (0.0..rows.lines.total()).contains(&y).then(|| rows.lines.at(y) as usize).filter(|&at| at < self.count); - } - let at = (y / f64::from(self.row_h)).floor(); - (at >= 0.0 && (at as usize) < self.count).then_some(at as usize) + let at = match &self.rows { + Some(rows) => (0.0..rows.lines.total()).contains(&y).then(|| rows.lines.at(y) as usize).filter(|&at| at < self.count), + None => { + let at = (y / f64::from(self.row_h)).floor(); + (at >= 0.0 && (at as usize) < self.count).then_some(at as usize) + } + }; + // A row as wide as it measured takes no point past its end. + at.filter(|&at| !self.fits.contains_key(&at) || f64::from(point.x) + offset.x < f64::from(self.width_of(at))) } fn column_count(&self) -> usize { @@ -460,6 +482,13 @@ impl ItemLayout for SpanLayout { } } + fn set_fit(&mut self, at: usize, width: Option) { + match width { + Some(width) => self.fits.insert(at, width), + None => self.fits.remove(&at), + }; + } + fn nav(&self) -> NavShape { if self.tree { NavShape::Tree } else { NavShape::Flat } } @@ -880,4 +909,19 @@ mod tests { assert!(!layout.shown(7) && layout.shown(6)); assert_eq!(layout.hit(Pos2::new(1.0, 5.0), ScrollPos { x: 0.0, y: 180.0 }), Some(8)); } + + /// A row as wide as it measured is that wide from the start edge and takes no point past its end; the rows around + /// it keep the layout's width, and `None` gives it that width again. + #[test] + fn a_fitted_span_row_is_as_wide_as_it_measured_and_hit_only_inside() { + let mut layout = SpanLayout::new(&crate::item_source::keyed(&[0_u8, 1, 2], |key| *key), 300.0, 20.0); + layout.set_fit(1, Some(60.0)); + let (row, other) = (layout.rect(1, ScrollPos::default()), layout.rect(2, ScrollPos::default())); + assert!(row.width() < other.width() && row.left() == other.left(), "the row is narrower from the start edge: {row:?} {other:?}"); + assert_eq!(layout.hit(Pos2::new(row.center().x, row.center().y), ScrollPos::default()), Some(1), "inside the row hits it"); + assert_eq!(layout.hit(Pos2::new(row.right() + 10.0, row.center().y), ScrollPos::default()), None, "past its end hits nothing"); + assert_eq!(layout.hit(Pos2::new(row.right() + 10.0, other.center().y), ScrollPos::default()), Some(2), "the next row keeps its width"); + layout.set_fit(1, None); + assert_eq!(layout.rect(1, ScrollPos::default()).width(), other.width(), "None gives the row the layout's width again"); + } } diff --git a/crates/behavior/src/item_source.rs b/crates/behavior/src/item_source.rs index 871e43d4c5..edac87c282 100644 --- a/crates/behavior/src/item_source.rs +++ b/crates/behavior/src/item_source.rs @@ -59,13 +59,18 @@ pub trait DisplayOrder { } /// Whether section `at` is a stop of navigation: it holds the lead, takes Enter, the context-menu key and a - /// press, and opens or closes with Forward and Back when it has children. A move stops on it, and it is never - /// selected, extended over, toggled, marqueed, dragged, renamed or reached by type-ahead. Only meaningful for a - /// section. + /// press, and opens or closes with Forward and Back when it has children. A move stops on it. By default it is + /// not selected or extended over; see `selectable_section`. It is not toggled, marqueed, dragged, renamed or + /// reached by type-ahead. Only meaningful for a section. fn section_stop(&self, _at: usize) -> bool { false } + /// Whether a section stop also represents an item that keyboard selection can pick or extend over. + fn selectable_section(&self, _at: usize) -> bool { + false + } + /// How many section stops (`section_stop`) come before entry `at`. They are not members of the set of items, so /// the positions an item reports to assistive technology do not count them. fn section_stops_before(&self, _at: usize) -> usize { diff --git a/crates/behavior/src/keys.rs b/crates/behavior/src/keys.rs index a24e52bf5e..c7fbcc40ff 100644 --- a/crates/behavior/src/keys.rs +++ b/crates/behavior/src/keys.rs @@ -7,9 +7,20 @@ use crate::intent::{Granularity, Intent, MoveMods, NavMove}; use craft_host::target::Os; use craft_keymap::{Chord, Key, Mods}; -/// What the focused stop is, as far as the table's rows differ. +/// The named key scheme of a reorderable collection. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] +pub enum ReorderKeys { + /// The stacking keys (`REORDER_KEYS`): Cmd+] and Cmd+[. + #[default] + Stacking, + /// Alt with the arrows (`ALT_ARROW_KEYS`). + AltArrows, +} + +/// What the focused stop is, as far as the table's rows differ. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub struct KeyRole { /// A value control with a reset value and no text part: Delete resets it. pub resettable: bool, @@ -17,8 +28,10 @@ pub struct KeyRole { pub space: bool, /// A collection that selects several items: Ctrl+Space (Control on macOS) toggles the lead's pick. pub multi_select: bool, - /// A reorderable collection: the stacking keys (`REORDER_KEYS`) move the selected items. - pub reorderable: bool, + /// The scheme whose keys move the selected items of a reorderable collection, `None` when it does not reorder. + pub reorderable: Option, + /// The axis the collection's order is laid out along. + pub reorder_axis: Axis, /// A collection with `CollectionProps.rename`. pub rename: bool, /// `FocusPolicy.pages`: Ctrl+Tab switches pages. @@ -52,6 +65,12 @@ pub struct KeyRole { pub home_row: usize, } +impl Default for KeyRole { + fn default() -> Self { + Self::new() + } +} + impl KeyRole { /// A role with no special rows. pub const fn new() -> KeyRole { @@ -59,7 +78,8 @@ impl KeyRole { resettable: false, space: false, multi_select: false, - reorderable: false, + reorderable: None, + reorder_axis: Axis::Y, rename: false, pages: false, nudge: false, @@ -94,9 +114,15 @@ impl KeyRole { self } - /// The stacking keys move the selected items. - pub const fn reorderable(mut self, on: bool) -> Self { - self.reorderable = on; + /// The scheme's keys move the selected items; `None` when the stop does not reorder. + pub const fn reorderable(mut self, keys: Option) -> Self { + self.reorderable = keys; + self + } + + /// The axis the order is laid out along. + pub const fn reorder_axis(mut self, axis: Axis) -> Self { + self.reorder_axis = axis; self } @@ -191,12 +217,29 @@ pub enum DropOperation { Link, } -/// The drop operation the held modifiers pick. -pub fn drop_operation(os: Os, mods: Mods) -> DropOperation { - let link = if os == Os::Mac { mods.cmd && mods.alt } else { mods.cmd && mods.shift }; +/// Which held key turns a drag into a copy over a target. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum CopyKeys { + /// Alt, Option on macOS: a design app's duplicating drag (Photoshop's layers). + #[default] + Alt, + /// The file manager's: Ctrl off macOS, Option on macOS (Explorer, Finder, a document's page grid). + Platform, +} + +/// The drop operation the held modifiers pick over a target that copies with `copy`. Link is Ctrl+Shift, Cmd+Option on +/// macOS, whatever the copy keys. +pub fn drop_operation(os: Os, mods: Mods, copy: CopyKeys) -> DropOperation { + let mac = os == Os::Mac; + let link = if mac { mods.cmd && mods.alt } else { mods.cmd && mods.shift }; + let copies = match copy { + CopyKeys::Platform if !mac => mods.cmd, + _ => mods.alt, + }; if link { DropOperation::Link - } else if mods.alt { + } else if copies { DropOperation::Copy } else { DropOperation::Move @@ -221,14 +264,32 @@ pub const REORDER_KEYS: [Chord; 6] = [ Chord::new(Mods { shift: true, ..Mods::CMD }, Key::OpenCurlyBracket), ]; -/// The `Intent::MoveItem` a stacking key asks for, `None` for any other press. -pub fn reorder_intent(key: Key, mods: Mods) -> Option { +/// The four Alt+arrow chords of `ReorderKeys::AltArrows`. +pub const ALT_ARROW_KEYS: [Chord; 4] = + [Chord::new(Mods::ALT, Key::Up), Chord::new(Mods::ALT, Key::Down), Chord::new(Mods::ALT, Key::Left), Chord::new(Mods::ALT, Key::Right)]; + +/// The `Intent::MoveItem` a key of the scheme `keys` asks for in an order laid out along `axis`, `None` for any other +/// press. +pub fn reorder_intent(key: Key, mods: Mods, keys: ReorderKeys, axis: Axis) -> Option { let chord = Chord::new(mods, key); - if !REORDER_KEYS.contains(&chord) { - return None; + match keys { + ReorderKeys::Stacking => { + if !REORDER_KEYS.contains(&chord) { + return None; + } + let front = matches!(key, Key::CloseBracket | Key::CloseCurlyBracket); + Some(Intent::move_item(front, mods.shift)) + } + ReorderKeys::AltArrows => { + if !ALT_ARROW_KEYS.contains(&chord) { + return None; + } + // Down and Right are one place later in reading order on either axis; the item step turns `front` back + // into a direction with `toward_end` over the same axis, which is its own inverse. + let later = matches!(key, Key::Down | Key::Right); + Some(Intent::move_item(toward_end(later, axis), false)) + } } - let front = matches!(key, Key::CloseBracket | Key::CloseCurlyBracket); - Some(Intent::move_item(front, mods.shift)) } /// Whether a move toward the front goes toward the end of an order laid out along `axis`. The front of a vertical @@ -256,8 +317,12 @@ pub fn intent(os: Os, key: Key, mods: Mods, role: KeyRole) -> Option { if let Some(fine) = fine_move(key, mods, role) { return Some(fine); } - if role.reorderable - && let Some(reorder) = reorder_intent(key, mods) + // Before the Alt+Up and Alt+Down rows, so that the Alt+arrow scheme reorders instead of opening or closing. Rows + // stacked one per line have no neighbour across their axis: the arrows across it stay their move rows there. + let across = if role.reorder_axis == Axis::X { matches!(key, Key::Up | Key::Down) } else { matches!(key, Key::Left | Key::Right) }; + if let Some(keys) = role.reorderable + && !(role.stacked && across) + && let Some(reorder) = reorder_intent(key, mods, keys, role.reorder_axis) { return Some(reorder); } diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 7ad5665c77..617f1f0347 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -23,8 +23,10 @@ pub mod eviction; pub mod fit; pub mod flow; pub mod focus; +pub mod frame_step; pub mod grid; pub mod hit; +pub mod hold_repeat; pub mod input; pub mod intent; pub mod item_layout; @@ -33,6 +35,7 @@ pub mod item_source; pub mod keys; pub mod label_column; pub mod layout_memory; +pub mod middle_scroll; pub mod monitor; pub mod motion; pub mod nav; @@ -64,7 +67,7 @@ pub use anchor::Anchor9; pub use arrangement::Arrangement; pub use canvas::CanvasTransform; -pub use canvas::{CanvasView, RulerUnits, Ticks, ViewHistory, ViewPlace, ZoomLadder, resize_cursor}; +pub use canvas::{CanvasView, RulerUnits, TickLabels, Ticks, ViewHistory, ViewPlace, ZoomFloor, ZoomScheme, resize_cursor}; /// The f64 geometry crate the canvas view and its callers share. pub use kurbo; @@ -79,6 +82,7 @@ pub use edit_history::EditHistory; pub use editor::{EditorInput, SurroundingUnit}; pub use flow::{Axis, Flow, Insets}; pub use focus::{CancelRule, KeyOwner, OwnerClass, PressFocus, ScopeKind}; +pub use frame_step::{FRAME_STEP_MAX, frame_step}; pub use grid::{GridCursor, GridMeasure, resolve_columns}; pub use hit::{HitLevel, HitPriority, HitShape, ResolveFor, Shape, Winner, resolve, resolve_mapped}; pub use input::Input; @@ -86,9 +90,10 @@ pub use intent::{AccessRequest, EditCommand, Granularity, Intent, MoveMods, NavM pub use item_layout::{FreeLayout, ItemLayout, LineIndex, SHEET_ZOOM, SheetLayout, SpanLayout, TileLayout}; pub use item_marquee::{MarqueeMode, MarqueeSelect}; pub use item_source::{DisplayOrder, ItemSource, Keyed, Outline, SizeHint, keyed}; -pub use keys::{DropOperation, KeyRole}; +pub use keys::{CopyKeys, DropOperation, KeyRole, ReorderKeys}; pub use label_column::{LabelColumn, LabelPlacement}; pub use layout_memory::SizeTween; +pub use middle_scroll::{MiddleButton, MiddleScroll}; pub use monitor::{Monitor, MonitorKey}; pub use motion::{MotionKind, MotionMode, Playback}; pub use nav::{Arrows, Letters, NavOutline, NavShape, NavState, NavStep, Roving, TypeAhead, lead_step, wheel_step}; @@ -96,9 +101,10 @@ pub use part::{PartKey, PartRef}; pub use pixel_size::PixelSize; +pub use hold_repeat::HoldRepeat; pub use press::{ - Buttons, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressMachine, PressPhase, PressStart, - PressState, PressStep, count_clicks, + Buttons, MultiTap, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressAside, PressCancel, PressMachine, + PressPhase, PressPick, PressStart, PressState, PressStep, count_clicks, }; pub use quantity::Reader; pub use role_rule::{GridFacts, RoleRule, is_checkable, is_selectable, role_violations}; @@ -115,7 +121,7 @@ pub use value::{ same_in_f32, same_in_f32_at, }; pub use value_drag::{DragWarp, ValueDrag, wrap_value}; -pub use wheel::{GESTURE_GAP, Wheel, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit}; +pub use wheel::{GESTURE_GAP, Wheel, WheelEase, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit}; #[cfg(test)] extern crate self as craft_behavior; diff --git a/crates/behavior/src/middle_scroll.rs b/crates/behavior/src/middle_scroll.rs new file mode 100644 index 0000000000..16d2bbe3ae --- /dev/null +++ b/crates/behavior/src/middle_scroll.rs @@ -0,0 +1,115 @@ +//! The middle button's auto-scroll latch: the gesture state of one middle press. + +use crate::frame_step; +use crate::press::PressPhase; +use emath::{Pos2, Vec2}; + +/// How far, in points, the pointer may sit above or below the anchor without scrolling. +const DEAD_ZONE: f32 = 15.0; +/// Held passes past the dead zone after which a release ends the latch: a shorter hold is a click, which keeps it. +const HELD_PASSES: u32 = 2; +/// The power of the distance the speed grows with. +const SPEED_EXPONENT: f32 = 2.2; +/// Points per second per unit of the distance raised to [`SPEED_EXPONENT`]. +const SPEED_MULTIPLIER: f32 = 0.04; +/// The farthest distance the speed is computed from, so the power of a hostile pointer position stays finite. No +/// pointer on a real screen reaches it. +const MAX_DISPLACEMENT: f32 = 1_000_000.0; + +/// What the middle button does over a scroll area. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum MiddleButton { + /// Drags the view. + #[default] + Pan, + /// Latches an auto-scroll anchor. + AutoScroll, +} + +/// The auto-scroll latch of one middle press. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MiddleScroll { + anchor: Option, + held_passes: u32, + swallowing: bool, +} + +impl MiddleScroll { + /// A middle press: inside the scroll area it latches at `at`; a second press ends the latch. + pub fn press(&mut self, at: Pos2, inside: bool) { + if self.active() { + self.cancel(); + } else if inside && at.is_finite() { + self.anchor = Some(at); + self.held_passes = 0; + } + } + + /// The button went up: after two held passes with the pointer past the dead zone the latch ends; an earlier + /// release keeps it. + pub fn release(&mut self) { + if self.held_passes >= HELD_PASSES { + self.cancel(); + } + } + + /// Whether a press's `phase` belongs to the press that ended a latch and so reaches nothing else: true for the + /// `Down` that cancels an active latch and for each later phase of that press through its release or cancel. A + /// press that begins while nothing is latched is not swallowed. + pub fn swallows(&mut self, phase: PressPhase) -> bool { + match phase { + PressPhase::Down { .. } => { + self.swallowing = self.active(); + if self.swallowing { + self.cancel(); + } + self.swallowing + } + PressPhase::Release { .. } | PressPhase::Cancel { .. } => std::mem::take(&mut self.swallowing), + PressPhase::Idle | PressPhase::Hover => false, + _ => self.swallowing, + } + } + + /// Ends the latch. + pub fn cancel(&mut self) { + self.anchor = None; + self.held_passes = 0; + } + + /// One pass: with this pass's `pointer` and `held` state it counts the held passes past the 15 pt dead zone and + /// returns the vertical scroll for the step `frame_step(dt)`, at `|d|^2.2 × 0.04` points per second, reversed by + /// `invert`. The result moves the content: with the pointer below the anchor it is negative, so the view scrolls + /// down. Zero while nothing is latched. + pub fn step(&mut self, pointer: Pos2, held: bool, dt: f64, invert: bool) -> Vec2 { + let Some(anchor) = self.anchor else { return Vec2::ZERO }; + let displacement = pointer.y - anchor.y; + if !displacement.is_finite() { + return Vec2::ZERO; + } + let distance = displacement.abs(); + if distance <= DEAD_ZONE { + return Vec2::ZERO; + } + let step = frame_step(dt); + // A frame's later passes take no time: counting them would count one frame's hold twice and end a click. + if held && step > 0.0 { + self.held_passes = self.held_passes.saturating_add(1); + } + // The full distance sets the speed, not the part past the dead zone. + let speed = distance.min(MAX_DISPLACEMENT).powf(SPEED_EXPONENT) * SPEED_MULTIPLIER; + let delta = -displacement.signum() * speed * step as f32; + Vec2::new(0.0, if invert { -delta } else { delta }) + } + + /// Where the latch is anchored, `None` when there is none. + pub fn anchor(&self) -> Option { + self.anchor + } + + /// Whether a latch is active. + pub fn active(&self) -> bool { + self.anchor.is_some() + } +} diff --git a/crates/behavior/src/nav/step.rs b/crates/behavior/src/nav/step.rs index bb93f2df45..d25aff01a5 100644 --- a/crates/behavior/src/nav/step.rs +++ b/crates/behavior/src/nav/step.rs @@ -330,17 +330,17 @@ fn ragged_at(outline: &dyn NavOutline, row: usize, column: usize) -> Option NavStep { let Some((row, column, _)) = locate(outline, lead) else { return NavStep::Unhandled }; let rows = (0..).take_while(|&r| outline.row_len(r).is_some()).count(); - // A row without a position that takes the lead (a closed group's) is passed over in the move's direction. + // A row without a position that takes the lead (a closed group's, a divider's) is passed over in the move's + // direction. let shifted = |to: usize| column.saturating_add_signed(outline.column_shift(row, to)); let toward = |rows: Vec| moved(rows.into_iter().find_map(|to| ragged_at(outline, to, shifted(to)))); - let vertical = |to: Option| moved(to.and_then(|to| ragged_at(outline, to, shifted(to)))); match mv { NavMove::Back => moved(neighbour(outline, state, lead, false)), NavMove::Forward => moved(neighbour(outline, state, lead, true)), NavMove::Up => toward((0..row).rev().collect()), NavMove::Down => toward((row + 1..rows).collect()), - NavMove::PageUp => vertical(Some(row.saturating_sub(state.page))), - NavMove::PageDown => vertical(Some((row + state.page).min(rows - 1))), + NavMove::PageUp => toward((0..=row.saturating_sub(state.page)).rev().collect()), + NavMove::PageDown => toward(((row + state.page).min(rows - 1)..rows).collect()), NavMove::Start => moved(first_enabled(outline)), NavMove::End => moved(last_enabled(outline)), } diff --git a/crates/behavior/src/overlay.rs b/crates/behavior/src/overlay.rs index 365078a3b4..680c616ecb 100644 --- a/crates/behavior/src/overlay.rs +++ b/crates/behavior/src/overlay.rs @@ -101,6 +101,10 @@ pub struct PlaceRequest { /// over the anchor from the preferred side; only one taller than the bounds is capped. For a context menu, whose /// anchor is a point or a row. pub covers_anchor: bool, + /// After side, alignment and the bounds clamp, the overlay shifts by this and clamps again. + pub offset: Vec2, + /// When the shifted overlay would cover this rect, the unshifted one wins. + pub clear: Option, } impl PlaceRequest { @@ -118,6 +122,8 @@ impl PlaceRequest { kept: None, flips_across: false, covers_anchor: false, + offset: Vec2::ZERO, + clear: None, } } @@ -163,6 +169,18 @@ impl PlaceRequest { self } + /// Shifts the overlay by `by` after it is placed and clamped. + pub const fn offset(mut self, by: Vec2) -> Self { + self.offset = by; + self + } + + /// Keeps the unshifted place when the shifted overlay would cover `rect`. + pub const fn clear(mut self, rect: Option) -> Self { + self.clear = rect; + self + } + /// Lines up with the anchor's other end, beside it, when that fits and the aligned end does not. pub const fn flips_across(mut self, on: bool) -> Self { self.flips_across = on; @@ -214,7 +232,9 @@ fn room(anchor: Rect, bounds: Rect, side: Side, rtl: bool, gap: f32) -> f32 { /// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Below or above the anchor, a /// request that covers its anchor and fits neither side keeps the preferred side and its height up to the bounds' and /// slides over the anchor. Beside the anchor, a request that flips across lines up with the anchor's other end when it -/// runs past the bounds from the aligned end and fits from the other. The rect is always finite and inside the bounds. +/// runs past the bounds from the aligned end and fits from the other. The rect is then shifted by the request's +/// `offset` and clamped again, unless the shifted rect would cover `clear`, in which case the unshifted one stays. The +/// rect is always finite and inside the bounds. pub fn place(request: &PlaceRequest) -> Placement { let anchor = clean(request.anchor); let bounds = clean(request.bounds); @@ -262,7 +282,11 @@ pub fn place(request: &PlaceRequest) -> Placement { (Side::Start, true) | (Side::End, false) => Pos2::new(anchor.right() + gap, across_y), }; let max_min = Pos2::new((bounds.right() - size.x).max(bounds.left()), (bounds.bottom() - size.y).max(bounds.top())); - let min = Pos2::new(min.x.clamp(bounds.left(), max_min.x), min.y.clamp(bounds.top(), max_min.y)); + let keep = |min: Pos2| Pos2::new(min.x.clamp(bounds.left(), max_min.x), min.y.clamp(bounds.top(), max_min.y)); + let min = keep(min); + let shifted = keep(min + Vec2::new(finite(request.offset.x), finite(request.offset.y))); + let hides_clear = request.clear.map(clean).is_some_and(|clear| clear.intersects(Rect::from_min_size(shifted, size))); + let min = if hides_clear { min } else { shifted }; Placement { rect: Rect::from_min_size(min, size), side } } @@ -290,6 +314,20 @@ mod tests { assert_eq!(neither.bottom(), BOUNDS.bottom(), "fits neither way: slides up to stay inside"); } + #[test] + fn an_overlay_with_no_room_on_its_side_opens_on_the_other() { + let size = Vec2::new(200.0, 80.0); + let low = rect(300.0, 540.0, 100.0, 30.0); + let placed = place(&PlaceRequest::new(low, size, BOUNDS).side(Side::Below).gap(4.0)); + assert_eq!(placed.side, Side::Above, "no room below the anchor: {placed:?}"); + assert!(placed.rect.bottom() <= low.top(), "above the anchor: {placed:?}"); + assert!(BOUNDS.contains_rect(placed.rect), "{placed:?}"); + let high = rect(300.0, 100.0, 100.0, 30.0); + let placed = place(&PlaceRequest::new(high, size, BOUNDS).side(Side::Below).gap(4.0)); + assert_eq!(placed.side, Side::Below, "room below: {placed:?}"); + assert!(placed.rect.top() >= high.bottom(), "below the anchor: {placed:?}"); + } + #[test] fn a_menu_that_covers_its_anchor_and_fits_neither_side_keeps_its_height_and_slides_over_the_anchor() { let point = rect(300.0, 400.0, 0.0, 0.0); @@ -312,6 +350,22 @@ mod tests { assert_eq!(place(&request.side(Side::End)).rect.width(), 120.0, "beside it: its own width"); } + #[test] + fn an_offset_overlay_moves_unless_it_would_cover_its_clear_rect() { + let request = PlaceRequest::new(rect(100.0, 100.0, 200.0, 24.0), Vec2::new(100.0, 40.0), BOUNDS); + let home = place(&request).rect; + assert_eq!(home.min, Pos2::new(100.0, 124.0), "below the anchor, aligned to its start"); + let by = Vec2::new(50.0, 30.0); + let moved = request.offset(by); + assert_eq!(place(&moved).rect.min, home.min + by, "shifted by the offset"); + let point = Rect::from_min_max(Pos2::new(160.0, 170.0), Pos2::new(160.0, 170.0)); + assert_eq!(place(&moved.clear(Some(point))).rect, home, "the shifted rect would cover the point: the unshifted one stays"); + let aside = rect(600.0, 500.0, 10.0, 10.0); + assert_eq!(place(&moved.clear(Some(aside))).rect.min, home.min + by, "a clear rect off to the side changes nothing"); + let far = place(&request.offset(Vec2::new(10_000.0, 0.0))).rect; + assert_eq!(far.right(), BOUNDS.right(), "the shifted rect is clamped inside the bounds"); + } + #[test] fn rect_is_finite_and_inside_the_bounds_for_any_request() { let sides = [Side::Below, Side::Above, Side::Start, Side::End]; @@ -328,7 +382,9 @@ mod tests { .align(align) .rtl(i % 2 == 0) .gap(if i == 1 { 4.0 } else { 0.0 }) - .covers_anchor(align != Align::Start); + .covers_anchor(align != Align::Start) + .offset(Vec2::new(w, y)) + .clear(Some(rect(h, x, w.abs(), y.abs()))); let placed = place(&request).rect; assert!(placed.min.is_finite() && placed.max.is_finite(), "{request:?}"); assert!(BOUNDS.contains_rect(placed), "{request:?} gave {placed:?}"); diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index ba4a4d7f30..50269615ff 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -99,12 +99,14 @@ pub struct PointerSample { pub rotation: f32, /// The eraser end of a pen. pub eraser: bool, + /// An airbrush pen's finger wheel, 0 to 1; `None` when the pen has none. + pub wheel: Option, } impl PointerSample { /// A sample with no tilt or rotation. pub const fn new(pressure: f32) -> Self { - PointerSample { pressure, tilt: [0.0, 0.0], rotation: 0.0, eraser: false } + PointerSample { pressure, tilt: [0.0, 0.0], rotation: 0.0, eraser: false, wheel: None } } /// The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value @@ -118,7 +120,8 @@ impl PointerSample { let quarter = std::f32::consts::FRAC_PI_2; let tilt = self.tilt.map(|tilt| if tilt.is_finite() { tilt.clamp(-quarter, quarter) } else { 0.0 }); let rotation = if self.rotation.is_finite() { self.rotation } else { 0.0 }; - PointerSample { pressure, tilt, rotation, eraser: self.eraser } + let wheel = self.wheel.filter(|wheel| wheel.is_finite()).map(|wheel| wheel.clamp(0.0, 1.0)); + PointerSample { pressure, tilt, rotation, eraser: self.eraser, wheel } } } @@ -157,6 +160,25 @@ pub enum PressCancel { Removed, /// The host ended what the press acted on (`primitives::cancel_press_of`). Host, + /// A second finger landed while a press was open. + Gesture, +} + +/// Two or more fingers came down and all lifted within [`MULTI_TAP_TIME`] without moving past [`MULTI_TAP_SLOP`]. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct MultiTap { + /// How many fingers tapped. + pub fingers: u8, + /// The centre of the fingers. + pub at: Pos2, +} + +impl MultiTap { + /// A tap of `fingers` around `at`. + pub const fn new(fingers: u8, at: Pos2) -> Self { + MultiTap { fingers, at } + } } /// One part's press state in one pass. @@ -284,15 +306,24 @@ pub struct PressState { pub sample: Option, /// A drag holds the pointer: nothing else hovers. pub captured: bool, + /// Where a secondary press made during another open press came up on this part in this pass + /// ([`PressStep::aside`]): a context request beside the running phase, which goes on. + pub context: Option, } impl PressState { /// A part with no press history. pub const IDLE: PressState = PressState::new(PressPhase::Idle); - /// A state in `phase` with no modifiers, sample or capture. + /// A state in `phase` with no modifiers, sample, capture or aside context request. pub const fn new(phase: PressPhase) -> Self { - PressState { phase, mods: Mods::NONE, sample: None, captured: false } + PressState { phase, mods: Mods::NONE, sample: None, captured: false, context: None } + } + + /// The aside secondary press that came up on the part at `at` in this pass. + pub const fn context(mut self, at: Option) -> Self { + self.context = at; + self } /// The modifiers held. @@ -332,6 +363,13 @@ impl Default for PressState { /// The longest gap between presses that still count as one multi-click, in seconds. pub const MULTI_CLICK_TIME: f64 = 0.3; +/// The longest the fingers of a multi-finger tap may stay down, in seconds. +pub const MULTI_TAP_TIME: f64 = 0.5; + +/// How far a finger of a multi-finger tap may move from where it landed, in points: fingers drift more than a +/// pointer does while the others land. +pub const MULTI_TAP_SLOP: f32 = 16.0; + /// The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks, /// mods)`: one more when it follows within [`MULTI_CLICK_TIME`] and `slop` of the previous one with the same /// modifiers, else 1. @@ -455,11 +493,56 @@ pub struct PressStep { pub dragging: bool, /// The target released as a click in this pass. pub activated: Option, + /// The start of an open press whose sense has `PASSES_DRAG` and no `DRAG` that moved past slop in this pass: + /// the caller may hand it to the shape below with [`PressMachine::hand_over`]. + pub passes: Option, + /// A secondary press that came up in this pass while a primary press stayed open: a right-click during a drag. The + /// open press goes on; the aside asks its target for a context menu. + pub aside: Option>, } impl Default for PressStep { fn default() -> Self { - PressStep { target: None, phase: None, dragging: false, activated: None } + PressStep { target: None, phase: None, dragging: false, activated: None, passes: None, aside: None } + } +} + +/// A secondary press made and released while a primary press was open ([`PressStep::aside`]). Its target is the one +/// `pick` gave the secondary press, so it senses `Sense::CONTEXT_CLICK`. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct PressAside { + /// The target of the secondary press. + pub target: T, + /// Where and when the secondary button went down. + pub start: PressStart, + /// Where it came up, in screen space. + pub pos: Pos2, +} + +/// The press winner a root picks at a press position, as [`PressMachine::step`]'s `pick` returns it. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct PressPick { + /// The press winner. + pub target: T, + /// What it senses of the press. + pub sense: Sense, + /// The press's click went to a shape above that passes its drag to this target (`Sense::PASSES_DRAG`): the press + /// opens silent and is the target's only once its drag starts. + pub passed: bool, +} + +impl PressPick { + /// `target`, sensing `sense`, takes the press. + pub fn new(target: T, sense: Sense) -> Self { + PressPick { target, sense, passed: false } + } + + /// The press's click went to a shape above that passes its drag to this target. + pub fn passed(mut self) -> Self { + self.passed = true; + self } } @@ -471,6 +554,13 @@ struct Open { dragging: bool, /// Moved past slop on a target that senses no drag: the click is gone and nothing starts. abandoned: bool, + /// Moved past slop in this pass on a target that clicks and passes its drag (`Sense::PASSES_DRAG`), with the + /// pointer at the pass's end: no click and no drag until [`PressMachine::hand_over`] gives the press its new + /// target. The next pass abandons a press no shape took. + passing: Option, + /// A press passed to this target ([`PressPick::passed`]) whose drag has not started: it reports nothing, and a + /// release or cancel ends it unreported. Its move past slop starts the drag with `DragStart`, as a hand-over does. + silent: bool, /// The pointer left the window ([`PointerEvent::Gone`]): the click is gone, but a target that senses a drag still /// starts it from the moves that follow. The button is still down and the window keeps getting the pointer's moves /// and release while it is outside, so a press near a window edge (a window's resize grip) that leaves the window @@ -487,14 +577,14 @@ struct Open { } impl Open { - /// A phase before the release is still to be reported. + /// A phase before the release is still to be reported, or the press waits for its hand-over. fn owes_phase(&self) -> bool { - !self.reported || (self.dragging && !self.drag_reported) + !self.reported || (self.dragging && !self.drag_reported) || self.passing.is_some() } /// A release now is a click. fn clicks(&self) -> bool { - !self.dragging && !self.abandoned && !self.left && self.sense.contains(Sense::CLICK) + !self.dragging && !self.abandoned && !self.left && self.passing.is_none() && self.sense.contains(Sense::CLICK) } } @@ -502,18 +592,20 @@ impl Open { #[derive(Clone, Copy, Debug)] pub struct PressMachine { open: Option>, + /// The secondary press held beside the open primary press, with its target and start. + aside: Option<(T, PressStart)>, } impl Default for PressMachine { fn default() -> Self { - PressMachine { open: None } + PressMachine { open: None, aside: None } } } impl PressMachine { /// A machine with no press. pub const fn new() -> Self { - PressMachine { open: None } + PressMachine { open: None, aside: None } } /// The target of the open press. @@ -531,27 +623,67 @@ impl PressMachine { self.open.is_some_and(|open| open.dragging) } + /// The press the open press began as. + pub fn start(&self) -> Option { + self.open.map(|open| open.start) + } + + /// Takes over a press whose button is down and went down elsewhere, as a drag of `target` from `start`: the next + /// pass reports `DragStart`, and later ones the press's own `Drag`, `Release` or `Cancel` from their input. A + /// press this machine holds already stays as it is. + // PLAN: the sheet's Files table has no row for this file; the handover of a held press (decision q346) needs the + // machine to open a press that did not begin on it, which only the machine can build. + pub fn take_over(&mut self, target: T, sense: Sense, start: PressStart) { + if self.open.is_some() { + return; + } + self.open = Some(Open { + target, + sense: sense - Sense::CLICK, + start, + dragging: true, + abandoned: false, + left: false, + reported: true, + drag_reported: false, + released_at: None, + passing: None, + silent: false, + }); + } + /// Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may /// come to start it. pub fn release_held(&self) -> bool { self.open.is_some_and(|open| open.released_at.is_some()) } - /// Runs one pass. `pick` chooses the press winner and what it senses at a press position; it returns `None` - /// when no shape of this root takes the press. - pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2) -> Option<(T, Sense)>) -> PressStep { + /// Runs one pass. `pick` chooses the press winner and what it senses at a press position, for the button pressed + /// there; it returns `None` when no shape of this root takes the press. A secondary press goes only to a shape that + /// senses `Sense::CONTEXT_CLICK`, so `pick` passes over the others for it, to the next shape under the press. + pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2, PointerButton) -> Option>) -> PressStep { let mut pos = input.pos; - let mut released: Option<(T, PressStart, Pos2, bool, bool)> = None; - let mut cancelled: Option<(T, PressStart, PressCancel)> = None; + // The press released or cancelled in this pass, and whether it was silent: one that ends silent reports nothing. + let mut released: Option<(T, PressStart, Pos2, bool, bool, bool)> = None; + let mut cancelled: Option<(T, PressStart, PressCancel, bool)> = None; + let mut aside: Option> = None; + // A press passed in the last pass that no shape took is abandoned; that pass reported its `Down`. + if let Some(open) = &mut self.open + && open.passing.is_some() + { + open.passing = None; + open.abandoned = true; + open.reported = true; + } if let Some(open) = self.open && let Some((at, click)) = open.released_at && !open.owes_phase() { - released = Some((open.target, open.start, at, open.dragging, click)); + released = Some((open.target, open.start, at, open.dragging, click, open.silent)); self.open = None; } if let (Some(reason), Some(open)) = (input.cancel, self.open) { - cancelled = Some((open.target, open.start, reason)); + cancelled = Some((open.target, open.start, reason, open.silent)); self.open = None; } for event in input.events { @@ -562,10 +694,14 @@ impl PressMachine { && open.released_at.is_none() && !open.dragging && !open.abandoned + && open.passing.is_none() && at.distance(open.start.origin) > input.slop { if open.sense.contains(Sense::DRAG) { open.dragging = true; + open.silent = false; + } else if open.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) { + open.passing = Some(at); } else { open.abandoned = true; } @@ -582,44 +718,70 @@ impl PressMachine { if let Some(open) = self.open && let Some((up, click)) = open.released_at { - released = Some((open.target, open.start, up, open.dragging, click)); + released = Some((open.target, open.start, up, open.dragging, click, open.silent)); self.open = None; } + // A secondary press during an open primary press goes beside it, to the context target `pick` gives + // it, and the primary press goes on (a right-click during a drag asks for the menu there). + if button == PointerButton::Secondary + && self.aside.is_none() + && self.open.is_some_and(|open| open.start.button == PointerButton::Primary) + { + let start = PressStart::new(at, button, time, clicks); + self.aside = pick(at, button).filter(|pick| pick.sense.contains(Sense::CONTEXT_CLICK)).map(|pick| (pick.target, start)); + continue; + } // An open press keeps the pointer until its button comes up: no press starts over it, of its own // button (a repeated Down, as a window never sends one) or another. Its moves and its release still - // reach it when a modal opened over its target since. A middle or secondary press captures for a - // drag (a canvas pan, a drag with the secondary button) and never clicks. A target that senses - // `MIDDLE_CLICK` also takes a middle press that can click (a tab closes on it), and one that senses - // `CONTEXT_CLICK` takes a secondary press, which a click-only target would not capture. + // reach it when a modal opened over its target since. A middle press captures for a drag (a canvas + // pan) and never clicks, unless its target senses `MIDDLE_CLICK` (a tab closes on it). A secondary + // press is only a target's that senses `CONTEXT_CLICK`, which clicks and drags with it; a target that + // only drags (a transform box) leaves it to the context target under it. let capture_only = button != PointerButton::Primary; if !matches!(button, PointerButton::Primary | PointerButton::Middle | PointerButton::Secondary) || self.open.is_some() { continue; } - self.open = pick(at) - .map(|(target, sense)| { + self.open = pick(at, button) + .map(|pick| { let clicks = match button { - PointerButton::Middle => sense.contains(Sense::MIDDLE_CLICK), - PointerButton::Secondary => sense.contains(Sense::CONTEXT_CLICK), + PointerButton::Middle => pick.sense.contains(Sense::MIDDLE_CLICK), + PointerButton::Secondary => pick.sense.contains(Sense::CONTEXT_CLICK), _ => false, }; - (target, if capture_only && !clicks { sense - Sense::CLICK } else { sense }, clicks) + let sense = if capture_only && !clicks { pick.sense - Sense::CLICK } else { pick.sense }; + (pick, sense, clicks) }) - .filter(|(_, sense, clicks)| !capture_only || *clicks || sense.contains(Sense::DRAG)) - .map(|(target, sense, _)| (target, sense)) - .map(|(target, sense)| Open { - target, - sense, - start: PressStart::new(at, button, time, clicks), - dragging: false, - abandoned: false, - left: false, - reported: false, - drag_reported: false, - released_at: None, + .filter(|(_, sense, clicks)| match button { + PointerButton::Primary => true, + PointerButton::Middle => *clicks || sense.contains(Sense::DRAG), + _ => *clicks, + }) + .map(|(pick, sense, _)| { + // A silent press owes no `Down`: its first phase is its `DragStart`. + let silent = pick.passed && sense.contains(Sense::DRAG); + Open { + target: pick.target, + sense, + start: PressStart::new(at, button, time, clicks), + dragging: false, + abandoned: false, + left: false, + passing: None, + silent, + reported: silent, + drag_reported: false, + released_at: None, + } }); } PointerEvent::Released { button, pos: at } => { pos = at; + if button == PointerButton::Secondary + && let Some((target, start)) = self.aside.take() + { + aside = Some(PressAside { target, start, pos: at }); + continue; + } if self.open.is_some_and(|open| open.start.button != button || open.released_at.is_some()) { continue; } @@ -628,7 +790,7 @@ impl PressMachine { { open.released_at = Some((at, open.clicks())); } else if let Some(open) = self.open.take() { - released = Some((open.target, open.start, at, open.dragging, open.clicks())); + released = Some((open.target, open.start, at, open.dragging, open.clicks(), open.silent)); } } } @@ -637,20 +799,38 @@ impl PressMachine { if self.open.is_some_and(|open| open.released_at.is_none()) && !input.held && released.is_none() { self.open = None; } - if let Some((target, start, reason)) = cancelled { - let phase = PressPhase::Cancel { start, reason }; - return PressStep { target: Some(target), phase: Some(phase), dragging: false, activated: None }; + // An aside press lasts no longer than the press it went beside. + if self.open.is_none() { + self.aside = None; } - if let Some((target, start, at, was_dragging, click)) = released { + let quiet = PressStep { aside, ..PressStep::default() }; + if let Some((target, start, reason, silent)) = cancelled { + if silent { + return quiet; + } + let phase = PressPhase::Cancel { start, reason }; + return PressStep { target: Some(target), phase: Some(phase), ..quiet }; + } + if let Some((target, start, at, was_dragging, click, silent)) = released { + if silent { + return quiet; + } let phase = PressPhase::Release { start, pos: at, click }; return PressStep { target: Some(target), phase: Some(phase), dragging: was_dragging, activated: (click && start.button == PointerButton::Primary).then_some(target), + ..quiet }; } - let Some(open) = self.open.as_mut() else { return PressStep::default() }; + let Some(open) = self.open.as_mut() else { return quiet }; + if open.silent { + return quiet; + } + if let Some(at) = &mut open.passing { + *at = pos; + } let phase = if !open.reported { PressPhase::Down { start: open.start } } else if open.dragging && !open.drag_reported { @@ -661,8 +841,33 @@ impl PressMachine { } else { PressPhase::Held { start: open.start, pos } }; - open.reported = true; - PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, activated: None } + // A passing press owes its `Down` to the shape `hand_over` gives it when this pass is its first. + if open.passing.is_none() { + open.reported = true; + } + let passes = open.passing.map(|_| open.start); + PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, passes, ..quiet } + } + + /// Makes `target` the open press's target in the pass that reported `passes`, dragging from the same + /// `PressStart`. It returns the `DragStart` step when an earlier pass reported the press, and the `Down` step + /// (the `DragStart` follows in the next pass) when the move past slop came in the pass of the press itself. + /// `None` when no press passes in this pass or `sense` has no `DRAG`; the next pass abandons the press. The step + /// has no [`aside`](PressStep::aside): that stays the pass's own step's. + pub fn hand_over(&mut self, target: T, sense: Sense) -> Option> { + let open = self.open.as_mut().filter(|open| !open.abandoned && sense.contains(Sense::DRAG))?; + let at = open.passing.take()?; + open.target = target; + open.sense = sense; + open.dragging = true; + let phase = if open.reported { + open.drag_reported = true; + PressPhase::DragStart { start: open.start, pos: at } + } else { + open.reported = true; + PressPhase::Down { start: open.start } + }; + Some(PressStep { target: Some(target), phase: Some(phase), dragging: open.drag_reported, ..PressStep::default() }) } } @@ -675,7 +880,7 @@ mod tests { fn pass(machine: &mut PressMachine, events: &[PointerEvent], sense: Sense) -> PressStep { let held = machine.open.is_some() || matches!(events.last(), Some(PointerEvent::Pressed { .. })); - machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), held), |_| Some((1, sense))) + machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), held), |_, _| Some(PressPick::new(1, sense))) } fn press(x: f32, time: f64) -> PointerEvent { @@ -698,6 +903,37 @@ mod tests { assert_eq!(step.activated, Some(1)); } + /// A right-click during a drag goes beside it: the secondary release reports an aside on the context target, and the + /// drag goes on to its own release. A secondary press on a target without `CONTEXT_CLICK` reports none. + #[test] + fn a_secondary_click_during_a_drag_reports_an_aside_and_the_drag_goes_on() { + let (from, to, menu) = (pos2(0.0, 0.0), pos2(40.0, 0.0), pos2(40.0, 5.0)); + let mut machine = PressMachine::new(); + let mut pass = |events: &[PointerEvent]| { + machine.step(PassInput::new(events, SLOP, to, true), |_, button| match button { + PointerButton::Secondary => Some(PressPick::new(2, Sense::CLICK | Sense::CONTEXT_CLICK)), + _ => Some(PressPick::new(1, Sense::DRAG)), + }) + }; + pass(&[PointerEvent::pressed(from, 1.0, 1)]); + pass(&[PointerEvent::moved(to, None)]); + let down = pass(&[PointerEvent::pressed_by(PointerButton::Secondary, menu, 1.2, 1)]); + assert!(down.aside.is_none(), "nothing asks before the secondary button comes up"); + assert!(matches!(down.phase, Some(PressPhase::Drag { .. })), "the drag goes on: {down:?}"); + let up = pass(&[PointerEvent::released_by(PointerButton::Secondary, menu)]); + assert_eq!(up.aside.map(|aside| (aside.target, aside.pos)), Some((2, menu)), "the release asks the context target"); + assert_eq!(up.target, Some(1), "the drag keeps its target"); + assert!(up.phase.is_some_and(|phase| phase.is_drag()), "and its drag: {up:?}"); + let end = pass(&[PointerEvent::released(to)]); + assert!(matches!(end.phase, Some(PressPhase::Release { .. })) && end.aside.is_none(), "the drag ends on its own release: {end:?}"); + + let mut machine = PressMachine::new(); + let mut pass = |events: &[PointerEvent]| machine.step(PassInput::new(events, SLOP, to, true), |_, _| Some(PressPick::new(1, Sense::DRAG))); + pass(&[PointerEvent::pressed(from, 1.0, 1)]); + pass(&[PointerEvent::pressed_by(PointerButton::Secondary, menu, 1.2, 1)]); + assert!(pass(&[PointerEvent::released_by(PointerButton::Secondary, menu)]).aside.is_none(), "a drag-only target takes no aside"); + } + /// The phases a sequence of passes reports, as `D`own, `H`eld, `S` (drag start), `G` (drag), `R`elease with `!` for an /// activation, `-` for none. fn phases(passes: &[&[PointerEvent]], sense: Sense) -> String { @@ -727,8 +963,9 @@ mod tests { fn a_press_of_the_held_button_leaves_the_open_drag_its_moves_and_release() { let first = pos2(0.0, 0.0); let mut machine = PressMachine::new(); - let mut step = - |events: &[PointerEvent]| machine.step(PassInput::new(events, SLOP, first, true), |at| (at == first).then_some((1u8, Sense::DRAG))); + let mut step = |events: &[PointerEvent]| { + machine.step(PassInput::new(events, SLOP, first, true), |at, _| (at == first).then_some(PressPick::new(1u8, Sense::DRAG))) + }; step(&[press(0.0, 1.0)]); step(&[PointerEvent::Moved { at: pos2(40.0, 0.0), sample: None }]); let repeated = step(&[press(50.0, 1.2)]); @@ -745,6 +982,22 @@ mod tests { assert!(machine.target().is_none(), "the release ends the press"); } + /// A press taken over from another machine reports its drag's start first, then the held button's own drag and + /// release, which never clicks. + #[test] + fn a_press_taken_over_reports_its_drag_start_then_its_own_phases() { + let origin = pos2(10.0, 0.0); + let mut machine = PressMachine::new(); + machine.take_over(1u8, Sense::DRAG | Sense::CLICK, PressStart::new(origin, PointerButton::Primary, 1.0, 1)); + let first = pass(&mut machine, &[], Sense::DRAG); + assert!(matches!(first.phase, Some(PressPhase::DragStart { start, .. }) if start.origin == origin), "{:?}", first.phase); + let moved = pass(&mut machine, &[PointerEvent::moved(pos2(30.0, 0.0), None)], Sense::DRAG); + assert!(matches!(moved.phase, Some(PressPhase::Drag { pos, .. }) if pos == pos2(30.0, 0.0)), "{:?}", moved.phase); + let up = pass(&mut machine, &[PointerEvent::released(pos2(30.0, 0.0))], Sense::DRAG); + assert!(matches!(up.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", up.phase); + assert_eq!(up.activated, None, "a taken-over press is no click"); + } + /// The pointer leaving the window (a press on a window's edge grip pulled outward) ends the press's click but not /// its drag: the window keeps getting the held button's moves from outside, and they start the drag once past slop. /// The resize from a window edge used to fail whenever the pointer left the window before it passed slop. @@ -783,4 +1036,79 @@ mod tests { let passes: [&[PointerEvent]; 5] = [&[press(0.0, 1.0)], &[up, second], &[far, up], &[], &[]]; assert_eq!(phases(&passes, Sense::CLICK | Sense::DRAG), "D R! D S R"); } + + const PASSES: Sense = Sense::CLICK.union(Sense::PASSES_DRAG); + + /// One pass with the button held at its end, over a root whose press winner is target 1 and passes its drag. + fn passing_pass(machine: &mut PressMachine, events: &[PointerEvent]) -> PressStep { + machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), true), |_, _| Some(PressPick::new(1, PASSES))) + } + + fn moved(x: f32) -> PointerEvent { + PointerEvent::Moved { at: pos2(x, 0.0), sample: None } + } + + fn up(x: f32) -> PointerEvent { + PointerEvent::released(pos2(x, 0.0)) + } + + #[test] + fn a_drag_past_slop_on_a_part_that_passes_it_goes_to_the_shape_below() { + let origin = pos2(0.0, 0.0); + assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(SLOP / 2.0)]], PASSES), "D R!", "within slop the press is the shape's click"); + + // The press was reported in an earlier pass: the shape below drags from the pass of the move. + let mut machine = PressMachine::new(); + let down = passing_pass(&mut machine, &[press(0.0, 1.0)]); + assert!(matches!(down.phase, Some(PressPhase::Down { .. })) && down.passes.is_none(), "{down:?}"); + assert!(machine.hand_over(2, Sense::DRAG).is_none(), "a press within slop passes nothing"); + let passed = passing_pass(&mut machine, &[moved(40.0)]); + assert_eq!(passed.passes.map(|start| start.origin), Some(origin), "{passed:?}"); + let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag"); + assert_eq!(handed.target, Some(2)); + assert!( + matches!(handed.phase, Some(PressPhase::DragStart { start, pos }) if start.origin == origin && pos == pos2(40.0, 0.0)), + "{:?}", + handed.phase + ); + let drag = passing_pass(&mut machine, &[moved(60.0)]); + assert_eq!(drag.target, Some(2)); + assert!(matches!(drag.phase, Some(PressPhase::Drag { .. })), "{:?}", drag.phase); + let end = passing_pass(&mut machine, &[up(60.0)]); + assert_eq!(end.target, Some(2)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); + assert_eq!(end.activated, None, "a passed press is no click"); + } + + /// The move past slop came in the press's own pass: the shape below gets the Down, its DragStart next pass, and a + /// release in between waits for it. + #[test] + fn a_drag_past_slop_in_the_press_pass_hands_the_down_over() { + let origin = pos2(0.0, 0.0); + let mut machine = PressMachine::new(); + let first = passing_pass(&mut machine, &[press(0.0, 1.0), moved(40.0)]); + assert!(matches!(first.phase, Some(PressPhase::Down { .. })) && first.passes.is_some(), "{first:?}"); + let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag"); + assert_eq!(handed.target, Some(2)); + assert!(matches!(handed.phase, Some(PressPhase::Down { start }) if start.origin == origin), "{:?}", handed.phase); + let start = passing_pass(&mut machine, &[up(40.0)]); + assert_eq!(start.target, Some(2)); + assert!(matches!(start.phase, Some(PressPhase::DragStart { .. })), "{:?}", start.phase); + assert!(machine.release_held(), "the release waits for the owed DragStart"); + let end = passing_pass(&mut machine, &[]); + assert_eq!(end.target, Some(2)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); + } + + /// No shape took the passed press: it is abandoned, and its release is no click. + #[test] + fn a_passed_press_no_shape_takes_is_abandoned() { + let mut machine = PressMachine::new(); + let _ = passing_pass(&mut machine, &[press(0.0, 1.0)]); + assert!(passing_pass(&mut machine, &[moved(40.0)]).passes.is_some()); + let end = passing_pass(&mut machine, &[up(40.0)]); + assert_eq!(end.target, Some(1)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); + assert_eq!(end.activated, None); + } } diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index b424c342cb..0aae495027 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -11,9 +11,10 @@ fn digit(c: char) -> Option { DIGIT_BLOCKS.iter().find_map(|&zero| (zero..zero + 10).contains(&(c as u32)).then(|| c as u32 - zero)) } -/// Whether `c` can be part of a unit spelling: a letter or a symbol that stands for a unit (`%`, `°`, `×`). +/// Whether `c` can be part of a unit spelling: a letter or a symbol that stands for a unit (`%`, `°`). `×` is the +/// product sign, never part of a unit. fn is_unit_char(c: char) -> bool { - c.is_alphabetic() || matches!(c, '%' | '\u{2030}' | '°' | '×' | '′' | '″') + c.is_alphabetic() || matches!(c, '%' | '\u{2030}' | '°' | '′' | '″') } /// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can @@ -29,23 +30,30 @@ struct Unit { factor: f64, /// What the caller named this unit by, handed back by [`Reader::read_tagged`]. tag: Option, + /// The factor of a number written right after the spelling ([`Reader::split_unit`]). + rest: Option, } /// Reads numbers, expressions and unit quantities written in one locale. /// -/// Grammar: `expr = term (('+' | '-') term)*`, `term = factor (('*' | '/') factor)*`, -/// `factor = ('-' | '+')? (number unit? | '(' expr ')')`. Text that starts with `+`, `*` or `/` is relative: it -/// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. +/// Grammar: `expr = term (('+' | '-') term)*`, `term = factor (('*' | '/' | 'x' | 'X' | '×') factor)*`, +/// `factor = ('-' | '+')? (number unit? | '(' expr ')')`. A factor after `*`, `/`, `x` or `×` may be a percentage +/// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it +/// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest +/// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a +/// quantity when `px` is registered. A group separator counts only before exactly three digits. #[derive(Clone, Debug, PartialEq)] pub struct Reader { decimal: char, group: Option, units: Vec, + /// The factor of a number with no unit ([`Reader::bare`]). + bare: f64, } impl Default for Reader { fn default() -> Self { - Reader { decimal: '.', group: None, units: Vec::new() } + Reader { decimal: '.', group: None, units: Vec::new(), bare: 1.0 } } } @@ -55,6 +63,15 @@ impl Reader { Self::default() } + /// A number with no unit counts as `factor` of the reader's base unit (a picas field reads bare numbers as + /// points: `1.0 / 12.0`). The factor applies to the first number of each term; a number after `*`, `/`, `x` or + /// `×` is a plain multiplier, so `12*2` is two factors of twelve points. + #[must_use] + pub fn bare(mut self, factor: f64) -> Self { + self.bare = factor; + self + } + /// The decimal separator. #[must_use] pub fn decimal(mut self, decimal: char) -> Self { @@ -69,18 +86,26 @@ impl Reader { self } - /// A unit spelling (case-insensitive; letters or the symbols `%`, `°`, `×`) and its factor to the base unit. + /// A unit spelling (case-insensitive; letters or the symbols `%`, `°`) and its factor to the base unit. /// Spaces between the number and the spelling are skipped, so "12 %" reads like "12%". #[must_use] pub fn unit(mut self, spelling: &str, factor: f64) -> Self { - self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: None }); + self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: None, rest: None }); self } /// Like [`Reader::unit`], with a `tag` that [`Reader::read_tagged`] returns when the text names this spelling. #[must_use] pub fn unit_tagged(mut self, spelling: &str, factor: f64, tag: u32) -> Self { - self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: Some(tag) }); + self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: Some(tag), rest: None }); + self + } + + /// Like [`Reader::unit_tagged`], where a number written right after the spelling adds that many of `rest`: picas + /// and points read as `2p6`, two picas and six points. + #[must_use] + pub fn split_unit(mut self, spelling: &str, factor: f64, rest: f64, tag: u32) -> Self { + self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: Some(tag), rest: Some(rest) }); self } @@ -105,6 +130,16 @@ impl Reader { }; (parse.at == chars.len() && value.is_finite()).then_some((value, parse.tag)).ok_or(NotAValue) } + + /// The fraction a lone percentage writes (`50%` is 0.5): a number and `%`, with no sign, unit or operator; + /// `None` for any other text. + pub fn share(&self, text: &str) -> Option { + let chars: Vec = text.chars().filter(|c| !c.is_whitespace()).collect(); + let number = chars.strip_suffix(&['%'])?; + let mut parse = Parse { reader: self, chars: number, at: 0, tag: None }; + let value = parse.number().ok()?; + (parse.at == number.len()).then_some(value / 100.0) + } } struct Parse<'a> { @@ -141,29 +176,32 @@ impl Parse<'_> { } fn term(&mut self) -> Result { - let first = self.factor()?; + let first = self.factor(true)?; self.product(first) } fn product(&mut self, mut left: f64) -> Result { // A bare relative `+5` has no product to run; the sum loop takes it. - while let Some(op @ ('*' | '/')) = self.peek() { + while let Some(op @ ('*' | '/' | 'x' | 'X' | '×')) = self.peek() { self.at += 1; - let right = self.factor()?; - left = if op == '*' { left * right } else { left / right }; + // A multiplier is a plain number: the reader's bare factor does not scale it. + let right = self.factor(false)?; + left = if op == '/' { left / right } else { left * right }; } Ok(left) } - fn factor(&mut self) -> Result { + /// A factor; `scaled` says it starts a term, where a number with no unit counts as the reader's bare factor. + /// Otherwise it is a multiplier, which may be a percentage. + fn factor(&mut self, scaled: bool) -> Result { match self.peek() { Some('-') => { self.at += 1; - self.factor().map(|value| -value) + self.factor(scaled).map(|value| -value) } Some('+') => { self.at += 1; - self.factor() + self.factor(scaled) } Some('(') => { self.at += 1; @@ -171,22 +209,43 @@ impl Parse<'_> { (self.peek() == Some(')')).then(|| self.at += 1).ok_or(NotAValue)?; Ok(value) } - _ => self.quantity(), + _ => self.quantity(scaled), } } - fn quantity(&mut self) -> Result { + /// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no + /// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it. + fn quantity(&mut self, scaled: bool) -> Result { let number = self.number()?; self.tag = None; - let rest: String = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect(); - if rest.is_empty() { - return Ok(number); + if !scaled && self.peek() == Some('%') { + self.at += 1; + return Ok(number / 100.0); } - let lowered = rest.to_lowercase(); - let unit = self.reader.units.iter().find(|unit| unit.spelling == lowered).ok_or(NotAValue)?; - self.at += rest.chars().count(); - self.tag = unit.tag; - Ok(number * unit.factor) + let reader = self.reader; + let run: Vec = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect(); + let unit = (1..=run.len()).rev().find_map(|len| { + let lowered = run[..len].iter().collect::().to_lowercase(); + reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit)) + }); + match unit { + Some((len, unit)) => { + self.at += len; + self.tag = unit.tag; + let rest = match unit.rest { + Some(rest) if self.peek().is_some_and(|c| digit(c).is_some() || c == reader.decimal) => rest * self.number()?, + _ => 0.0, + }; + Ok(number * unit.factor + rest) + } + None if scaled => Ok(number * reader.bare), + None => Ok(number), + } + } + + /// Whether the group separator at `at` is followed by exactly three digits. + fn three_digits_after(&self, at: usize) -> bool { + self.chars[at + 1..].iter().take_while(|c| digit(**c).is_some()).count() == 3 } fn number(&mut self) -> Result { @@ -198,7 +257,7 @@ impl Parse<'_> { } else if c == self.reader.decimal && !seen_decimal { seen_decimal = true; text.push('.'); - } else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() { + } else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() && self.three_digits_after(self.at) { } else { break; } @@ -226,13 +285,52 @@ mod tests { assert_eq!(reader.read("+5", Some(10.0)), Ok(15.0)); assert_eq!(reader.read("*2", Some(10.0)), Ok(20.0)); assert_eq!(reader.read("٣٤", None), Ok(34.0), "Arabic-Indic digits"); - let symbols = Reader::new().unit("%", 1.0).unit("°", 1.0).unit("×", 1.0); + let symbols = Reader::new().unit("%", 1.0).unit("°", 1.0); assert_eq!(symbols.read("12 %", None), Ok(12.0), "a symbol spelling after a space"); assert_eq!(symbols.read("12°", None), Ok(12.0)); - assert_eq!(symbols.read("1.5×", None), Ok(1.5)); + assert_eq!(symbols.read("1.5×2", None), Ok(3.0), "× is the product sign"); assert_eq!(symbols.read("10%+5%", None), Ok(15.0), "a symbol ends where the next operator starts"); for bad in ["", "abc", "1 +", "2px", "1/0", "(1"] { assert_eq!(reader.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value"); } } + + #[test] + fn times_signs_and_bare_numbers_read_through_the_grammar() { + let near = |reader: &Reader, text: &str, want: f64| { + let got = reader.read(text, None).unwrap_or(f64::NAN); + assert!((got - want).abs() < 1e-9, "{text:?} read {got}, wanted {want}"); + }; + let lengths = Reader::new().unit("px", 1.0).unit("in", 72.0); + for sign in ["x", "X", "×", "*"] { + near(&lengths, &format!("2{sign}3"), 6.0); + } + near(&lengths, "2inx3", 432.0); + near(&lengths, "2px", 2.0); + near(&lengths, "2px×2", 4.0); + + let picas = Reader::new().bare(1.0 / 12.0).unit("pt", 1.0 / 12.0).unit("pc", 1.0); + near(&picas, "12", 1.0); + near(&picas, "1pt+12", 13.0 / 12.0); + near(&picas, "1pc+12", 2.0); + near(&picas, "12*2", 2.0); + + let split = Reader::new().bare(1.0 / 12.0).split_unit("p", 1.0, 1.0 / 12.0, 0); + near(&split, "2p6", 2.5); + near(&split, "-2p6", -2.5); + near(&split, "2p", 2.0); + + let percent = Reader::new().unit("cm", 1.0).unit("%", 7.0); + near(&percent, "3cm*50%", 1.5); + near(&percent, "3cm/50%", 6.0); + near(&percent, "2%", 14.0); + assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share"); + + let german = Reader::new().decimal(',').group('.'); + near(&german, "1.234,5", 1234.5); + near(&german, "1.234.567", 1_234_567.0); + for bad in ["1.2", "1.2345", "×3", "x3"] { + assert_eq!(german.read(bad, None), Err(NotAValue), "{bad:?} is not a value"); + } + } } diff --git a/crates/behavior/src/sense.rs b/crates/behavior/src/sense.rs index 077310f662..c64efa2fbd 100644 --- a/crates/behavior/src/sense.rs +++ b/crates/behavior/src/sense.rs @@ -30,7 +30,8 @@ bitflags! { /// The zoom share (Ctrl or Cmd with the wheel, pinch), taken without scroll; the split rule passes both scroll shares on. const WHEEL_ZOOM = 1024; /// A secondary press captures the part and its release is reported to it, so a part that senses only a click - /// still gets its context click. Without this bit a secondary press only captures for a drag. + /// still gets its context click, and one that drags drags with the secondary button too. Without this bit the + /// shape takes no secondary press: it goes to the next shape under it that senses this bit. const CONTEXT_CLICK = 2048; /// A container root learns of a primary press on its own surface: inside its rect, on its layer, where no /// shape takes the press. The root takes no press and no focus by it, so it is no click target. @@ -50,6 +51,10 @@ bitflags! { /// with `DRAG` by a part whose click does nothing a drag could be mistaken for (a transform box's handles). /// The component begins the gesture from `PressPhase::Held`. const FOLLOWS_IN_SLOP = 65536; + /// A press on this shape that moves past slop is not the shape's: the press passes to the shape ranked under + /// it that senses a drag, with its start. Released within slop it is the shape's click. Declared with `CLICK`, + /// without `DRAG`. + const PASSES_DRAG = 131072; } } diff --git a/crates/behavior/src/typing.rs b/crates/behavior/src/typing.rs index 00d7d228e3..c95fe4c8c5 100644 --- a/crates/behavior/src/typing.rs +++ b/crates/behavior/src/typing.rs @@ -238,4 +238,22 @@ mod tests { typing.edit(&mut run, &Some(5.0), "9"); assert_eq!(typing.escape(&mut run), Escaped::Restore(Some(5.0))); } + + /// A field's value can change under a half-typed draft (a panel's selection changes): the draft and the value the + /// run began from must stay, so the commit and Escape work from what the user started typing over. + #[test] + fn a_draft_survives_an_outside_value_change_until_commit() { + let typing = TypingRun::new(NumberCodec::default()); + let (began, outside) = (Some(12.0), Some(24.0)); + let mut run = EditRun::new(began); + typing.edit(&mut run, &began, "+"); + typing.edit(&mut run, &outside, "+6"); + assert_eq!(typing.shown(&run, &outside), "+6", "the open draft is shown, not the value that changed under it"); + assert_eq!(run.start, began, "the run keeps the value it began from"); + assert_eq!(typing.commit(&mut run), Ended::Commit(Some(18.0)), "relative input applies to the value the run began from"); + + typing.edit(&mut run, &began, "9"); + typing.edit(&mut run, &outside, "90"); + assert_eq!(typing.escape(&mut run), Escaped::Restore(began), "Escape restores the value from before the run"); + } } diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 625f684bbd..1985e4bf9c 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -86,6 +86,135 @@ pub struct Wheel { pub rotation: f32, /// Rotation of a two-finger touch, in radians. pub touch_rotation: f32, + /// Two fingers' movement this pass, in points. + pub touch_pan: Vec2, + /// The running gesture's scroll gathered so far, this share included, in its owner's points. + pub gathered: Vec2, + /// Whether the owner marked the running gesture moved (`Pointer::mark_wheel_moved`). + pub moved: bool, +} + +/// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct WheelEase { + owed: kurbo::Vec2, + burst: u32, + last_notch: f64, + last_sign: Vec2, + last_paid: f64, +} + +/// Notches closer than this many seconds are a fast spin and grow the burst. +const FAST_NOTCH: f64 = 0.08; +/// Notches this many seconds apart, or more, start a new burst. +const BURST_RESET: f64 = 0.3; +/// The multiplier one fast notch adds. +const BURST_STEP: f32 = 0.4; +/// The burst notches that count toward the multiplier. +const BURST_TICKS: u32 = 13; +/// Notches kept past `BURST_TICKS`, so a few slower notches in a spin do not drop the multiplier at once. +const BURST_HOLD: u32 = 4; +/// The largest multiplier. +const BURST_CAP: f32 = 6.0; +/// The most motion owed on an axis, in points: a hostile run of notches cannot grow it without bound. +const MAX_OWED: f32 = 16384.0; +/// The longest pass the ease pays for, in seconds: after a stall it does not jump the whole way at once. +const LONGEST_PASS: f64 = 0.1; +/// The seconds a pass is taken to last when the ease starts from rest, so the first notch moves in its own pass. +const FIRST_PASS: f64 = 1.0 / 60.0; +/// Owed motion this small, in points, is paid whole. +const SETTLE: f32 = 0.01; + +/// The sign of `v`: 0 for zero, where `f32::signum` gives 1. +fn sign(v: f32) -> f32 { + if v > 0.0 { + 1.0 + } else if v < 0.0 { + -1.0 + } else { + 0.0 + } +} + +impl WheelEase { + /// Adds the line pan `pan` of this pass, at time `now`, to the owed motion; a burst of notches under 0.08 s apart + /// accelerates it, a reversal or 0.3 s idle resets the burst. + pub fn feed(&mut self, pan: Vec2, now: f64) { + if !now.is_finite() || !pan.is_finite() || pan == Vec2::ZERO { + return; + } + let signs = Vec2::new(sign(pan.x), sign(pan.y)); + let idle = now - self.last_notch; + let reversed = signs.x * self.last_sign.x < 0.0 || signs.y * self.last_sign.y < 0.0; + if self.last_sign == Vec2::ZERO || !(0.0..BURST_RESET).contains(&idle) || reversed { + self.burst = 0; + } else if idle < FAST_NOTCH { + self.burst = (self.burst + 1).min(BURST_TICKS + BURST_HOLD); + } else { + // A slower notch in the same direction sheds one, rather than extending the burst. + self.burst = self.burst.saturating_sub(1); + } + self.last_notch = now; + self.last_sign = signs; + let boost = (1.0 + BURST_STEP * self.burst.min(BURST_TICKS) as f32).min(BURST_CAP); + if !self.owes() { + self.last_paid = now - FIRST_PASS; + } + self.owed = kurbo::Vec2::new(owe(self.owed.x, f64::from(pan.x * boost)), owe(self.owed.y, f64::from(pan.y * boost))); + } + + /// Drops the owed motion on the axes marked. + pub fn cancel_axis(&mut self, x: bool, y: bool) { + if x { + self.owed.x = 0.0; + } + if y { + self.owed.y = 0.0; + } + } + + /// The step this pass pays at time `now`: `1 − 0.1^(dt/0.1)` of the owed motion, with `dt` since the last paid pass. + pub fn step(&mut self, now: f64) -> Vec2 { + if !now.is_finite() || now < self.last_paid { + // A clock that runs backwards or breaks cannot tell how much to pay: the tail goes. + self.owed = kurbo::Vec2::ZERO; + self.last_paid = if now.is_finite() { now } else { self.last_paid }; + return Vec2::ZERO; + } + let dt = (now - self.last_paid).min(LONGEST_PASS); + self.last_paid = now; + if !self.owes() || dt <= 0.0 { + return Vec2::ZERO; + } + let fraction = 1.0 - 0.1_f64.powf(dt / 0.1); + let paid = Vec2::new(pay(self.owed.x, fraction), pay(self.owed.y, fraction)); + self.owed -= kurbo::Vec2::new(f64::from(paid.x), f64::from(paid.y)); + // A tail below normal f32 precision cannot move a view and must not keep scheduling frames. + if self.owed.x.abs() < f64::from(f32::MIN_POSITIVE) { + self.owed.x = 0.0; + } + if self.owed.y.abs() < f64::from(f32::MIN_POSITIVE) { + self.owed.y = 0.0; + } + paid + } + + /// Whether motion is still owed. + pub fn owes(&self) -> bool { + self.owed != kurbo::Vec2::ZERO + } +} + +/// `owed` with `more` added on one axis: motion the other way drops what was owed, and the sum stays within +/// `MAX_OWED`. +fn owe(owed: f64, more: f64) -> f64 { + let owed = if more * owed < 0.0 { 0.0 } else { owed }; + (owed + more).clamp(-f64::from(MAX_OWED), f64::from(MAX_OWED)) +} + +/// The part of `owed` one pass pays, `fraction` of it; a remainder under `SETTLE` is paid whole. +fn pay(owed: f64, fraction: f64) -> f32 { + if owed.abs() <= f64::from(SETTLE) { owed as f32 } else { (owed * fraction) as f32 } } impl Wheel { @@ -104,6 +233,9 @@ impl Wheel { touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, + touch_pan: Vec2::ZERO, + gathered: Vec2::ZERO, + moved: false, } } @@ -131,6 +263,13 @@ impl Wheel { self } + /// The same gesture with the two-finger touch movement `pan`, in points. + #[must_use] + pub const fn touch_pan(mut self, pan: Vec2) -> Self { + self.touch_pan = pan; + self + } + /// The same gesture from `source`. pub const fn source(mut self, source: WheelSource) -> Self { self.source = source; @@ -422,15 +561,15 @@ fn for_field(wheel: &Wheel) -> bool { !(mods.alt || mods.cmd || mods.ctrl) && (wheel.scroll.y != 0.0 || (mods.shift && wheel.scroll.x != 0.0)) } -/// Whether `wheel` carries a pinch, a touch zoom or a rotation: the zoom share's values. +/// Whether `wheel` carries a pinch, a touch zoom, a rotation or a two-finger pan: the zoom share's values. fn pinches(wheel: &Wheel) -> bool { - wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 + wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 || wheel.touch_pan != Vec2::ZERO } /// `wheel` without the zoom share's values: a scroll share carries no pinch or rotation, so a field or a scroll region /// never reads one. const fn scroll_only(wheel: Wheel) -> Wheel { - Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, zooms: false, ..wheel } + Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, zooms: false, ..wheel } } /// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes @@ -579,6 +718,7 @@ fn split_at( share.touch_zoom *= part.touch_zoom; share.rotation += part.rotation; share.touch_rotation += part.touch_rotation; + share.touch_pan += part.touch_pan; share.zooms |= part.zooms; } None => shares.push((owner, part)), @@ -647,4 +787,39 @@ mod tests { let shares = split(&[region, view, zone], at, wheel(4.0, 0.0), WheelFocus::new(None), None, &mut WheelGesture::default(), 0.0); assert_eq!(shares.iter().map(|(o, w)| (*o, w.zooms)).collect::>(), [(2, false)], "the horizontal share passes the zone"); } + + #[test] + fn fast_notches_accelerate_to_a_cap_and_reset_on_reversal_or_idle_but_a_lone_notch_does_not() { + const NOTCH: f64 = 40.0; + // What one notch of `y` points adds to the owed motion. + let notch = |ease: &mut WheelEase, y: f64, now: f64| { + let before = ease.owed.y; + ease.feed(Vec2::new(0.0, y as f32), now); + ease.owed.y - before + }; + let mut ease = WheelEase::default(); + assert_eq!(notch(&mut ease, NOTCH, 1.0), NOTCH, "a lone notch is one notch"); + assert_eq!(notch(&mut ease, NOTCH, 1.5), NOTCH, "a slow notch is one notch"); + + let mut gains = Vec::new(); + for i in 1..=20 { + gains.push(notch(&mut ease, NOTCH, 1.5 + f64::from(i) * 0.02)); + } + // The owed sum rounds in its last bits, so per-notch gains compare within a hundredth of a point. + let near = |a: f64, b: f64| (a - b).abs() < 0.01; + assert!(gains.windows(2).all(|pair| pair[1] > pair[0] - 0.01), "a fast run never pays less per notch: {gains:?}"); + let fastest = gains.iter().copied().fold(0.0, f64::max); + assert!(fastest > 2.0 * NOTCH, "a fast run accelerates: {gains:?}"); + assert!(fastest < 6.0 * NOTCH + 0.01, "the acceleration is capped: {gains:?}"); + assert!(gains.last().is_some_and(|&last| near(last, 6.0 * NOTCH)), "a long run reaches the cap and stays there: {gains:?}"); + + notch(&mut ease, -NOTCH, 1.5 + 21.0 * 0.02); + assert_eq!(ease.owed.y, -NOTCH, "a reversal drops what was owed and starts again at one notch"); + + for i in 1..=10 { + notch(&mut ease, -NOTCH, 2.0 + f64::from(i) * 0.02); + } + assert!(notch(&mut ease, -NOTCH, 2.0 + 11.0 * 0.02) < -NOTCH - 1.0, "precondition: the run is fast again"); + assert!(near(notch(&mut ease, -NOTCH, 5.0), -NOTCH), "an idle gap starts again at one notch"); + } } diff --git a/crates/behavior/tests/canvas_view.rs b/crates/behavior/tests/canvas_view.rs index 2da0b59c99..2b71090371 100644 --- a/crates/behavior/tests/canvas_view.rs +++ b/crates/behavior/tests/canvas_view.rs @@ -1,7 +1,7 @@ //! The canvas view's mapping between document and screen. use craft_behavior::CanvasView; -use craft_behavior::canvas::zoom; +use craft_behavior::canvas::{ZoomScheme, zoom}; use emath::{Rect as ScreenRect, pos2, vec2}; use kurbo::{Point, Rect, Size}; @@ -55,22 +55,44 @@ fn fit_and_fill_measure_the_stretched_document() { // Fit keeps 20 points of margin per side: 1000 points across for a 1000 px wide document, 2000 shown at aspect 2. let (mut square, mut wide) = (stage(1.0, rect(1040.0, 800.0)), stage(2.0, rect(1040.0, 800.0))); - zoom::fit(&mut square, size, 1.0, 20.0); - zoom::fit(&mut wide, size, 1.0, 20.0); + zoom::fit(&mut square, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); + zoom::fit(&mut wide, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 1.0), "{}", square.zoom); assert!(near(wide.zoom, 0.5), "{}", wide.zoom); assert!(near(wide.center.x, 500.0) && near(wide.center.y, 250.0), "{:?}", wide.center); // On a square rect the height limits fill at both aspects; the 1000 by 400 rect below is where the stretched width decides. let (mut square, mut wide) = (stage(1.0, rect(1000.0, 1000.0)), stage(2.0, rect(1000.0, 1000.0))); - zoom::fill(&mut square, size, 1.0); - zoom::fill(&mut wide, size, 1.0); + zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); + zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 2.0) && near(wide.zoom, 2.0), "{} {}", square.zoom, wide.zoom); // A wide rect: the unstretched document is limited by its width, the stretched one by its height. let (mut square, mut wide) = (stage(1.0, rect(1000.0, 400.0)), stage(2.0, rect(1000.0, 400.0))); - zoom::fill(&mut square, size, 1.0); - zoom::fill(&mut wide, size, 1.0); + zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); + zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 1.0), "{}", square.zoom); assert!(near(wide.zoom, 0.8), "{}", wide.zoom); assert!(near(wide.center.x, 500.0) && near(wide.center.y, 250.0), "{:?}", wide.center); } + +#[test] +fn a_scheme_steps_and_clamps_in_its_own_units_about_its_hundred() { + let (small, big) = (Size::new(100.0, 100.0), Size::new(10_000.0, 10_000.0)); + + let illustrator = ZoomScheme::ILLUSTRATOR; + let up = illustrator.step(1.0, 1, big); + assert!(near(up, 1.5), "{up}"); + assert!(near(illustrator.step(up, -1, big), 1.0), "a step in then out returns to the rung"); + assert!(near(illustrator.min(small), 0.0313) && near(illustrator.min(big), 0.0313), "a fixed floor ignores the document"); + + let photoshop = ZoomScheme::PHOTOSHOP; + assert!(near(photoshop.min(small), 0.02), "{}", photoshop.min(small)); + assert!(photoshop.min(big) < photoshop.min(small), "the floor follows the shorter side"); + + let doubled = photoshop.with_hundred(2.0); + for device in [0.5, 3.0, 40.0] { + assert!(near(doubled.device(doubled.percent(device)), device), "{device}"); + } + assert!(near(doubled.step(2.0, 1, small), 4.0), "the rung after the scheme's 100 % is the next rung times it"); + assert!(near(photoshop.clamp(f64::NAN, small), 1.0) && near(doubled.clamp(f64::NAN, small), 2.0), "a non-finite zoom is 100 %"); +} diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index b3bad10d0e..1d25354fdc 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -439,6 +439,63 @@ fn a_panel_that_docks_only_in_columns_never_lands_in_a_frame() { assert_eq!(sorted(saved.layout()), [1, 2, 3, 4, 6]); } +/// A location whose anchor, sibling and tab-before name `anchor`. +fn recorded(layout: &Layout, anchor: u32) -> craft_behavior::dock::Location { + let mut location = layout.location(&5).unwrap(); + location.anchor = Some(anchor); + location.sibling = vec![anchor]; + location.placement = DockPlacement::tab(Some(anchor)); + location +} + +/// Every place of `workspace` that holds the panel `id`: the layout, the keys of the records and their locations. +fn mentions(workspace: &Workspace, id: u32) -> bool { + let records = workspace.hidden().iter().chain(workspace.floated()); + let named = records.clone().any(|(panel, location)| { + let before = matches!(&location.placement, DockPlacement::Tab { before: Some(p) } if *p == id); + *panel == id || location.anchor == Some(id) || location.sibling.contains(&id) || before + }); + named || workspace.layout().contains(&id) +} + +/// A rename keeps the panel's place wherever the id sits (tab group, dock column, floating window, records and the +/// anchors of other records), refuses a missing source and a taken name, and leaves the workspace as it was then. +#[test] +fn a_renamed_panel_keeps_its_place_and_a_taken_name_changes_nothing() { + for from in [11, 3, 7, 50, 51] { + let layout = docked(); + let mut base = Workspace::default(); + base.replace(Workspace::from_parts( + layout.clone(), + vec![(50, recorded(&layout, from)), (52, recorded(&layout, 5))], + vec![(51, recorded(&layout, from))], + )); + base.validate().unwrap(); + let swap = |panel: u32| if panel == from { 99 } else { panel }; + + let mut renamed = base.clone(); + let (revision, generation) = (renamed.revision(), renamed.generation()); + renamed.rename(&from, 99).unwrap_or_else(|e| panic!("{from}: {e:?}")); + let panels = |workspace: &Workspace| workspace.layout().panels().into_iter().copied().collect::>(); + assert_eq!(panels(&renamed), panels(&base).into_iter().map(swap).collect::>(), "{from}: the panel keeps its position"); + let keys = |records: &[(u32, _)]| records.iter().map(|(panel, _)| *panel).collect::>(); + assert_eq!(keys(renamed.hidden()), keys(base.hidden()).into_iter().map(swap).collect::>(), "{from}: hidden keys"); + assert_eq!(keys(renamed.floated()), keys(base.floated()).into_iter().map(swap).collect::>(), "{from}: floated keys"); + assert!(!mentions(&renamed, from) && mentions(&renamed, 99), "{from}: no field holds the old id"); + renamed.validate().unwrap(); + assert!(renamed.revision() != revision && renamed.generation() == generation, "{from}: a rename is an edit"); + + for (source, name, error) in [(40, 99, DockError::MissingPanel), (from, 4, DockError::DuplicatePanel), (from, 52, DockError::DuplicatePanel)] + { + let mut refused = base.clone(); + let revision = refused.revision(); + assert_eq!(refused.rename(&source, name), Err(error), "{from}: {source} to {name}"); + assert_eq!(refused, base, "{from}: a refused rename changes nothing"); + assert_eq!(refused.revision(), revision); + } + } +} + /// A stepped column (a toolbar's) keeps its step count docked, floating and through JSON, and its width moves only /// by steps. #[test] @@ -494,6 +551,7 @@ fn every_workspace_mutator_moves_the_revision() { moves("set_visible", &|workspace| workspace.set_visible(5, false, None, false, allow).unwrap()); moves("reconcile", &|workspace| workspace.reconcile(|panel| *panel != 5, allow, &Workspace::new(docked()))); moves("raise_window_floor", &|workspace| workspace.raise_window_floor(1000)); + moves("rename", &|workspace| workspace.rename(&5, 99).unwrap()); moves("forget_hidden", &|workspace| { workspace.apply(Action::close(5), false, allow).unwrap(); let revision = workspace.revision(); diff --git a/crates/behavior/tests/geometry/move_gesture.rs b/crates/behavior/tests/geometry/move_gesture.rs index 074de32669..029106960e 100644 --- a/crates/behavior/tests/geometry/move_gesture.rs +++ b/crates/behavior/tests/geometry/move_gesture.rs @@ -1,7 +1,8 @@ //! The direction lock of the move gesture. -use craft_behavior::geometry::{Directions, lock_direction}; -use kurbo::Vec2; +use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, lock_direction}; +use craft_keymap::Mods; +use kurbo::{Point, Vec2}; fn polar(deg: f64, len: f64) -> Vec2 { let a = deg.to_radians(); @@ -19,3 +20,16 @@ fn lock_direction_keeps_the_axis_until_eight_degrees_past_half() { let switched = lock_direction(polar(31.0, 10.0), Some(axis), Directions::Eight); assert!((switched.y - switched.x).abs() < 1e-9 && switched.y > 0.0); } + +#[test] +fn a_shift_move_with_four_directions_locks_an_axis_and_frees_it_when_shift_is_let_go() { + let mut drag = MoveGesture::press(&ConstrainStyle::new(4.0, 4.0), Point::ZERO, Mods::SHIFT, Directions::Four); + let at = Point::new(10.0, 3.0); + let locked = drag.follow(at, Mods::SHIFT, 1.0).expect("the move changed the value"); + assert_eq!(locked.delta.y, 0.0, "Shift holds the offset to the horizontal axis: {:?}", locked.delta); + assert!(locked.delta.x > 0.0, "{:?}", locked.delta); + assert!(drag.locked().is_some(), "the lock is remembered while Shift is down"); + let free = drag.follow(at, Mods::NONE, 1.0).expect("letting Shift go changed the value"); + assert_eq!(free.delta, Vec2::new(10.0, 3.0), "without Shift the offset is free"); + assert_eq!(drag.locked(), None, "the lock is forgotten when Shift is let go"); +} diff --git a/crates/behavior/tests/geometry/quad.rs b/crates/behavior/tests/geometry/quad.rs index e716f2511d..2350de7957 100644 --- a/crates/behavior/tests/geometry/quad.rs +++ b/crates/behavior/tests/geometry/quad.rs @@ -13,6 +13,18 @@ fn session() -> BoxState { BoxState::from_rect(Rect::new(0.0, 0.0, 100.0, 50.0)) } +#[test] +fn corner_drag_preserves_the_offset_of_the_press() { + let start = session(); + let press = p(96.0, 47.0); + let rules = BoxRules::default(); + let back = drag(&start, &start, BoxPart::Corner(2), press, press, Mods::default(), &rules); + assert_eq!(back, start, "returning to the press must restore the box"); + let moved = drag(&start, &start, BoxPart::Corner(2), press, press + Vec2::new(20.0, 10.0), Mods::SHIFT, &rules); + assert!(near(moved.quad[2], start.quad[2] + Vec2::new(20.0, 10.0)), "the corner follows the movement, keeping the press offset"); + assert!(near(moved.quad[0], start.quad[0]), "the opposite corner stays fixed"); +} + fn dragged(from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState { let start = session(); drag(&start, &start, start.part_at(from, 8.0), from, to, mods, rules) @@ -31,6 +43,15 @@ fn turns(q: &[Point; 4]) -> [f64; 4] { std::array::from_fn(|k| (q[(k + 1) % 4] - q[k]).cross(q[(k + 2) % 4] - q[(k + 1) % 4])) } +#[test] +fn proportional_corner_uses_the_larger_relative_drag_even_when_shrinking() { + let rules = BoxRules::default().with_scale(ScaleRule::LargerAxis); + let wider = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::NONE, &rules); + assert!(corners_are(&wider, 0.0, 0.0, 200.0, 100.0)); + let smaller = dragged(p(100.0, 50.0), p(75.0, 50.0), Mods::NONE, &rules); + assert!(corners_are(&smaller, 0.0, 0.0, 75.0, 37.5)); +} + #[test] fn a_proportional_corner_follows_the_diagonal_and_flips_past_the_anchor() { let rules = BoxRules::default(); diff --git a/crates/behavior/tests/hit_excluding.rs b/crates/behavior/tests/hit_excluding.rs new file mode 100644 index 0000000000..aea0f1f910 --- /dev/null +++ b/crates/behavior/tests/hit_excluding.rs @@ -0,0 +1,16 @@ +//! A hit shape with discs cut out: a point in a hole misses where the shape alone hits. + +use craft_behavior::HitShape; +use emath::{Pos2, Rect, pos2}; + +#[test] +fn a_point_inside_a_hole_misses_and_one_beside_it_hits() { + let shape = HitShape::Rect(Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0))); + let hole = (pos2(10.0, 10.0), 5.0); + let cut = HitShape::excluding(shape.clone(), vec![hole]); + let (inside, beside): (Pos2, Pos2) = (pos2(12.0, 10.0), pos2(50.0, 50.0)); + assert!(shape.hit(inside), "the shape alone takes the point the hole covers"); + assert!(!cut.hit(inside), "a point in a hole misses"); + assert!(cut.hit(beside), "a point outside every hole still hits"); + assert_eq!(cut.bounds(), shape.bounds(), "the holes leave the bounds as they are"); +} diff --git a/crates/behavior/tests/main.rs b/crates/behavior/tests/main.rs index dfa1e77c9a..c52c1045ec 100644 --- a/crates/behavior/tests/main.rs +++ b/crates/behavior/tests/main.rs @@ -8,4 +8,6 @@ mod dock_apply; mod fit; #[path = "geometry/main.rs"] mod geometry; +mod hit_excluding; mod key_table; +mod middle_scroll; diff --git a/crates/behavior/tests/middle_scroll.rs b/crates/behavior/tests/middle_scroll.rs new file mode 100644 index 0000000000..e43423fe41 --- /dev/null +++ b/crates/behavior/tests/middle_scroll.rs @@ -0,0 +1,77 @@ +//! The middle button's auto-scroll latch. + +use craft_behavior::{MiddleScroll, PointerButton, PressCancel, PressPhase, PressStart}; +use emath::{Vec2, pos2}; + +/// One frame's elapsed time. +const FRAME: f64 = 1.0 / 60.0; + +/// A click keeps the latch, as does a hold of one frame even when that frame runs a second pass; a hold of two frames +/// past the dead zone ends it on release. +#[test] +fn a_click_inside_the_dead_zone_latches_and_a_hold_past_it_ends_on_release() { + let anchor = pos2(100.0, 100.0); + let past = pos2(100.0, 140.0); + + let mut latch = MiddleScroll::default(); + latch.press(anchor, true); + assert_eq!(latch.step(pos2(100.0, 105.0), true, FRAME, false), Vec2::ZERO, "inside the dead zone nothing scrolls"); + latch.release(); + assert!(latch.active(), "a click latches"); + assert_eq!(latch.anchor(), Some(anchor)); + let scroll = latch.step(past, false, FRAME, false); + assert!(scroll.y < 0.0 && scroll.x == 0.0, "past the dead zone below the anchor the view scrolls down: {scroll:?}"); + latch.step(past, false, FRAME, false); + latch.release(); + assert!(latch.active(), "passes with the button up count no hold"); + latch.press(anchor, true); + assert!(!latch.active(), "a second press ends the latch"); + assert_eq!(latch.anchor(), None); + + // One frame held past the dead zone, rerun as a second pass with no elapsed time. + latch.press(anchor, true); + latch.step(past, true, FRAME, false); + latch.step(past, true, 0.0, false); + latch.release(); + assert!(latch.active(), "one held frame is a click, however many passes it runs"); + + // A fresh latch starts its count over: one more held frame is still a click. + latch.press(anchor, true); + latch.press(anchor, true); + latch.step(past, true, FRAME, false); + latch.release(); + assert!(latch.active(), "the count starts over at each latch"); + + latch.press(anchor, true); + latch.press(anchor, true); + latch.step(past, true, FRAME, false); + latch.step(past, true, FRAME, false); + latch.release(); + assert!(!latch.active(), "a hold of two frames past the dead zone ends on release"); + assert_eq!(latch.anchor(), None); +} + +/// A primary click that ends the latch is swallowed from its press through its release; the next click is not. +#[test] +fn a_primary_click_that_ends_auto_scroll_is_swallowed_through_its_release() { + let at = pos2(100.0, 100.0); + let start = PressStart::new(at, PointerButton::Primary, 0.0, 1); + let down = PressPhase::Down { start }; + let held = PressPhase::Held { start, pos: at }; + let release = PressPhase::Release { start, pos: at, click: true }; + + let mut latch = MiddleScroll::default(); + latch.press(at, true); + assert!(latch.swallows(down), "the press that ends the latch is swallowed"); + assert!(!latch.active()); + assert!(latch.swallows(held), "its later phases are too"); + assert!(latch.swallows(release), "through its release"); + assert!(!latch.swallows(down), "the next click, with nothing latched, is not"); + assert!(!latch.swallows(held)); + assert!(!latch.swallows(release)); + + latch.press(at, true); + assert!(latch.swallows(down)); + assert!(latch.swallows(PressPhase::Cancel { start, reason: PressCancel::Escape })); + assert!(!latch.swallows(held), "a cancel ends the swallowed press"); +} diff --git a/crates/browse/src/links/mod.rs b/crates/browse/src/links/mod.rs index 0884e5e4d7..4d992a02ef 100644 --- a/crates/browse/src/links/mod.rs +++ b/crates/browse/src/links/mod.rs @@ -223,7 +223,7 @@ impl SearchRun { wake: Wake, ) -> Self { // filmcraft: crates/ui-egui/src/panels/media_dialogs.rs:146 (`link_media` ran `media.search` on the UI thread). - let queue = JobQueue::new(jobs, wake.clone(), QueueOptions { lanes: 1, name: "relink-search" }); + let queue = JobQueue::new(jobs, wake.clone(), QueueOptions { lanes: 1, name: "relink-search", ..QueueOptions::default() }); let updates = Arc::new(Mutex::new(Vec::new())); let cancel = Cancel::new(); let inbox = Arc::clone(&updates); diff --git a/crates/browse/src/ui/bin/free_view.rs b/crates/browse/src/ui/bin/free_view.rs index 9eddab3f5d..c8fdb826e7 100644 --- a/crates/browse/src/ui/bin/free_view.rs +++ b/crates/browse/src/ui/bin/free_view.rs @@ -67,7 +67,7 @@ where } for event in out.response.events { match event { - CollectionEvent::Selection(change) => events.push(BinEvent::Selection(change)), + CollectionEvent::Selection { change, .. } => events.push(BinEvent::Selection(change)), CollectionEvent::Activate(key) => events.push(open_event(model, key, mods.cmd, mods.shift || mods.alt)), CollectionEvent::ContextMenu(request) => events.push(BinEvent::ContextMenu(request)), CollectionEvent::Delete(keys) => events.push(BinEvent::Remove(keys)), diff --git a/crates/browse/src/ui/bin/icon.rs b/crates/browse/src/ui/bin/icon.rs index 9fde6bb1d1..118a11870d 100644 --- a/crates/browse/src/ui/bin/icon.rs +++ b/crates/browse/src/ui/bin/icon.rs @@ -11,7 +11,7 @@ use craft_ui::contract::{ use craft_ui::list::ThumbAspect; use craft_ui::primitives::ContentPainterCx; use craft_ui::primitives::textures::{Priority, TextureKey, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails}; -use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid, TilePartEvent}; +use craft_ui::tile_grid::{CaptionPlace, GridZoom, Tile, TileGrid, TilePartEvent}; use egui::{Rect, Ui}; use super::list::{drop_items, inside_any, item_of, open_event, rename_event, reorder_event, sort_entries, stack_event}; @@ -172,7 +172,7 @@ where .caption(CaptionPlace::Below) .detail_line() .aspect(ASPECT) - .zoom(state.settings.zoom as f32) + .zoom(GridZoom::Fixed(state.settings.zoom)) .rename(true) .deletable(true) .rows_stamp(stamp_of(state.shown.as_ref(), &state.search, state.settings.icon_sort.as_ref())) @@ -189,7 +189,7 @@ where } for event in out.response.events { match event { - CollectionEvent::Selection(change) => events.push(BinEvent::Selection(change)), + CollectionEvent::Selection { change, .. } => events.push(BinEvent::Selection(change)), CollectionEvent::Activate(key) => events.push(open_event(model, key, mods.cmd, mods.shift || mods.alt)), CollectionEvent::ContextMenu(request) => events.push(BinEvent::ContextMenu(request)), CollectionEvent::Delete(keys) => events.push(BinEvent::Remove(keys)), diff --git a/crates/browse/src/ui/bin/list.rs b/crates/browse/src/ui/bin/list.rs index 78c587f304..e0c5c9a4d7 100644 --- a/crates/browse/src/ui/bin/list.rs +++ b/crates/browse/src/ui/bin/list.rs @@ -179,7 +179,7 @@ where } for event in out.events { match event { - CollectionEvent::Selection(change) => events.push(BinEvent::Selection(change)), + CollectionEvent::Selection { change, .. } => events.push(BinEvent::Selection(change)), CollectionEvent::Activate(key) => events.push(open_event(model, key, mods.cmd, mods.shift || mods.alt)), CollectionEvent::ContextMenu(request) => events.push(BinEvent::ContextMenu(request)), CollectionEvent::Delete(keys) => events.push(BinEvent::Remove(keys)), diff --git a/crates/browse/src/ui/relink/dialog.rs b/crates/browse/src/ui/relink/dialog.rs index 348d84ec84..247d78a88f 100644 --- a/crates/browse/src/ui/relink/dialog.rs +++ b/crates/browse/src/ui/relink/dialog.rs @@ -634,7 +634,7 @@ impl Model { let ctx = ctx.clone(); Wake::new(move || ctx.request_repaint()) }; - let checks = JobQueue::new(Arc::clone(&jobs), wake.clone(), QueueOptions { lanes: 1, name: "relink-check" }); + let checks = JobQueue::new(Arc::clone(&jobs), wake.clone(), QueueOptions { lanes: 1, name: "relink-check", ..QueueOptions::default() }); self.runtime = Some(Runtime { jobs, wake, checks }); } self.poll_pick(); diff --git a/crates/browse/src/ui/relink/list.rs b/crates/browse/src/ui/relink/list.rs index fb046938d2..08b35fa15e 100644 --- a/crates/browse/src/ui/relink/list.rs +++ b/crates/browse/src/ui/relink/list.rs @@ -315,7 +315,7 @@ impl LinkList<'_, K> { .show_items(ui, &source, &mut |_, icx| link_row(&rows, source.shown[icx.at], icx.at)); for event in out.events { match event { - CollectionEvent::Selection(change) => events.borrow_mut().push(LinkListEvent::Selection(change)), + CollectionEvent::Selection { change, .. } => events.borrow_mut().push(LinkListEvent::Selection(change)), CollectionEvent::Activate(key) => events.borrow_mut().push(LinkListEvent::GoTo(key)), _ => {} } diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml new file mode 100644 index 0000000000..edeb8d72e2 --- /dev/null +++ b/crates/cdr/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "craft-cdr" +description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer. +synth = [] + +[dependencies] +crc32fast = "1.5" +flate2 = { version = "1", default-features = false, features = ["rust_backend"] } + +[dev-dependencies] +proptest = { workspace = true } +craft-cdr = { path = ".", features = ["synth"] } diff --git a/crates/cdr/LICENSE-kaitai.txt b/crates/cdr/LICENSE-kaitai.txt new file mode 100644 index 0000000000..296cf04d0e --- /dev/null +++ b/crates/cdr/LICENSE-kaitai.txt @@ -0,0 +1,33 @@ +The record layouts this crate reads are described in the Kaitai Struct +specification `coreldraw_cdr.ksy` +(https://github.com/kaitai-io/coreldraw_cdr.ksy, commit +9d8e2704b946961f5114115f1a488750a3c86ed0), which is published under the +license below. No part of that specification is copied into this crate; +`PROVENANCE.md` cites it by line. + +Some layouts are also taken from the fork of that specification by Zach Wolfe +(https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, commit +2189b68f07e0cafe9afec3dcf699ebc0342144c7), which is published under the same +license and copyright notice. + +MIT License + +Copyright (c) 2020 Kaitai team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md new file mode 100644 index 0000000000..7c3ddadbb5 --- /dev/null +++ b/crates/cdr/PROVENANCE.md @@ -0,0 +1,132 @@ +# Where each layout comes from + +The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and +`tests/it/provenance.rs` fails when a cited id has no row here. + +Sources: + +- **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`), + https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy +- **KF**: the fork of K by Zach Wolfe, `filestar/coreldraw_cdr.ksy`, branch `new_stuff`, under the same + MIT license and notice as K (`LICENSE-kaitai.txt`), + https://github.com/filestar/coreldraw_cdr.ksy/blob/2189b68f07e0cafe9afec3dcf699ebc0342144c7/coreldraw_cdr.ksy +- **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at + the same commit as K, + https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md + and https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/bin/cdr-unpk +- **Z**: the PKWARE ZIP specification, APPNOTE.TXT version 6.3.10, + https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE), + https://www.rfc-editor.org/rfc/rfc1951 +- **F**: the magic database of the `file` utility (BSD-2-Clause), + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff +- **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0, + https://pronom.nationalarchives.gov.uk/fmt/467.xml, + https://pronom.nationalarchives.gov.uk/fmt/466.xml and + https://pronom.nationalarchives.gov.uk/fmt/465.xml +- **G**: the reference pages for the BMP file header and the bitmap info header, + https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapfileheader and + https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader +- **S**: own inspection of the bytes of public sample files, checked against the picture each file + carries of its drawing where it has one (versions 2 and 4 to 25; files of versions 1 and 3 carry + none). The files come from: + - **TP**: https://telparia.com/fileFormatSamples/image/cdr/, by file name + - **LT**: https://git.libreoffice.org/libcdr-test at commit + `dafe4fe53d685d89df20a5c0bb18f318ccefb4a8`, `testset//` + - **UC**: https://svn.code.sf.net/p/uniconvertor/code/formats/CDR/testing%20base/ at revision + 434, by file name + - **TDF**: attachments to The Document Foundation's bug tracker, + https://bugs.documentfoundation.org/attachment.cgi?id= + - **NR**: Natural Resources Canada's tactile maps, + https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/approach-approch/cdr/banff_ap_en.cdr and + https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr + - **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name + - **CX**: the `.cmx` files of https://telparia.com/fileFormatSamples/image/cmx/, by file name. The + nine with 32-bit coordinates are `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, + `gold_bar.cmx`, `goldblue.cmx`, `PC.CMX`, `squares.cmx` and `thatch.cmx`; they carry no picture + of their drawing. +- **CN**: the `.cmx` notes of an MIT OR Apache-2.0 drawing program, which mark each layout + "confirmed" when the program's authors found it in sample files, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md. + The same program's `.cmx` reader at that commit, + 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 + +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; +listed so it can be checked against a file, with what the reader does when it is wrong). + +Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as +the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the +sample files they name. +The test inputs are the synthetic files that `src/synth.rs` builds from the rows below; no sample +file is committed. + +| Id | What the code relies on | Source | Status | +|---|---|---|---| +| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01 from the form type alone, whatever its `vrsn` chunk names, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) | +| R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec | +| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec | +| R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec | +| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700 | public-spec | +| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893 | public-spec | +| R7 | Angles: i16 tenths of a degree before version 6, else i32 millionths of a degree | K L2835-L2855 | public-spec | +| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834 | public-spec | +| R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec | +| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec | +| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) | +| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; a record of id 2 holds a property list laid out as R11's, and the reader takes the outline's color from it when it names a library color; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; KF L1225-L1249 (the id 2 record); S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them; the id 2 record: no sample names a library color in it, and a wrong guess changes only the outline's color) | +| R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample | +| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) | +| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec | +| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec | +| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) | +| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) | +| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. On a layer, group or object, bit 0x01 of byte 1 hides it and bit 0x10 of byte 0 locks it. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); KF L1831-L1866 (the hidden and lock bits); S: every grid layer of versions 14 to 25 in the sample files (631) carries byte 1 = 1, and 206 of the 927 of versions 7 to 13 do; desktop layers carry byte 1 = 0 except TDF 114901's [0, 1, 1]; the drawing layers with byte 1 = 1 (TDF 114901, NR `banff_ap_en.cdr` and `symbology_en.cdr`) also carry bit 0x08; of the group and object lists in the sample files, only one object of TDF 60491 (version 14) sets either bit, the lock bit; in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects; bit 0x10 is also the lock bit, so a locked guides layer without a `loda` reads as a grid) | +| R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec | +| R21 | Page size argument (19130): width and height | K L666-L672 | public-spec | +| R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample | +| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | S: argument 16000 in NR `ab_en_br.cdr` (9) and TDF 194220 (13); the `guid` chunk of TDF 123971 (7). Pictures do not show guidelines | sample | +| R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec | +| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec | +| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec | +| R75 | `DISP`, a chunk of the RIFF form itself, holds the picture of the drawing: 4 bytes, then a bitmap info header (its own length u32, width, height, planes u16, bit count u16, compression u32, image size, two resolutions, the colors used u32, the important colors), then the color table or color masks and the pixels, to the end of the chunk. A BMP file is that bitmap after a 14-byte file header: `BM`, the file length u32, 4 reserved bytes of 0 and the offset of the pixels u32. The color table holds the colors used, at most 2^bit count, or 2^bit count colors when that is 0 at 8 bits or fewer; compression 3 (valid at 16 and 32 bits) puts three u32 masks after the header, before the pixels. The plane count is 1, and the image size is 0 or the rows' size. Uncompressed pixels (compression 0 or 3) are one row for each line of the height, each the width times the bit count rounded up to whole 32-bit words. The reader takes only a `DISP` chunk whose 4 bytes are `08 00 00 00`, with a 40-byte header and compression 0 or 3, and refuses other header lengths and compressions | K L231, L280-L306; G (both pages); S: every RIFF file of versions 4 to 13 in TP, UC, LT, NR, DM and TDF (469 files) has one `DISP`, starting with the bytes `08 00 00 00` and a 40-byte header of 1 plane and 1, 4 or 8 bits, compression 0, a positive height and an image size equal to the rows' size, whose color table and rows fill the rest of the chunk; the files of version 3 (TP, 9) have none | public-spec (the 4 bytes and where the chunk lies: sample; bit counts above 8 and compression 3: unconfirmed, as no sample has one, and a wrong guess gives a picture that fails to decode) | +| R76 | The package holds the picture of the drawing as `metadata/thumbnails/thumbnail.bmp`, a BMP file, in versions 14 to 16, and as `previews/thumbnail.png`, a PNG file, from version 17; each page's picture is beside it (`page1.bmp`, `page1.png` ...) ; the package's RIFF stream has no `DISP` chunk | S: every package of versions 14 to 16 (62) and of 17 to 25 (231) in LT, TP and TDF | sample | +| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec | +| R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) | +| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) | +| R30 | Object type 0x25 (version 10 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; S: TDF 78250 (version 15) and UC `shapes_cdr10.cdr`, `shapes_cdr11.cdr`, `shapes_cdr12.cdr` and `shapes_x3.cdr` (versions 10 to 13), whose type bytes start where the counts put them; no sample before version 10 holds the type | public-spec (from version 10: sample) | +| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; PR fmt/465; F `riff` L786; S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | public-spec (pages and layers as R19 and R22: sample) | +| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | S: the rectangles, curves and text of TP `ARMYSTF1.CDR`, `DALI.CDR` and `FOX.CDR`, which come out whole | sample (ellipse 1 and bitmap 4: unconfirmed, as no sample holds them; a bitmap is left out with a warning) | +| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | K L851; S: the matrices of every version 3 file in TP, whose drawings come out whole | sample (envelope type 0x14: unconfirmed, as no sample holds one; it is not applied, with a warning) | +| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547 | public-spec | +| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; S: the outlines of the version 3 files in TP | public-spec (flag bit: sample; dash unit, and the join, where bytes 32 and 33 of some samples hold 2 and 2: unconfirmed, and a wrong guess changes only how corners, ends and dashes are drawn) | +| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; S: model 1 in TP `ARMYSTF1.CDR` (3) and DM `lion1.cdr` (4), model 0 in TP `ARROW5.CDR` (3) and `WI.CDR` (1) | sample (ink 1, and models other than 0 and 1: unconfirmed; an ink of another number opens as a spot color without a look) | +| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | sample | +| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756 | public-spec | +| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 1, 2 and 4, 0 in the others), where K reads the two as one u32 | S: TP `DALI.CDR` (3), DM `headup.cdr` and `lion1.cdr` (4), TP `WI.CDR` (1), `FLAG.CDR` and `MENU.CDR` (2) | sample | +| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings, the start and the end of the object records, the start of the trailer and that value minus two. Version 1 has the marker `e` and its settings start at byte 28. Version 2 has the marker `m` or `l`, and its settings start after a 1-bit picture of the drawing, whose header starts where the u32 at byte 28 says. The reader takes these three markers | F `images` L4159-L4172; PR fmt/467, fmt/466; S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`), `MENU.CDR` and `DRINKS.CDR` (`l`) | public-spec (markers `e` and `m`: F and PR; the offsets and the marker `l`: sample) | +| R41 | The page's box in a file of version 1 or 2: four i16 two bytes after the start of the settings (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | S: TP `WI.CDR`, `FLAG.CDR` and `MENU.CDR` | sample | +| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample | +| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | +| R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | +| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u16 before version 6, u32 from it). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables; argument 200 is 2 bytes on all 844 objects of versions 4 and 5 in the sample files that carry it, and 4 bytes on all 18 of version 6 | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | +| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32, a u16 before version 6) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | +| R47 | Argument 8000 marks an object seen through: a lens or a transparency. From version 13 it holds records of a u32 version, a u32 length and a body; a body of version 1300 that is 117 bytes long holds an f64 at byte 61 and a merge mode byte at byte 77, which the reader applies as a uniform transparency. VectorCraft reads the f64 as the transparency in percent (0 opaque, 100 clear) and maps the merge modes 0 normal, 9 multiply, 11 lighten, 12 darken, 14 color, 15 hue, 16 saturation, 17 luminosity, 24 difference, 28 screen, 29 overlay, 30 soft light, 31 hard light, 33 color dodge, 34 color burn and 36 exclusion to its blend modes. Other merge modes, other records (a lens record of version 13 is 84 bytes) and the argument before version 13 are not applied, and the reader names them with lenses in the warnings | K L859 (the argument); KF L707-L798 (the records, the 117-byte body and the merge modes); S: the version 1300 record of LT `square_blackfill_nooutline_transparency50percent` of `testset/15` to `testset/25` is 117 bytes long, with 50.0 at byte 61 and 0 at byte 77; the lens records of UC `corel_lens_test_x3.cdr` (13) are 84 bytes long; of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; the direction of the value: VectorCraft's own reading, as every sample is at 50%, and a wrong reading shows a 25% transparency at 75%; the layout before version 13: unconfirmed, and it is not read) | +| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | +| R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample | +| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | +| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | +| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | +| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | +| 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) | +| 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 | 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) | +| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) | +| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) | +| R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) | +| R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample | diff --git a/crates/cdr/README.md b/crates/cdr/README.md new file mode 100644 index 0000000000..7a842a3abc --- /dev/null +++ b/crates/cdr/README.md @@ -0,0 +1,116 @@ +# craft-cdr + +A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates). +It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its +compressed lists, the ZIP packages that versions 14 and later save (with the data streams of +versions 16 and later) and the records listed below, and hands the engine a drawing in points, +with each object's transform. It does not write `.cdr` files. + +## What is read + +| In the `.cdr` file | Read as | +|---|---| +| ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it | +| Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side | +| Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind | +| The hidden and locked flags of layers, groups and objects | flags | +| Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle | +| Groups (`LIST grp `) | groups | +| Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips | +| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths | +| Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius | +| Ellipses, arcs and pies | ellipses, and paths for arcs and pies | +| Polygons and stars (a base side copied for each side) | paths | +| Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints | +| The fill's winding flag | the nonzero fill rule, or even-odd | +| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags, and from version 13 a library color named in their property list | outlines | +| Uniform transparency (version 13 on) and its merge mode | the shape's opacity and blend mode | +| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own | + +Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, +pattern, texture and PostScript fills, outline arrowheads, lenses, transparency other than uniform +transparency of version 13 and later, and merge modes without a VectorCraft blend mode are not +read; the drawing's +`warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages +that are encrypted, ZIP64 archives or split across files. + +VectorCraft reads a uniform transparency's stored value as the transparency in percent (0 opaque, +100 clear), and a winding flag other than 0 as the nonzero fill rule. These are VectorCraft's own +readings: no public source states either direction. + +## Versions 1 to 4 + +Public specifications cover only parts of these versions, such as the version 3 fill and page +settings. For the rest, the reader follows the layouts of public sample files that +`PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that +`src/synth.rs` builds from those rows. + +| Version | Read | Left out or refused | +|---|---|---| +| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the reader does not look for; the records after a drawn object of another type, with the unsupported-objects warning | +| 3 (RIFF, form type `CDR `) | the page size from the page's corners; pages, layers and groups; rectangles, ellipses, arcs and curves with the matrices of the object and of the groups around it; uniform fills; outlines with their width, color, caps, joins and dashes | text and bitmaps; envelopes, with the envelopes warning (the objects and groups under one keep their outlines and matrices); fountain, pattern and texture fills; arrowheads | +| 4 (RIFF, form type `CDR4`) | as version 5, with the colors and the fixed-point transforms of version 4 | as version 5 | + +A file is taken for version 1 or 2 by its content only when, after `WL`, its marker byte is one of +`e`, `l` and `m`, the next byte is zero, and the offsets of its header fit the file. The reader +reports version 1 for the marker `e` and version 2 for the other two. A RIFF file that names +a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as +not a `.cdr` drawing. + +## Previews + +`preview` returns the picture a `.cdr` file keeps of its drawing without reading the drawing (rows +R75 and R76). In versions 4 to 13 the picture is the `DISP` chunk, returned as a BMP file. In versions +14 to 16 it is the package member `metadata/thumbnails/thumbnail.bmp`, and from version 17 on it +is `previews/thumbnail.png`. The package's drawing stream is not read, so a package that holds +both members gives the PNG. Files of versions 1 and 3 keep no picture. A version 2 file keeps a +1-bit picture (R40) that `preview` does not read, so it refuses the file. `preview` does not check +the drawing's version, so a RIFF file that `read` refuses for its version, such as one that names a +version before 3, still gives its `DISP` picture. + +A `DISP` bitmap must start with the 4 bytes `08 00 00 00`, have a 40-byte info header and be +uncompressed (compression 0, or 3 with color masks at 16 or 32 bits). A `DISP` chunk of another +kind, or a bitmap with another header length or compression, is passed over without checking the +rest of its bytes, and a file with no other `DISP` chunk is refused. A RIFF file without a `DISP` bitmap is refused as damaged when its last chunk does not end +where the form's length says the form ends, which includes a file cut short. The bytes are returned +still encoded, so the caller decodes them within its own image limits. + +## `.cmx` files + +`read_cmx` reads `.cmx` exchange files with 32-bit coordinates (rows R53 to R63) into the same +drawing model, with a version of 0. It reads the color, pen, line type, dash, outline and +arrowhead tables, then each page's instructions in drawing order: + +| In the `.cmx` file | Read as | +|---|---| +| Pages, with the size the page gives, or else the size of the drawing's bounds that the page stores | pages; a page sized to the bounds is centered on them | +| Layers, by their UTF-16 or 8-bit name | drawing layers, unnamed when the file gives no name; a layer that holds nothing is left out | +| Groups | groups | +| Curves (moves, lines and cubic curves, as `.cdr` point lists) | paths | +| Uniform fills: CMYK in percent or 0 to 255, CMY, RGB, gray, and library colors with their names | colors, spot colors | +| Outlines: width, color, caps, joins, dashes, the no-outline, behind-the-fill and scaled-with flags | outlines | + +Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones, outline +arrowheads and lenses are not read; the drawing's `warnings` name each kind it held. A clipping +path is left out and the objects it clips are read without it. Files in big-endian byte order and +files with 16-bit coordinates are refused. + +## Provenance + +`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. +Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row. +The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the +`synth` feature); no third-party file is committed. + +## Limits + +`Limits` bounds the input size, the bytes inflated from compressed lists and package members, the +size of one package member, the number of members, the nesting depth, the chunk count, the +objects, the coordinates and the outline dashes of one read. Past a limit the reader stops with an +error or leaves the rest out with a warning; it does not recurse and does not panic. Each record +of a version 1 or 2 file counts toward the chunk count, and the transform entries of a version 3 +object are held to the arguments one record may have. A package's +data stream is read once however many lines of `content/dataFileList.dat` name it. A redirected +list whose bytes overlap those of an earlier redirected list is left out with the damage warning. +Other records may share bytes, and the bytes read again may add up to the member limit; past it +the records are left out with the limit warning. diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs new file mode 100644 index 0000000000..0bf017e4d7 --- /dev/null +++ b/crates/cdr/src/build.rs @@ -0,0 +1,917 @@ +//! The drawing the chunk index holds: pages, layers, objects and the fills and outlines they name +//! (R19 to R23). Records are decoded only when an object refers to them. + +use std::collections::HashMap; + +use crate::bytes::Rd; +use crate::geometry; +use crate::inline; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Blend, Color, Drawing, Flags, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::records::{self, Loda}; +use crate::riff::{Chunk, Index, push}; +use crate::styles::Styles; +use crate::{Error, Warning}; + +/// Object types (R6). +const RECTANGLE: u32 = 1; +const ELLIPSE: u32 = 2; +const CURVE: u32 = 3; +const POLYGON: u32 = 0x14; +const GUIDELINE: u32 = 0x16; +const PATH: u32 = 0x25; +/// Argument types (R6, R20, R21, R33, R52). +const ARG_OUTLINE: u32 = 10; +const ARG_FILL: u32 = 20; +const ARG_COORDS: u32 = 30; +const ARG_TRANSFORMS: u32 = 100; +const ARG_STYLE: u32 = 200; +const ARG_NAME: u32 = 1000; +const ARG_LENS: u32 = 8000; +const ARG_CONTAINER: u32 = 8005; +const ARG_POLYGON: u32 = 11000; +const ARG_WINDING: u32 = 14001; +const ARG_GUIDE: u32 = 16000; +const ARG_PAGE_SIZE: u32 = 19130; + +/// What a RIFF file that names a version before 3 is refused as. +const BEFORE_3: &str = "RIFF files of versions before 3"; + +/// What one read keeps while mapping. +struct Ctx<'a, 'b> { + ix: &'b Index<'a>, + p: Profile, + budget: &'b mut Budget, + warn: &'b mut Vec, + /// Fill and outline records by id, decoded on first use. + fill_chunks: HashMap, + outline_chunks: HashMap, + fills: HashMap>, + outlines: HashMap>, + /// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't + /// parse. + styles: Result, + /// The groups of `LIST clpt` that containers clip, by the id in their `spnd` chunk (R46). + clips: HashMap, + /// The clipped groups being read, innermost last. + open_clips: Vec, + /// Whether the walk of a clipped group stopped at the clipped chunk limit. + clip_cut: bool, + /// The chunks the object lists of clipped groups keep for themselves, by list, each found the + /// first time a read needs it. + own: HashMap<(*const Chunk, Own), Option<&'b Chunk>>, + /// The matrices the `trfd` chunks of clipped groups' objects hold, by chunk; `None` for one + /// that can't be read. + trfds: HashMap<*const Chunk, Option>, +} + +/// A chunk an object list keeps for itself. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Own { + /// Its `loda` (or `lobj`). + Loda, + /// Its `flgs`, among its own chunks alone. + Flags, + /// Its `trfd`. + Trfd, +} + +impl Own { + fn ids(self) -> &'static [&'static [u8; 4]] { + match self { + Own::Loda => &[b"loda", b"lobj"], + Own::Flags => &[b"flgs"], + Own::Trfd => &[b"trfd"], + } + } +} + +/// The most clipped groups read one inside another: VectorCraft's own limit. +const MAX_CLIP_DEPTH: usize = 64; + +pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) -> Result { + let root = ix.root().ok_or(Error::NotCdr)?; + let version = ix.version(); + // A template whose `vrsn` chunk doesn't name a version read (R28). + if version == 0 { + return Err(Error::NotCdr); + } + // Versions 1 and 2 are `WL` files (R40); no source shows a RIFF file that names a version + // before 3. + if version < layout::OLDEST_RIFF { + return Err(Error::Unsupported(BEFORE_3)); + } + let p = layout::for_version(version).ok_or(Error::Version(version))?; + let mut found = Found::default(); + collect(ix, root, &mut found); + let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p)); + // Before version 7 a `LIST stlt` holds chunks, not the style table (R4). + let styles = match found.stlt { + Some(c) if version >= 700 => Styles::read(ix.data(c), version, budget)?.ok_or(()), + _ => Ok(Styles::default()), + }; + let mut cx = Ctx { + ix, + p, + budget, + warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::new(), + fills: HashMap::new(), + outlines: HashMap::new(), + styles, + clips: HashMap::new(), + open_clips: Vec::new(), + clip_cut: false, + own: HashMap::new(), + trfds: HashMap::new(), + }; + // The `spnd` id is a u16 in files of 16-bit fields (R46). + let spnd = |b: &[u8]| if p.short { Rd::new(b).u16().map(u32::from) } else { Rd::new(b).u32() }; + for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) { + if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| spnd(ix.data(c))) { + cx.clips.entry(id).or_insert(g); + } + } + for c in &found.fills { + if let Some(id) = Rd::new(ix.data(c)).u32() { + cx.fill_chunks.entry(id).or_insert(ix.data(c)); + } + } + for c in &found.outlines { + if let Some(id) = Rd::new(ix.data(c)).u32() { + cx.outline_chunks.entry(id).or_insert(ix.data(c)); + } + } + let mut guides = found.guid.map(|c| guid_chunk(ix.data(c), &cx.p, cx.budget, cx.warn)).unwrap_or_default(); + let mut pages = Vec::new(); + let mut master = Vec::new(); + for page in &found.pages { + let (is_master, read) = cx.page(page); + if is_master { + // Guidelines on any of the master page's layers show on every page. + for mut layer in read.layers { + guides.append(&mut layer.guides); + if !layer.objects.is_empty() && layer.kind != LayerKind::Grid { + master.push(layer); + } + } + } else { + pages.push(read); + } + } + // A file of only a master page keeps it as its page. + if pages.is_empty() && !master.is_empty() { + pages.push(Page { size: None, layers: std::mem::take(&mut master) }); + } + Ok(Drawing { version, page_size, pages, master, guides, warnings: std::mem::take(cx.warn) }) +} + +#[derive(Default)] +struct Found<'i> { + fills: Vec<&'i Chunk>, + outlines: Vec<&'i Chunk>, + mcfg: Option<&'i Chunk>, + guid: Option<&'i Chunk>, + stlt: Option<&'i Chunk>, + clpt: Vec<&'i Chunk>, + pages: Vec<&'i Chunk>, +} + +/// Every fill, outline, `LIST clpt` and page in file order, and the first `mcfg`, `guid` and +/// `LIST stlt`; pages are not looked into. +fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { + let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect(); + while let Some(c) = stack.pop() { + match &c.id { + b"fild" | b"fill" => found.fills.push(c), + b"outl" => found.outlines.push(c), + b"mcfg" => found.mcfg = found.mcfg.or(Some(c)), + b"guid" => found.guid = found.guid.or(Some(c)), + // Before version 7 the list holds chunks, which are looked through. + _ if c.is_list(b"stlt") => { + found.stlt = found.stlt.or(Some(c)); + stack.extend(ix.children(c).iter().rev()); + } + _ if c.is_list(b"clpt") => found.clpt.push(c), + _ if c.is_list(b"page") => found.pages.push(c), + _ => stack.extend(ix.children(c).iter().rev()), + } + } +} + +/// The page size in `mcfg` (R10); in version 3 the distance between the page's two corners, after +/// 2 bytes (R38). +fn page_size(b: &[u8], p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, p.mcfg_skip); + if p.mcfg_corners { + r.skip(2)?; + let (x0, y0, x1, y1) = (records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?); + return sane_size(x1 - x0, y1 - y0); + } + sane_size(records::coord(&mut r, p)?, records::coord(&mut r, p)?) +} + +fn sane_size(w: f64, h: f64) -> Option<(f64, f64)> { + let (w, h) = (w.abs(), h.abs()); + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// The version 7 `guid` chunk (R23): two counts, then 40-byte records laid out as argument 16000. +/// Each guideline counts toward the objects a read maps; past them the rest are left out. +fn guid_chunk(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Vec { + let mut r = Rd::new(b); + let Some(n) = r.u32() else { return Vec::new() }; + let _again = r.u32(); + let fits = r.left() / 40; + if n as usize > fits { + push(warn, Warning::Damaged); + } + let n = (n as usize).min(fits); + let mut out = Vec::new(); + for i in 0..n { + if !budget.take_object() { + push(warn, Warning::TooDeep); + break; + } + out.extend(b.get(8 + i * 40..8 + (i + 1) * 40).and_then(|g| guideline(g, p))); + } + out +} + +/// A guideline record (R23): 12 bytes, the angle in millionths of a degree, then a point. +fn guideline(b: &[u8], p: &Profile) -> Option { + if p.short { + return None; + } + let mut r = Rd::at(b, 12); + let angle = f64::from(r.i32()?) / 1_000_000.0; + let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? }; + Some(Guideline { at, angle, hidden: false }) +} + +/// Marks the guidelines from `from` on hidden when `flags` hide what holds them. +fn hide_guides(guides: &mut [Guideline], from: usize, flags: Flags) { + if flags.hidden { + for g in guides.iter_mut().skip(from) { + g.hidden = true; + } + } +} + +/// A list's flags (R19): four bytes. +fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> { + flgs_bytes(ix, ix.children(list).iter().find(|c| &c.id == b"flgs")?) +} + +/// The four bytes of a `flgs` chunk. +fn flgs_bytes(ix: &Index, c: &Chunk) -> Option<[u8; 4]> { + ix.data(c).get(..4)?.try_into().ok() +} + +/// Whether a layer, group or object list is hidden (bit 0x01 of byte 1) or locked (bit 0x10 of +/// byte 0) (R19). +fn state(ix: &Index, list: &Chunk) -> Flags { + flags(ix, list).map_or(Flags::default(), flag_bits) +} + +/// What a list's four flag bytes say, as [`state`] reads them. +fn flag_bits([b0, b1, _, _]: [u8; 4]) -> Flags { + Flags { hidden: b1 & 0x01 != 0, locked: b0 & 0x10 != 0 } +} + +/// `o` with `f` added to its own flags: the objects of a group left ungrouped keep the group's. +fn inherit(o: &mut Object, f: Flags) { + let own = match o { + Object::Shape(s) => &mut s.flags, + Object::Group { flags, .. } => flags, + Object::Clip { container, .. } => &mut container.flags, + }; + own.hidden |= f.hidden; + own.locked |= f.locked; +} + +/// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a +/// drawing layer. Version 3 counts its types from 0, one less (R32). +fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind { + match kind.saturating_add(u32::from(types_from_zero)) { + 11 => LayerKind::Grid, + 12 => LayerKind::Guides, + 17 => LayerKind::Desktop, + _ => LayerKind::Drawing, + } +} + +/// What a layer's flags make it, for a layer without an object type of its own (R19). The low +/// four bits of byte 0 hold the kind: 0x0a guides, or a grid with bit 0x10 set (versions 7 to 13 +/// also flag them 0x02); 0x08 the desktop when byte 2 is set, a drawing layer when it is clear. +/// Versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set. Bit 0x10 +/// alone does not make a grid. +fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind { + let [b0, b1, b2, _] = f; + let grid_bit = b0 & 0x10 != 0; + match b0 & 0x0f { + 0x0a if grid_bit => LayerKind::Grid, + 0x0a => LayerKind::Guides, + 0x02 if version_below_14 && grid_bit => LayerKind::Grid, + 0x02 if version_below_14 => LayerKind::Guides, + 0x08 if b2 != 0 => LayerKind::Desktop, + 0 if version_below_14 && b1 == 1 && b2 == 1 => LayerKind::Desktop, + _ => LayerKind::Drawing, + } +} + +/// The first chunk of one of `ids` that a page, layer or object keeps for itself: among its own +/// chunks, or in its `lgob` list and the `trfl` list there (R22). +fn own_chunk<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]]) -> Option<&'i Chunk> { + find_own(ix, list, ids, true, || true).flatten() +} + +/// The first chunk of one of `ids` among `list`'s own chunks, and when `nested` also in its `lgob` +/// list and the `trfl` list there, as [`own_chunk`] finds it. `visit` is asked before each chunk +/// the search looks at, and the search stops with `None` when it answers `false`. +fn find_own<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]], nested: bool, mut visit: impl FnMut() -> bool) -> Option> { + // The lists being looked through, outermost first, each with the next chunk to look at, and + // the innermost one's place. + let mut stack: [(&'i [Chunk], usize); 3] = [(ix.children(list), 0), (&[], 0), (&[], 0)]; + let mut depth = 0; + loop { + let Some(top) = stack.get_mut(depth) else { return Some(None) }; + let chunks: &'i [Chunk] = top.0; + let Some(c) = chunks.get(top.1) else { + if depth == 0 { + return Some(None); + } + depth -= 1; + continue; + }; + top.1 += 1; + if !visit() { + return None; + } + if ids.contains(&&c.id) { + return Some(Some(c)); + } + if nested && depth < 2 && (c.is_list(b"lgob") || c.is_list(b"trfl")) { + depth += 1; + if let Some(next) = stack.get_mut(depth) { + *next = (ix.children(c), 0); + } + } + } +} + +/// The `loda` (or `lobj`) a page, layer or object keeps for itself. +fn own_loda<'i>(ix: &'i Index, list: &'i Chunk) -> Option<&'i Chunk> { + own_chunk(ix, list, &[b"loda", b"lobj"]) +} + +/// A page's layer lists in file order: its own, and those in the lists it holds, such as the +/// `gobj` list of files of versions 7 to 13 (R22). +fn page_layers<'i>(ix: &'i Index, page: &'i Chunk) -> Vec<&'i Chunk> { + let mut out = Vec::new(); + let mut stack: Vec<&Chunk> = ix.children(page).iter().rev().collect(); + while let Some(c) = stack.pop() { + if c.is_list(b"layr") { + out.push(c); + } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { + stack.extend(ix.children(c).iter().rev()); + } + } + out +} + +/// One frame of the object walk: a list's chunks, the next one to look at, and the objects so far. +struct Frame<'i> { + chunks: &'i [Chunk], + next: usize, + objects: Vec, + /// Whether its objects form a group in the frame below. + group: bool, + /// The group's own flags. + flags: Flags, + /// The first of the guidelines read inside it. + guides_from: usize, + /// What places its objects after their own transforms: the matrices of the version 3 groups + /// around them (R33). The identity in other versions, whose objects hold their whole transform. + outer: Matrix, +} + +impl<'a, 'b> Ctx<'a, 'b> { + /// A page: whether it is the master page, and its layers. + fn page(&mut self, page: &Chunk) -> (bool, Page) { + let ix = self.ix; + let is_master = flags(ix, page).is_some_and(|f| f[2] != 0); + let size = own_loda(ix, page) + .and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) + .and_then(|l| l.arg(ARG_PAGE_SIZE).and_then(|b| self.size_arg(b))); + let mut layers = Vec::new(); + for l in page_layers(ix, page) { + let layer = self.layer(l); + let empty = layer.objects.is_empty() && layer.guides.is_empty(); + // The entries that stand for the master page's layers hold nothing of the page's own. + if empty && (is_master || layer.kind != LayerKind::Drawing) { + continue; + } + layers.push(layer); + } + (is_master, Page { size, layers }) + } + + fn size_arg(&self, b: &[u8]) -> Option<(f64, f64)> { + let mut r = Rd::new(b); + sane_size(records::coord(&mut r, &self.p)?, records::coord(&mut r, &self.p)?) + } + + fn layer(&mut self, list: &Chunk) -> Layer { + let ix = self.ix; + let loda = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)); + // The layer's own object type says what it is; its flags, only when it has none (R19). + let kind = match &loda { + Some(l) => layer_kind_of_type(l.kind, self.p.types_from_zero), + None => flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)), + }; + let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default(); + let mut guides = Vec::new(); + let objects = self.objects(ix.children(list), &mut guides); + let flags = state(ix, list); + hide_guides(&mut guides, 0, flags); + Layer { name, kind, flags, objects, guides } + } + + /// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`. + fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec) -> Vec { + let ix = self.ix; + let mut stack = vec![Frame { + chunks, + next: 0, + objects: Vec::new(), + group: false, + flags: Flags::default(), + guides_from: guides.len(), + outer: Matrix::IDENTITY, + }]; + loop { + let Some(top) = stack.last_mut() else { return Vec::new() }; + let (here, outer) = (top.chunks, top.outer); + let Some(c) = here.get(top.next) else { + let Some(done) = stack.pop() else { return Vec::new() }; + // A hidden group hides the guidelines inside it. + hide_guides(guides, done.guides_from, done.flags); + match stack.last_mut() { + // A group counts toward the objects a read maps; past them its objects stay, + // ungrouped, with the group's flags. + Some(parent) if done.group && !done.objects.is_empty() => { + if self.budget.take_object() { + parent.objects.push(Object::Group { objects: done.objects, flags: done.flags }); + } else { + push(self.warn, Warning::TooDeep); + let mut objects = done.objects; + for o in &mut objects { + inherit(o, done.flags); + } + parent.objects.extend(objects); + } + } + Some(parent) if !done.group => parent.objects.extend(done.objects), + Some(_) => {} + None => return done.objects, + } + continue; + }; + top.next += 1; + // Every chunk of a clipped group counts, empty groups included, each time a container + // names the group; past the limit the group is left out. + if !self.open_clips.is_empty() && !self.budget.take_clipped_chunk() { + push(self.warn, Warning::TooDeep); + self.clip_cut = true; + return Vec::new(); + } + if c.is_list(b"obj ") { + if let Some(o) = self.object(c, guides, &outer) { + top.objects.push(o); + } + // Past the limit while looking for what the object keeps for itself. + if self.clip_cut { + return Vec::new(); + } + } else if c.is_list(b"grp ") { + let own = self.group_placement(c); + let flags = state(ix, c); + let guides_from = guides.len(); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, flags, guides_from, outer: outer.after(&own) }); + } else if c.is_list(b"lnkg") { + // Linked groups (brush strokes, blends, contours) place their objects with a + // matrix of their own, which this reader doesn't apply: they are left out. + push(self.warn, Warning::UnsupportedObjects); + } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { + // Other lists under a layer are looked through (R22). + let guides_from = guides.len(); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, flags: Flags::default(), guides_from, outer }); + } + } + } + + /// The `which` chunk object list `list` keeps for itself. In a clipped group it is looked for + /// once per read, the first time a container's walk needs it, and each chunk the search looks + /// at counts toward the clipped chunk limit then; past that limit the walk stops (`None`). + fn own(&mut self, list: &'b Chunk, which: Own) -> Option> { + let nested = which != Own::Flags; + if self.open_clips.is_empty() { + return find_own(self.ix, list, which.ids(), nested, || true); + } + let key = (std::ptr::from_ref(list), which); + if let Some(c) = self.own.get(&key) { + return Some(*c); + } + let Some(c) = find_own(self.ix, list, which.ids(), nested, || self.budget.take_clipped_chunk()) else { + push(self.warn, Warning::TooDeep); + self.clip_cut = true; + return None; + }; + self.own.insert(key, c); + Some(c) + } + + /// The matrix `trfd` holds, or `None` when it can't be read. In a clipped group each `trfd` is + /// read once per read, however many containers name the group. + fn trfd(&mut self, c: &'b Chunk) -> Option { + if self.open_clips.is_empty() { + return records::trfd(self.ix.data(c), &self.p); + } + let ix = self.ix; + let p = &self.p; + *self.trfds.entry(std::ptr::from_ref(c)).or_insert_with(|| records::trfd(ix.data(c), p)) + } + + /// The matrix a group places its objects with. Only a version 3 group has one, in the + /// transforms argument of its own `lobj` (R33); one that can't be read is damage, and the + /// group's objects stay where their own transforms put them. + fn group_placement(&mut self, list: &Chunk) -> Matrix { + if !self.p.inline_styles { + return Matrix::IDENTITY; + } + let ix = self.ix; + let Some(arg) = + own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)).and_then(|l| l.arg(ARG_TRANSFORMS)) + else { + return Matrix::IDENTITY; + }; + self.placement(arg) + } + + /// The matrices of a transforms argument (R33). An envelope among them is not applied: the + /// shapes keep their outlines, placed by the matrices alone, with the envelopes warning. + fn placement(&mut self, arg: &[u8]) -> Matrix { + match inline::transforms(arg, &self.p, &self.budget.limits, self.warn) { + Some(t) => { + if t.envelope { + push(self.warn, Warning::Envelopes); + } + t.matrix + } + None => { + push(self.warn, Warning::Damaged); + Matrix::IDENTITY + } + } + } + + /// One `LIST obj `: a shape placed by its own transform and then by `outer`, or `None` (a + /// guideline goes to `guides`). + fn object(&mut self, list: &'b Chunk, guides: &mut Vec, outer: &Matrix) -> Option { + let ix = self.ix; + let Some(loda) = self.own(list, Own::Loda)?.and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) else { + push(self.warn, Warning::Damaged); + return None; + }; + // Guidelines count toward the objects a read maps. + if !self.budget.take_object() { + push(self.warn, Warning::TooDeep); + return None; + } + let flags = self.own(list, Own::Flags)?.and_then(|c| flgs_bytes(ix, c)).map_or(Flags::default(), flag_bits); + if loda.kind == GUIDELINE { + guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)).map(|g| Guideline { hidden: flags.hidden, ..g })); + return None; + } + if self.p.inline_styles { + return self.inline_object(&loda, outer, flags); + } + let geometry = self.geometry(&loda)?; + // A uniform transparency from version 13 applies (R47); a lens, and a transparency of + // another kind or version, is not applied: the shape shows opaque. + let (opacity, blend) = match loda.arg(ARG_LENS) { + None => (1.0, Blend::Normal), + Some(b) => match records::transparency(b).filter(|_| self.p.tagged) { + Some(t) => t, + None => { + push(self.warn, Warning::Lenses); + (1.0, Blend::Normal) + } + }, + }; + let nonzero = self.nonzero(&loda); + // A transform that is there but can't be read is damage; the shape stays where it is. + let matrix = match self.own(list, Own::Trfd)? { + None => Matrix::IDENTITY, + Some(c) => self.trfd(c).unwrap_or_else(|| { + push(self.warn, Warning::Damaged); + Matrix::IDENTITY + }), + }; + // Without a fill or outline argument of its own, an object takes its style's (R45). The + // style id is a u16 in files of 16-bit fields. + let style = loda.arg(ARG_STYLE).and_then(|b| if self.p.short { self.short_id(b) } else { self.id(b) }); + let fill_id = match loda.arg(ARG_FILL) { + Some(b) => self.id(b), + None => style.and_then(|s| self.style_entry(s, Styles::fill)), + }; + let outline_id = match loda.arg(ARG_OUTLINE) { + Some(b) => self.id(b), + None => style.and_then(|s| self.style_entry(s, Styles::outline)), + }; + let fill = fill_id.and_then(|id| self.fill(id)); + let outline = outline_id.and_then(|id| self.outline(id)); + let shape = Box::new(Shape { geometry, matrix, fill, outline, nonzero, opacity, blend, flags }); + // A container clips the group its argument 8005 names (R46). + Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) { + Some(id) => self.clip(shape, id, guides), + None => Object::Shape(shape), + }) + } + + /// `container` and the objects of the clipped group `id`, which keep their own transforms. + /// A group that isn't there is damage; one already being read, past the depth limit or past + /// the chunks clipped groups may walk is left out with the limit warning, the guidelines it + /// holds included. Either way the container stays, as a plain shape. + fn clip(&mut self, container: Box, id: u32, guides: &mut Vec) -> Object { + let Some(&group) = self.clips.get(&id) else { + push(self.warn, Warning::Damaged); + return Object::Shape(container); + }; + if self.open_clips.contains(&id) || self.open_clips.len() >= MAX_CLIP_DEPTH { + push(self.warn, Warning::TooDeep); + return Object::Shape(container); + } + self.open_clips.push(id); + let (ix, mark) = (self.ix, guides.len()); + let objects = self.objects(ix.children(group), guides); + self.open_clips.pop(); + if std::mem::take(&mut self.clip_cut) { + guides.truncate(mark); + return Object::Shape(container); + } + // The clipped group's own flags hide or lock the objects it holds; it and the container + // hide its guidelines. + let flags = state(ix, group); + hide_guides(guides, mark, flags); + hide_guides(guides, mark, container.flags); + if objects.is_empty() { + return Object::Shape(container); + } + let mut objects = objects; + for o in &mut objects { + inherit(o, flags); + } + Object::Clip { container, objects } + } + + /// The record id that argument `b` names; an argument too short for one is damage. + fn id(&mut self, b: &[u8]) -> Option { + let id = id_of(b); + if id.is_none() { + push(self.warn, Warning::Damaged); + } + id + } + + /// A u16 id at the start of argument `b`; an argument too short for one is damage. + fn short_id(&mut self, b: &[u8]) -> Option { + let id = Rd::new(b).u16().map(u32::from); + if id.is_none() { + push(self.warn, Warning::Damaged); + } + id + } + + /// Whether the object's fill rule is nonzero: byte 0 of argument 14001 set (R52). Without the + /// argument the fill is even-odd; an argument without its byte is damage. + fn nonzero(&mut self, loda: &Loda) -> bool { + let Some(b) = loda.arg(ARG_WINDING) else { return false }; + match b.first() { + Some(v) => *v != 0, + None => { + push(self.warn, Warning::Damaged); + false + } + } + } + + /// The fill or outline record that style `id` names; a style table that doesn't parse is + /// damage, and the object is drawn without it. + fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option) -> Option { + match &self.styles { + Ok(s) => entry(s, id), + Err(()) => { + push(self.warn, Warning::Damaged); + None + } + } + } + + /// A version 3 object, whose transforms, fill and outline are arguments of its own record + /// (R33, R34, R35). A fill or an outline that is there but can't be read is damage. + fn inline_object(&mut self, loda: &Loda, outer: &Matrix, flags: Flags) -> Option { + let own = match loda.arg(ARG_TRANSFORMS) { + None => Matrix::IDENTITY, + Some(arg) => self.placement(arg), + }; + let geometry = self.geometry(loda)?; + let fill = loda.arg(ARG_FILL).and_then(|b| { + let read = inline::fill(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.flatten() + }); + let outline = loda.arg(ARG_OUTLINE).and_then(|b| { + let read = inline::outline(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.flatten() + }); + // Past the dashes a read takes, the outline is solid. + let outline = outline.map(|mut o| { + if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + o + }); + let nonzero = self.nonzero(loda); + let shape = Shape { nonzero, flags, ..Shape::new(geometry, outer.after(&own), fill, outline) }; + Some(Object::Shape(Box::new(shape))) + } + + fn geometry(&mut self, loda: &Loda) -> Option { + let coords = loda.arg(ARG_COORDS); + // Version 3 counts the first object types from 0, one below the later numbers (R32). + let kind = if self.p.types_from_zero && loda.kind <= 4 { loda.kind + 1 } else { loda.kind }; + // A shape without its coordinates, or a polygon without its sides, is damage like a shape + // whose coordinates can't be read; one left out at the coordinate limit is not. + self.budget.coordinates_refused(); + let g = match kind { + RECTANGLE => coords.and_then(|c| geometry::rect(c, &self.p)), + ELLIPSE => coords.and_then(|c| geometry::ellipse(c, &self.p)), + CURVE => coords.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)).map(Geometry::Path), + PATH if self.p.paths => coords.and_then(|c| geometry::path_record(c, &self.p, self.budget, self.warn)).map(Geometry::Path), + POLYGON => match loda.arg(ARG_POLYGON) { + Some(sides) => coords + .and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)) + .and_then(|base| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)), + None => { + push(self.warn, Warning::Damaged); + return None; + } + }, + _ => { + push(self.warn, Warning::UnsupportedObjects); + return None; + } + }; + if g.is_none() && !self.budget.coordinates_refused() { + push(self.warn, Warning::Damaged); + } + g + } + + fn fill(&mut self, id: u32) -> Option { + if let Some(f) = self.fills.get(&id) { + return f.clone(); + } + // A record that is missing or can't be read is damage, and the shape is drawn without a + // fill; id 0 without a record is no fill. + if id != 0 && !self.fill_chunks.contains_key(&id) { + push(self.warn, Warning::Damaged); + } + let read = self.fill_chunks.get(&id).and_then(|b| { + let read = records::fill(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.and_then(|(_, c)| c) + }); + self.fills.insert(id, read.clone()); + read + } + + /// The outline of record `id`. Its dashes count toward the read's dashes for every shape that + /// uses it; past them the shape's outline is solid. + fn outline(&mut self, id: u32) -> Option { + if !self.outlines.contains_key(&id) { + // A record that is missing is damage, as one that can't be read is; id 0 without a + // record is no outline. + if id != 0 && !self.outline_chunks.contains_key(&id) { + push(self.warn, Warning::Damaged); + } + let read = self.outline_chunks.get(&id).and_then(|b| { + let read = records::outline(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.and_then(|(_, o)| o) + }); + // An outline with more dashes than the read may still take is kept solid. + let read = read.map(|mut o| { + if o.dashes.len() > self.budget.dashes_left() { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + o + }); + self.outlines.insert(id, read); + } + let o = self.outlines.get_mut(&id)?.as_mut()?; + // The dashes left only shrink, so an outline refused once is refused for every later + // shape: its dashes are dropped from the cache, and later shapes take it solid. + if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + Some(o.clone()) + } +} + +/// A fill or outline argument: the record id (R20). +fn id_of(b: &[u8]) -> Option { + Rd::new(b).u32() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layer_flags_name_the_kinds() { + assert_eq!(layer_kind([0, 0, 0, 0x98], true), LayerKind::Drawing); + assert_eq!(layer_kind([0x0a, 0, 0, 0x98], true), LayerKind::Guides); + assert_eq!(layer_kind([0x02, 1, 1, 0x98], true), LayerKind::Guides); + assert_eq!(layer_kind([0x08, 0, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0, 1, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0x1a, 0, 1, 0x98], true), LayerKind::Grid); + assert_eq!(layer_kind([0x12, 0, 1, 0x98], true), LayerKind::Grid); + // From version 14 the master page flags its layers by byte 0 alone. + assert_eq!(layer_kind([0x0a, 0, 1, 0x98], false), LayerKind::Guides); + assert_eq!(layer_kind([0x08, 0, 1, 0x98], false), LayerKind::Desktop); + assert_eq!(layer_kind([0x5a, 1, 1, 0x98], false), LayerKind::Grid); + assert_eq!(layer_kind([0x02, 1, 1, 0x98], false), LayerKind::Drawing); + assert_eq!(layer_kind([0, 1, 1, 0x98], false), LayerKind::Drawing); + // Drawing layers flagged 0x10, 0x08, 0x18, 0x40 and 0x58 with byte 2 clear, as sample + // files flag them, and desktop and guides layers with bit 0x40 or 0x10 set. + for f in [[0x10, 0, 0, 0x98], [0x08, 1, 0, 0x98], [0x18, 1, 0, 0x98], [0x40, 0, 0, 0x98], [0x58, 1, 0, 0x98]] { + assert_eq!(layer_kind(f, true), LayerKind::Drawing, "{f:?}"); + assert_eq!(layer_kind(f, false), LayerKind::Drawing, "{f:?}"); + } + assert_eq!(layer_kind([0x18, 0, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0x48, 0, 1, 0x98], false), LayerKind::Desktop); + assert_eq!(layer_kind([0x4a, 1, 1, 0x98], true), LayerKind::Guides); + } + + /// An outline record refused at the dash limit keeps no dashes in the cache, so the shapes + /// that use it later copy none. + #[test] + fn an_outline_past_the_dash_limit_keeps_no_dashes() { + let v = crate::synth::V(1100); + let pen = crate::synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 }; + let record = v.outline(1, pen, &crate::synth::color(5, [0, 0, 0, 255]), &[3, 1, 3]); + let file = crate::synth::riff(1100, &[]); + let mut budget = Budget::new(crate::Limits { dashes: 4, ..crate::Limits::default() }); + let mut warn = Vec::new(); + let ix = crate::riff::Index::build(&file, None, &mut budget, &mut warn).unwrap(); + let mut cx = Ctx { + ix: &ix, + p: layout::for_version(1100).unwrap(), + budget: &mut budget, + warn: &mut warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::from([(1, record.as_slice())]), + fills: HashMap::new(), + outlines: HashMap::new(), + styles: Ok(Styles::default()), + clips: HashMap::new(), + open_clips: Vec::new(), + clip_cut: false, + own: HashMap::new(), + trfds: HashMap::new(), + }; + assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(3)); + for _ in 0..3 { + assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(0)); + assert_eq!(cx.outlines.get(&1).and_then(|o| o.as_ref()).map(|o| o.dashes.len()), Some(0)); + } + assert_eq!(*cx.warn, vec![Warning::TooDeep]); + } +} diff --git a/crates/cdr/src/bytes.rs b/crates/cdr/src/bytes.rs new file mode 100644 index 0000000000..216bd90024 --- /dev/null +++ b/crates/cdr/src/bytes.rs @@ -0,0 +1,76 @@ +//! Little-endian reads that fail instead of panicking. + +/// A cursor over one record's bytes. Every read returns `None` past the end. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Rd<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Rd<'a> { + pub(crate) fn new(b: &'a [u8]) -> Self { + Rd { b, pos: 0 } + } + + pub(crate) fn at(b: &'a [u8], pos: usize) -> Self { + Rd { b, pos } + } + + pub(crate) fn pos(&self) -> usize { + self.pos + } + + pub(crate) fn left(&self) -> usize { + self.b.len().saturating_sub(self.pos) + } + + pub(crate) fn skip(&mut self, n: usize) -> Option<()> { + let end = self.pos.checked_add(n)?; + (end <= self.b.len()).then(|| self.pos = end) + } + + pub(crate) fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(n)?; + let s = self.b.get(self.pos..end)?; + self.pos = end; + Some(s) + } + + fn array(&mut self) -> Option<[u8; N]> { + self.bytes(N)?.try_into().ok() + } + + pub(crate) fn u8(&mut self) -> Option { + Some(self.array::<1>()?[0]) + } + + pub(crate) fn u16(&mut self) -> Option { + self.array().map(u16::from_le_bytes) + } + + pub(crate) fn i16(&mut self) -> Option { + self.array().map(i16::from_le_bytes) + } + + pub(crate) fn u32(&mut self) -> Option { + self.array().map(u32::from_le_bytes) + } + + pub(crate) fn i32(&mut self) -> Option { + self.array().map(i32::from_le_bytes) + } + + /// A finite f64; NaN and the infinities read as `None`. + pub(crate) fn f64(&mut self) -> Option { + self.array().map(f64::from_le_bytes).filter(|v| v.is_finite()) + } + + pub(crate) fn fourcc(&mut self) -> Option<[u8; 4]> { + self.array() + } +} + +/// The u32 at `pos` of `b`. +pub(crate) fn u32_at(b: &[u8], pos: usize) -> Option { + Rd::at(b, pos).u32() +} diff --git a/crates/cdr/src/cmx.rs b/crates/cdr/src/cmx.rs new file mode 100644 index 0000000000..4960c4b8df --- /dev/null +++ b/crates/cdr/src/cmx.rs @@ -0,0 +1,655 @@ +//! Reader for `.cmx` exchange files with 32-bit coordinates: the RIFF form `CMX1` (R53), its +//! header (R54), the color, pen, line type, dash, outline and arrowhead tables (R55 to R59) and the +//! instructions of each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills +//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses +//! are left out with a warning. + +use crate::bytes::{Rd, u32_at}; +use crate::geometry::path_of; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::records::{name, property_color}; +use crate::riff::{LIST, push}; +use crate::{Error, Warning}; + +const FORM: [u8; 4] = *b"CMX1"; +/// Meters per coordinate unit when the header gives no usable value: the 0.1 µm of every sample +/// file with 32-bit coordinates (R54). +const DEFAULT_UNIT: f64 = 1e-7; +/// How far past a chunk that runs short the next chunk id is looked for (R53). +const RESYNC: usize = 64; +/// The chunks the reader uses (R53 to R60). +const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"]; +/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them. +const MAX_NAME_UNITS: usize = 4096; + +// Instruction codes (R60). +const BEGIN_PAGE: i16 = 9; +const END_PAGE: i16 = 10; +const BEGIN_LAYER: i16 = 11; +const END_LAYER: i16 = 12; +const BEGIN_GROUP: i16 = 13; +const END_GROUP: i16 = 14; +const BEGIN_TEXT: i16 = 20; +const END_TEXT: i16 = 21; +const GLYPH_RUN: i16 = 65; +const ELLIPSE: i16 = 66; +const CURVE: i16 = 67; +const RECTANGLE: i16 = 68; +const IMAGE: i16 = 69; +const ADD_CLIP: i16 = 88; +const REMOVE_CLIP: i16 = 89; +const JUMP: i16 = 111; + +/// Does `bytes` start as a CMX file: a RIFF or RIFX form of type `CMX1` (R53)? +pub(crate) fn is_cmx(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some(b"RIFF" | b"RIFX")) && bytes.get(8..12) == Some(FORM.as_slice()) +} + +/// A chunk outside the `LIST` chunks: its id, its body and where the body starts in the file. +struct Chunk<'a> { + id: [u8; 4], + body: &'a [u8], + start: usize, +} + +/// The tables that page instructions refer to by 1-based index (R55 to R59). +#[derive(Default)] +struct Tables { + colors: Vec>, + /// Outline widths in points. + pens: Vec>, + /// Flags, and the caps and join. + line_types: Vec>, + dashes: Vec>, + /// Line type, screen, color, arrowheads, pen and dashes. + outlines: Vec>, + arrowheads: Vec<(u16, u16)>, +} + +pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result { + if !is_cmx(bytes) { + return Err(Error::NotCmx); + } + if bytes.get(0..4) == Some(b"RIFX") { + return Err(Error::Unsupported("big-endian CMX files")); + } + let mut warn = Vec::new(); + let chunks = chunks(bytes, budget, &mut warn)?; + let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?; + match cont.get(52) { + Some(b'4') => {} + Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")), + _ => return Err(Error::Damaged("CMX header")), + } + let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT); + let unit = meters / 0.0254 * 72.0; + let tables = Tables::read(&chunks, unit, budget, &mut warn)?; + let mut pages = Vec::new(); + for c in chunks.iter().filter(|c| c.id == *b"page") { + pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?); + } + Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) +} + +/// The chunks of the file in order, those inside `LIST` chunks in place (R53). +fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Result>, Error> { + let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len()); + if declared > b.len() { + // The file was cut short of the size its header gives. + push(warn, Warning::Damaged); + } + let end = declared.min(b.len()); + let mut out = Vec::new(); + // (position, end, depth) of the lists still to walk; a list's children go before the rest of + // the list that holds it. + let mut stack = vec![(12usize, end, 0usize)]; + while let Some((mut pos, end, depth)) = stack.pop() { + while pos.saturating_add(8) <= end { + let Some(id) = Rd::at(b, pos).fourcc() else { break }; + if !is_id(&id) { + match resync(b, pos, end) { + Some(next) => { + pos = next; + continue; + } + None => { + push(warn, Warning::Damaged); + break; + } + } + } + budget.take_chunk()?; + let size = u32_at(b, pos + 4).map_or(0, |s| s as usize); + let start = pos + 8; + let stop = start.saturating_add(size); + if stop > end { + // Stray bytes that happen to start with four letters give a length past the list: + // look for the next chunk id after them. A chunk the reader uses is kept, cut at + // the end of the list. + if !READ_IDS.contains(&id) + && let Some(next) = resync(b, pos, end) + { + pos = next; + continue; + } + push(warn, Warning::Damaged); + } + let stop = stop.min(end); + let next = stop.saturating_add(size & 1); + if id == LIST { + if depth >= budget.limits.depth { + push(warn, Warning::TooDeep); + pos = next; + continue; + } + stack.push((next, end, depth)); + stack.push((start + 4, stop, depth + 1)); + break; + } + if let Some(body) = b.get(start..stop) { + out.push(Chunk { id, body, start }); + } + pos = next; + } + } + Ok(out) +} + +/// Is `t` a chunk id: an ASCII letter, then three ASCII letters, digits or spaces (R53)? +fn is_id(t: &[u8]) -> bool { + matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ')) +} + +/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`] +/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list +/// that ends at `end` (R53). +fn resync(b: &[u8], pos: usize, end: usize) -> Option { + let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end); + let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p))); + (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p)) +} + +/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs +/// past it (R55). +fn list_end(b: &[u8], mut pos: usize) -> usize { + while let Some(&tag) = b.get(pos) { + if tag == 0xff { + return pos + 1; + } + match Rd::at(b, pos + 1).u16().map(usize::from).filter(|n| *n >= 3) { + Some(n) if pos + n <= b.len() => pos += n, + _ => break, + } + } + b.len() +} + +/// The data of field `tag` in the field list `b` (R55). +fn field(b: &[u8], tag: u8) -> Option<&[u8]> { + let mut pos = 0; + while let Some(&t) = b.get(pos) { + if t == 0xff { + return None; + } + let n = usize::from(Rd::at(b, pos + 1).u16()?); + let data = b.get(pos + 3..pos.checked_add(n)?).filter(|_| n >= 3)?; + if t == tag { + return Some(data); + } + pos += n; + } + None +} + +/// The field lists of a table: a u16 count, then that many lists (R55). Each entry counts toward +/// the chunk limit. +fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result, Error> { + let count = Rd::new(d).u16().map_or(0, usize::from); + let mut out = Vec::new(); + let mut pos = 2; + for _ in 0..count { + if pos >= d.len() { + break; + } + budget.take_chunk()?; + let end = list_end(d, pos); + out.push(d.get(pos..end).unwrap_or_default()); + pos = end; + } + Ok(out) +} + +impl Tables { + /// The first chunk of each table; a table that is missing is empty. + fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec) -> Result { + let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body); + // A color record of field 10 holds a property list as a `.cdr` fill does (R56). + let record = layout::for_version(1300); + let mut t = Tables::default(); + for e in entries(first(b"rclr"), budget)? { + t.colors.push(color(e, record.as_ref(), warn)); + } + for e in entries(first(b"rpen"), budget)? { + t.pens.push(field(e, 1).and_then(|f| Rd::new(f).u32()).map(|w| f64::from(w) * unit)); + } + for e in entries(first(b"rott"), budget)? { + t.line_types.push(field(e, 1).and_then(|f| Some((*f.first()?, f.get(1).copied().unwrap_or(0))))); + } + for e in entries(first(b"rdot"), budget)? { + let mut r = Rd::new(field(e, 1).unwrap_or_default()); + let n = r.u16().map_or(0, usize::from); + let mut pattern: Vec = (0..n).map_while(|_| r.u16()).collect(); + // A pattern of zero lengths draws as a solid line, as in a `.cdr` outline (R48). + if pattern.iter().all(|x| *x == 0) { + pattern.clear(); + } + t.dashes.push(pattern); + } + for e in entries(first(b"rotl"), budget)? { + t.outlines.push(field(e, 1).and_then(|f| { + let mut r = Rd::new(f); + Some([r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?]) + })); + } + // Arrowhead pairs are plain u16 pairs after the count, not field lists (R59). + let mut r = Rd::new(first(b"rota")); + let n = r.u16().map_or(0, usize::from); + for _ in 0..n { + let Some(pair) = r.u16().zip(r.u16()) else { break }; + budget.take_chunk()?; + t.arrowheads.push(pair); + } + Ok(t) + } + + /// Entry `index` (1-based) of `list`, or `None` with a warning when there is none. + fn get(list: &[Option], index: u16, warn: &mut Vec) -> Option { + let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten(); + if found.is_none() { + push(warn, Warning::Damaged); + } + found + } + + fn color(&self, index: u16, warn: &mut Vec) -> Color { + Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) + } + + /// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58). + fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec) -> Option { + let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?; + let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0)); + if flags & 1 != 0 { + return None; + } + let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0); + let mut dashes = Vec::new(); + if flags & 4 != 0 { + let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i)); + match stored { + Some(d) if d.is_empty() => {} + Some(d) if budget.take_dashes(d.len()) => dashes = d.iter().map(|x| f64::from(*x)).collect(), + Some(_) => push(warn, Warning::TooDeep), + None => push(warn, Warning::Damaged), + } + } + if usize::from(arrows).checked_sub(1).and_then(|i| self.arrowheads.get(i)).is_some_and(|(s, e)| *s != 0 || *e != 0) { + push(warn, Warning::Arrowheads); + } + Some(Outline { + width, + color: self.color(color, warn), + cap: match caps_join & 0x0f { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }, + join: match caps_join >> 4 { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }, + dashes, + behind_fill: flags & 8 != 0, + scale_with: flags & 16 != 0, + }) + } +} + +/// A color entry (R56): the property list of field 10 when there is one, else the model and +/// palette bytes of field 1 and the values of field 2. Colors in other models read as black with a +/// warning. +fn color(e: &[u8], record: Option<&Profile>, warn: &mut Vec) -> Option { + if let (Some(f), Some(p)) = (field(e, 10), record) { + let mut r = Rd::new(f); + let len = r.u32()? as usize; + return property_color(r.bytes(len.min(r.left()))?, p, warn); + } + let model = *field(e, 1)?.first()?; + let v = field(e, 2)?; + let byte = |i: usize| v.get(i).map(|b| f32::from(*b)); + let pct = |i: usize| byte(i).map(|x| (x / 100.0).clamp(0.0, 1.0)); + let full = |i: usize| byte(i).map(|x| x / 255.0); + Some(match model { + 2 => Color::Cmyk([pct(0)?, pct(1)?, pct(2)?, pct(3)?]), + 3 => Color::Cmyk([full(0)?, full(1)?, full(2)?, full(3)?]), + 4 => Color::Cmyk([full(0)?, full(1)?, full(2)?, 0.0]), + 5 => Color::Rgb([full(0)?, full(1)?, full(2)?]), + 9 => Color::Gray(1.0 - full(0)?), + _ => { + push(warn, Warning::UnknownColors); + Color::Rgb([0.0; 3]) + } + }) +} + +/// The objects of one layer while it is read: the layer's own list, then one list for each group +/// left open. +struct LayerRead { + name: String, + lists: Vec>, +} + +impl LayerRead { + /// The layer, its open groups closed. Lists are drawn back to front (R60), and the model holds + /// them front to back. + fn finish(mut self) -> Layer { + while self.lists.len() > 1 { + close_group(&mut self.lists); + } + let mut objects = self.lists.pop().unwrap_or_default(); + objects.reverse(); + Layer { name: self.name, kind: LayerKind::Drawing, flags: Default::default(), objects, guides: Vec::new() } + } +} + +/// Close the innermost open group of `lists` into the one that holds it. +fn close_group(lists: &mut Vec>) { + if lists.len() < 2 { + return; + } + let mut objects = lists.pop().unwrap_or_default(); + objects.reverse(); + if let Some(top) = lists.last_mut() { + top.push(Object::Group { objects, flags: Default::default() }); + } +} + +/// The reading of one page chunk. +struct PageRead<'t, 'b> { + tables: &'t Tables, + unit: f64, + budget: &'b mut Budget, + warn: &'b mut Vec, + size: Option<(f64, f64)>, + /// The page's center in the file's coordinates when the page takes its size from the + /// drawing's bounds; points are moved by it so the art lies on the page. + center: (f64, f64), + layers: Vec, + open: Option, + /// Groups nested past the depth limit that are still open; their content is left out. + skipped: usize, +} + +impl<'t, 'b> PageRead<'t, 'b> { + fn new(tables: &'t Tables, unit: f64, budget: &'b mut Budget, warn: &'b mut Vec) -> Self { + PageRead { tables, unit, budget, warn, size: None, center: (0.0, 0.0), layers: Vec::new(), open: None, skipped: 0 } + } + + /// The instructions of a page chunk: a u16 size counting the whole instruction and an i16 code, + /// or 0xFFFF, a u32 size and the code; then the code's field lists (R60). + fn read(mut self, c: &Chunk) -> Result { + let d = c.body; + let mut pos = 0usize; + while pos.saturating_add(4) <= d.len() { + self.budget.take_chunk()?; + let mut r = Rd::at(d, pos); + let (size, code, head) = match r.u16() { + Some(0xFFFF) => match (r.u32(), r.i16()) { + (Some(size), Some(code)) => (size as usize, code, 8), + _ => break, + }, + Some(size) => match r.i16() { + Some(code) => (usize::from(size), code, 4), + None => break, + }, + None => break, + }; + if size < head { + push(self.warn, Warning::Damaged); + break; + } + let end = pos.saturating_add(size); + if end > d.len() { + push(self.warn, Warning::Damaged); + } + let body = d.get(pos + head..end.min(d.len())).unwrap_or_default(); + if code == JUMP { + // Field 1 is the file offset the instructions go on from; the bytes passed over + // hold the page's images (R60). + let target = field(body, 1).and_then(|f| Rd::new(f).u32()).and_then(|t| (t as usize).checked_sub(c.start)); + pos = target.filter(|t| *t >= end && *t <= d.len()).unwrap_or(end); + if pos > end { + push(self.warn, Warning::UnsupportedObjects); + } + continue; + } + self.instruction(code, body); + pos = end; + } + if pos < d.len() { + // An instruction whose head runs past the page was not read. + push(self.warn, Warning::Damaged); + } + self.close_layer(); + // A layer that holds nothing (the special layers every sample file lists empty) is left + // out. The file lists layers back to front. + let mut layers = self.layers; + layers.retain(|l| !l.objects.is_empty()); + layers.reverse(); + Ok(Page { size: self.size, layers }) + } + + fn instruction(&mut self, code: i16, body: &[u8]) { + match code { + BEGIN_PAGE => { + // Field 4: the page's width and height (R61). + let mut r = Rd::new(field(body, 4).unwrap_or_default()); + if let (Some(w), Some(h)) = (r.u32(), r.u32()) { + let (w, h) = (f64::from(w) * self.unit, f64::from(h) * self.unit); + self.size = (w > 0.0 && h > 0.0).then_some((w, h)); + } + if self.size.is_none() { + self.size_from_bounds(field(body, 1).unwrap_or_default()); + } + } + BEGIN_LAYER => { + self.close_layer(); + // A layer without a name is left unnamed, as in a `.cdr` drawing. + let name = self.layer_name(body).unwrap_or_default(); + self.open = Some(LayerRead { name, lists: vec![Vec::new()] }); + } + END_LAYER => self.close_layer(), + BEGIN_GROUP => { + let open = self.layer().lists.len(); + if self.skipped > 0 || open > self.budget.limits.depth { + self.skipped += 1; + push(self.warn, Warning::TooDeep); + } else if self.budget.take_object() { + self.layer().lists.push(Vec::new()); + } else { + // Past the object limit the group's content joins the group that holds it. + self.skipped += 1; + push(self.warn, Warning::TooDeep); + } + } + END_GROUP => { + if self.skipped > 0 { + self.skipped -= 1; + } else { + close_group(&mut self.layer().lists); + } + } + CURVE if self.skipped == 0 => { + if let Some(shape) = self.curve(body) { + if self.budget.take_object() { + if let Some(list) = self.layer().lists.last_mut() { + list.push(Object::Shape(Box::new(shape))); + } + } else { + push(self.warn, Warning::TooDeep); + } + } + } + BEGIN_TEXT | GLYPH_RUN | ELLIPSE | RECTANGLE | IMAGE | ADD_CLIP => push(self.warn, Warning::UnsupportedObjects), + // These and the other codes (text styles and characters, color contexts) draw nothing + // on their own. + END_PAGE | END_TEXT | REMOVE_CLIP => {} + _ => {} + } + } + + /// A page without a size of its own is sized to the drawing's bounds in field 1 (R61): a u16 + /// page number, a u32 of flags, then the left, top, right and bottom edges as i32 in + /// coordinate units. The page is centered on those bounds. + fn size_from_bounds(&mut self, f: &[u8]) { + let mut r = Rd::new(f); + if r.u16().is_none() || r.u32().is_none() { + return; + } + let (Some(l), Some(t), Some(rt), Some(b)) = (r.i32(), r.i32(), r.i32(), r.i32()) else { + return; + }; + let (l, t, rt, b) = (f64::from(l) * self.unit, f64::from(t) * self.unit, f64::from(rt) * self.unit, f64::from(b) * self.unit); + let (w, h) = ((rt - l).abs(), (t - b).abs()); + if w > 0.0 && h > 0.0 { + self.size = Some((w, h)); + self.center = ((l + rt) / 2.0, (t + b) / 2.0); + } + } + + /// The open layer, or a new unnamed one when objects come before any layer begins. + fn layer(&mut self) -> &mut LayerRead { + self.open.get_or_insert_with(|| LayerRead { name: String::new(), lists: vec![Vec::new()] }) + } + + fn close_layer(&mut self) { + self.skipped = 0; + if let Some(l) = self.open.take() { + self.layers.push(l.finish()); + } + } + + /// A layer's name: field 4 as a u32 count and UTF-16 units, else field 1 from byte 12 as a + /// u16 count and 8-bit characters (R62). + fn layer_name(&mut self, body: &[u8]) -> Option { + // A field 4 that can't be read leaves the name to field 1. + let wide = field(body, 4).and_then(|f| { + let mut r = Rd::new(f); + let n = (r.u32()? as usize).min(MAX_NAME_UNITS).min(r.left() / 2); + Some((r.bytes(n * 2)?, layout::for_version(1200)?)) + }); + if let Some((units, l)) = wide { + let s = name(units, &l, self.warn); + if !s.trim().is_empty() { + return Some(s); + } + } + let mut r = Rd::at(field(body, 1)?, 12); + let n = usize::from(r.u16()?).min(r.left()); + let s = name(r.bytes(n)?, &layout::for_version(1100)?, self.warn); + (!s.trim().is_empty()).then_some(s) + } + + /// A curve (R62): field 1 its rendering attributes, field 2 a u16 point count, the points (i32 + /// x and y) and one type byte for each. Points are from the page's center, y up. + fn curve(&mut self, body: &[u8]) -> Option { + let mut r = Rd::new(field(body, 2).unwrap_or_default()); + let Some(count) = r.u16().map(usize::from) else { + // A curve without its points is lost. + push(self.warn, Warning::Damaged); + return None; + }; + // `stored` points are read, so the type bytes are found after all of them, and the first + // `n`, those that have a type byte, are kept. When the field holds every point, a short + // field has lost type bytes. When it holds whole points and their types for fewer points, + // the count is too large. Otherwise the field lost points, and its type bytes can't be + // found: the curve is lost. + let left = r.left(); + let (stored, n) = match count.checked_mul(8).filter(|c| *c <= left) { + Some(c) => (count, count.min(left - c)), + None if left.is_multiple_of(9) => (left / 9, left / 9), + None => { + push(self.warn, Warning::Damaged); + return None; + } + }; + if n < count { + push(self.warn, Warning::Damaged); + } + if !self.budget.take_coordinates(stored) { + push(self.warn, Warning::TooDeep); + return None; + } + let mut points = Vec::with_capacity(stored); + for _ in 0..stored { + let (x, y) = (f64::from(r.i32()?) * self.unit, f64::from(r.i32()?) * self.unit); + points.push(Pt { x: x - self.center.0, y: y - self.center.1 }); + } + points.truncate(n); + let path = path_of(&points, r.bytes(n)?); + if path.subpaths.is_empty() { + return None; + } + let (fill, outline) = self.attributes(field(body, 1).unwrap_or_default()); + Some(Shape::new(Geometry::Path(path), Matrix::IDENTITY, fill, outline)) + } + + /// Rendering attributes (R63): a mask (1 fill, 2 outline, 4 lens), then a field list for the + /// fill and one for the outline when the mask names them. + fn attributes(&mut self, a: &[u8]) -> (Option, Option) { + let Some(&mask) = a.first() else { return (None, None) }; + let mut pos = 1; + let mut fill = None; + if mask & 1 != 0 { + let end = list_end(a, pos); + let list = a.get(pos..end).unwrap_or_default(); + pos = end; + // Field 1: the fill type (u16), then its own field list; type 1, uniform, names its + // color in field 1. + let v = field(list, 1).unwrap_or_default(); + match Rd::new(v).u16() { + Some(0) | None => {} + Some(1) => { + let index = field(v.get(2..).unwrap_or_default(), 1).and_then(|c| Rd::new(c).u16()); + fill = Some(match index { + Some(i) => self.tables.color(i, self.warn), + None => { + push(self.warn, Warning::Damaged); + Color::Rgb([0.0; 3]) + } + }); + } + Some(_) => push(self.warn, Warning::UnsupportedFills), + } + } + let mut outline = None; + if mask & 2 != 0 { + let list = a.get(pos..list_end(a, pos)).unwrap_or_default(); + match field(list, 1).and_then(|f| Rd::new(f).u16()) { + Some(i) => outline = self.tables.outline(i, self.budget, self.warn), + None => push(self.warn, Warning::Damaged), + } + } + if mask & 4 != 0 { + push(self.warn, Warning::Lenses); + } + // A canvas (8) or a container (16) is not read. + if mask & (8 | 16) != 0 { + push(self.warn, Warning::UnsupportedObjects); + } + (fill, outline) + } +} diff --git a/crates/cdr/src/geometry.rs b/crates/cdr/src/geometry.rs new file mode 100644 index 0000000000..61b776f23a --- /dev/null +++ b/crates/cdr/src/geometry.rs @@ -0,0 +1,455 @@ +//! The coordinates argument (30) of each object type read as geometry: curves (R16), rectangles +//! (R15), ellipses and arcs (R17) and polygons (R18). + +use std::f64::consts::PI; + +use crate::Warning; +use crate::bytes::Rd; +use crate::layout::Profile; +use crate::limits::Budget; +use crate::model::{Geometry, Path, Pt, Segment, SubPath}; +use crate::records::{angle, coord}; +use crate::riff::push; + +/// The most sides a polygon record may give (VectorCraft's own bound). +const MAX_POLYGON_SIDES: u32 = 1000; +/// The base curve of a polygon lies on a circle of 1000 mm (R18), in points. +const POLYGON_UNIT_RADIUS: f64 = 1000.0 / 25.4 * 72.0; + +/// What a point type byte asks for (R16): bits 7 and 6. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Op { + Move, + Line, + Curve, + Control, +} + +fn op(t: u8) -> Op { + match t >> 6 { + 0 => Op::Move, + 1 => Op::Line, + 2 => Op::Curve, + _ => Op::Control, + } +} + +/// Bit 3 closes the subpath (R16). +const CLOSES: u8 = 0x08; + +/// A point list (R16): the count, the points, then one type byte each. The count is a u32 from +/// version 6 and a u16 followed by another u16 before it (R39). It is held to what the bytes hold; +/// `None` when the points are past the budget. +pub(crate) fn point_list(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + let count = if p.short { + let count = usize::from(r.u16()?); + r.skip(2)?; + count + } else { + r.u32()? as usize + }; + points(b, r, count, p, budget, warn) +} + +/// A path record (object type 0x25, R30): 4 bytes, two u16 counts whose sum is the point count, 16 +/// bytes, then the points and their type bytes as in a point list. +pub(crate) fn path_record(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + r.skip(4)?; + let count = usize::from(r.u16()?) + usize::from(r.u16()?); + r.skip(16)?; + points(b, r, count, p, budget, warn) +} + +/// `count` points from `r` over `b`, then their type bytes. A list cut short is read two ways: as +/// all `count` points with the type bytes after them, and as the points and type bytes the bytes +/// hold split evenly. The reading that keeps more points with a type byte wins, the first on a tie. +fn points(b: &[u8], mut r: Rd, count: usize, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let each = 2 * p.word(); + let left = r.left(); + let split = (left / (each + 1)).min(count); + let whole = count.checked_mul(each).filter(|len| *len <= left).map(|len| (left - len).min(count)); + let stored = match whole { + Some(typed) if typed >= split => count, + _ => split, + }; + let types = b.get(r.pos() + stored * each..)?; + let n = stored.min(types.len()); + if count > n { + push(warn, Warning::Damaged); + } + if !budget.take_coordinates(n) { + push(warn, Warning::TooDeep); + return None; + } + let mut points = Vec::with_capacity(n); + for _ in 0..n { + points.push(Pt { x: coord(&mut r, p)?, y: coord(&mut r, p)? }); + } + Some(path_of(&points, types)) +} + +/// The subpaths that points and their type bytes draw. +pub(crate) fn path_of(points: &[Pt], types: &[u8]) -> Path { + let mut subpaths = Vec::new(); + let mut cur: Option = None; + // The last two control points: a curve end uses only those. + let mut controls: Vec = Vec::with_capacity(2); + for (&pt, &t) in points.iter().zip(types) { + let o = op(t); + if o == Op::Control { + if controls.len() == 2 { + controls.remove(0); + } + controls.push(pt); + continue; + } + if o == Op::Move || cur.is_none() { + subpaths.extend(cur.take()); + cur = Some(SubPath { start: pt, segments: Vec::new(), closed: t & CLOSES != 0 && o == Op::Move }); + controls.clear(); + if o == Op::Move { + continue; + } + } + let Some(sp) = cur.as_mut() else { continue }; + let seg = match (o, controls.as_slice()) { + (Op::Curve, [c1, c2]) => Segment::Cubic(*c1, *c2, pt), + _ => Segment::Line(pt), + }; + controls.clear(); + sp.segments.push(seg); + if t & CLOSES != 0 { + sp.closed = true; + } + } + subpaths.extend(cur); + // A closed subpath with no segments, or an open one with none, draws nothing. + subpaths.retain(|s| !s.segments.is_empty()); + Path { subpaths } +} + +/// A rectangle record (R15): width, height, then one corner radius for every corner, four from +/// version 9. +pub(crate) fn rect(b: &[u8], p: &Profile) -> Option { + if p.f64_rect { + return rect_f64(b, p); + } + let mut r = Rd::new(b); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let first = coord(&mut r, p)?.abs(); + let mut radii = [first; 4]; + if p.four_radii { + for slot in radii.iter_mut().skip(1) { + *slot = coord(&mut r, p)?.abs(); + } + } + Some(Geometry::Rect { w, h, radii }) +} + +/// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale +/// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the +/// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter +/// side; with it set the radius is in inches. A corner is held to half the shorter side, and +/// sizes to the range of the 32-bit coordinates of earlier versions. +fn rect_f64(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit()); + let (w, h) = (size(r.f64()?)?, size(r.f64()?)?); + r.skip(8 + 8)?; + let inches = r.u8()? != 0; + r.skip(7)?; + let short = w.abs().min(h.abs()); + let mut radii = [0.0; 4]; + for (k, slot) in radii.iter_mut().enumerate() { + if k > 0 { + r.skip(16)?; + } + let v = r.f64()?.abs(); + let radius = if inches { v * 72.0 } else { v * short / 2.0 }; + *slot = radius.min(short / 2.0); + } + Some(Geometry::Rect { w, h, radii }) +} + +/// An ellipse record (R17): the box's width and height, the start and end angles and whether +/// the arc closes through the centre. Equal angles make a whole ellipse. +pub(crate) fn ellipse(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let (a1, a2) = (angle(&mut r, p)?, angle(&mut r, p)?); + let pie = if p.short { r.u16()? != 0 } else { r.u32()? != 0 }; + let sweep = (a2 - a1).rem_euclid(360.0); + if sweep.abs() < 1e-9 { + return Some(Geometry::Ellipse { w, h }); + } + Some(Geometry::Path(arc(w, h, a1, sweep, pie))) +} + +/// The arc of the ellipse in the box from the origin to (`w`, `h`), from `start` degrees through +/// `sweep` degrees, in the ellipse's own axes; a pie runs from the centre and closes there. The +/// radii are half the size, and a negative width or height points its axis the other way (R17), so +/// with a negative height 0 to 180 degrees is the half below the centre. +fn arc(w: f64, h: f64, start: f64, sweep: f64, pie: bool) -> Path { + let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0); + let at = |t: f64| Pt { x: cx + rx * t.cos(), y: cy + ry * t.sin() }; + let tangent = |t: f64| Pt { x: -rx * t.sin(), y: ry * t.cos() }; + let pieces = (sweep / 90.0).ceil().max(1.0) as usize; + let step = sweep.to_radians() / pieces as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let t0 = start.to_radians(); + let mut segments = Vec::with_capacity(pieces + 2); + if pie { + segments.push(Segment::Line(at(t0))); + } + for i in 0..pieces { + let (a, b) = (t0 + step * i as f64, t0 + step * (i + 1) as f64); + let (p0, p1, d0, d1) = (at(a), at(b), tangent(a), tangent(b)); + segments.push(Segment::Cubic(Pt { x: p0.x + k * d0.x, y: p0.y + k * d0.y }, Pt { x: p1.x - k * d1.x, y: p1.y - k * d1.y }, p1)); + } + let start = if pie { Pt { x: cx, y: cy } } else { at(t0) }; + Path { subpaths: vec![SubPath { start, segments, closed: pie }] } +} + +/// A polygon (R18): its base curve, one side of the outline on a circle of 1000 mm with its top +/// vertex first, copied once per side and turned clockwise each time by the vertices the side +/// spans, then scaled by (`rx`, `ry`) and moved to the centre the polygon argument (11000) gives. +/// A star whose sides skip vertices draws as one outline, or as several when the side count and +/// the step share a factor. +pub(crate) fn polygon(base: &Path, b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + if !p.tagged { + r.skip(4)?; + } + let sides = r.u32()?; + // The next point: the first field, or the second when the first is 0 or 1. + let (first, second) = (r.u32()?, r.u32()?); + let next = if first > 1 { first } else { second }; + if p.tagged { + r.skip(4)?; + } + let (rx, ry) = (r.f64()?, r.f64()?); + let (cx, cy) = (coord(&mut r, p)?, coord(&mut r, p)?); + let side = base.subpaths.first()?; + if !(1..=MAX_POLYGON_SIDES).contains(&sides) { + push(warn, Warning::Damaged); + return None; + } + if !budget.take_coordinates(side.segments.len().saturating_mul(3).saturating_mul(sides as usize)) { + push(warn, Warning::TooDeep); + return None; + } + // The base curve's own unit radius, measured from its first point, keeps the scale right + // whatever unit the file's coordinates are in. + let unit = side.start.x.hypot(side.start.y); + let unit = if unit > 0.0 { unit } else { POLYGON_UNIT_RADIUS }; + let place = |q: Pt, turn: f64| { + let (s, c) = turn.sin_cos(); + let (x, y) = (q.x * c - q.y * s, q.x * s + q.y * c); + Pt { x: x / unit * POLYGON_UNIT_RADIUS * rx + cx, y: y / unit * POLYGON_UNIT_RADIUS * ry + cy } + }; + let step = side_step(side, sides, next); + let outlines = gcd(sides, step); + let each = sides / outlines; + let angle = |k: u32| -2.0 * PI * f64::from(k % sides) / f64::from(sides); + let mut subpaths = Vec::with_capacity(outlines as usize); + for o in 0..outlines { + let mut segments = Vec::with_capacity(side.segments.len() * each as usize); + for j in 0..each { + let turn = angle(o + j * step); + segments.extend(side.segments.iter().map(|s| match *s { + Segment::Line(a) => Segment::Line(place(a, turn)), + Segment::Cubic(a, b, c) => Segment::Cubic(place(a, turn), place(b, turn), place(c, turn)), + })); + } + subpaths.push(SubPath { start: place(side.start, angle(o)), segments, closed: true }); + } + Some(Geometry::Path(Path { subpaths })) +} + +/// How many vertices the base side moves on from its first point (R18): the vertex its last +/// point lies at, clockwise; else the next-point field when it names one; else 1. +fn side_step(side: &SubPath, sides: u32, next: u32) -> u32 { + let field = if (1..sides).contains(&next) { next } else { 1 }; + let Some(end) = side.segments.last().map(|s| match *s { + Segment::Line(e) | Segment::Cubic(_, _, e) => e, + }) else { + return field; + }; + let (r0, r1) = (side.start.x.hypot(side.start.y), end.x.hypot(end.y)); + if !(r0 > 0.0 && (r1 - r0).abs() <= r0 * 1e-3) { + return field; + } + let turned = (side.start.y.atan2(side.start.x) - end.y.atan2(end.x)) / (2.0 * PI / f64::from(sides)); + let k = turned.round(); + if !k.is_finite() || (turned - k).abs() > 1e-3 { + return field; + } + match k.rem_euclid(f64::from(sides)) as u32 { + 0 => field, + k => k, + } +} + +fn gcd(a: u32, b: u32) -> u32 { + let (mut a, mut b) = (a, b); + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pt(x: f64, y: f64) -> Pt { + Pt { x, y } + } + + #[test] + fn type_bytes_make_moves_lines_curves_and_closes() { + let points = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0), pt(20.0, 20.0), pt(30.0, 20.0)]; + // move (closed), line, control, control, curve end closing; move, line. + let types = [0x08, 0x40, 0xC0, 0xC0, 0x88, 0x00, 0x40]; + let path = path_of(&points, &types); + assert_eq!(path.subpaths.len(), 2); + let first = &path.subpaths[0]; + assert!(first.closed); + assert_eq!(first.segments, vec![Segment::Line(pt(10.0, 0.0)), Segment::Cubic(pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0))]); + assert!(!path.subpaths[1].closed); + } + + #[test] + fn a_point_list_short_of_type_bytes_reads_them_after_all_its_points() { + let p = crate::layout::for_version(1300).unwrap_or_else(|| panic!("profile")); + // Three points, (0, 0), (1 inch, 0) and (0, 0), and type bytes for the first two only. + let mut b = 3u32.to_le_bytes().to_vec(); + for v in [0i32, 0, 254_000, 0, 0, 0] { + b.extend(v.to_le_bytes()); + } + b.extend([0x00, 0x40]); + let mut warn = vec![]; + let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path")); + assert_eq!(path.subpaths.len(), 1); + assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(72.0, 0.0))]); + assert_eq!(warn, vec![Warning::Damaged]); + // A count past the points the bytes hold keeps the points that have a type byte. + // Eight points and their eight type bytes take the bytes of nine points. + let mut b = 9u32.to_le_bytes().to_vec(); + for i in 0..8 { + b.extend((i * 254_000i32).to_le_bytes()); + b.extend(0i32.to_le_bytes()); + } + b.extend([0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40]); + let mut warn = vec![]; + let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path")); + assert_eq!(path.subpaths[0].segments.len(), 7); + assert!(matches!(path.subpaths[0].segments[6], Segment::Line(end) if (end.x - 504.0).abs() < 1e-9 && end.y == 0.0)); + assert_eq!(warn, vec![Warning::Damaged]); + } + + #[test] + fn a_run_of_control_points_keeps_the_last_two() { + let points: Vec = (0..7).map(|i| pt(f64::from(i), 0.0)).collect(); + let path = path_of(&points, &[0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80]); + assert_eq!(path.subpaths[0].segments, vec![Segment::Cubic(pt(4.0, 0.0), pt(5.0, 0.0), pt(6.0, 0.0))]); + } + + #[test] + fn a_curve_end_without_two_controls_is_a_line() { + let path = path_of(&[pt(0.0, 0.0), pt(1.0, 1.0)], &[0x00, 0x80]); + assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(1.0, 1.0))]); + } + + #[test] + fn a_quarter_arc_ends_on_the_ellipse() { + let p = arc(20.0, 10.0, 0.0, 90.0, false); + let sp = &p.subpaths[0]; + assert_eq!(sp.start, pt(20.0, 5.0)); + let Some(Segment::Cubic(_, _, end)) = sp.segments.last() else { panic!("no curve") }; + assert!((end.x - 10.0).abs() < 1e-9 && (end.y - 10.0).abs() < 1e-9); + let pie = arc(20.0, 10.0, 0.0, 180.0, true); + assert!(pie.subpaths[0].closed && pie.subpaths[0].start == pt(10.0, 5.0)); + } + + #[test] + fn a_negative_height_turns_the_arc_below_the_centre() { + let p = arc(20.0, -10.0, 0.0, 180.0, false); + let sp = &p.subpaths[0]; + assert_eq!(sp.start, pt(20.0, -5.0)); + let Some(Segment::Cubic(_, _, mid)) = sp.segments.first() else { panic!("no curve") }; + assert!((mid.x - 10.0).abs() < 1e-9 && (mid.y + 10.0).abs() < 1e-9, "{mid:?}"); + } + + /// A version 13 polygon argument: `sides`, the two next-point fields, then rx = ry = 1 at the + /// origin. + fn polygon_arg(sides: u32, first: u32, second: u32) -> Vec { + let mut b = Vec::new(); + for v in [sides, first, second, 0] { + b.extend(v.to_le_bytes()); + } + b.extend(1.0f64.to_le_bytes()); + b.extend(1.0f64.to_le_bytes()); + b.extend([0; 8]); + b + } + + /// Vertex `k` of `sides`, counted clockwise from the top, on the base circle. + fn vertex(k: u32, sides: u32) -> Pt { + let a = PI / 2.0 - 2.0 * PI * f64::from(k) / f64::from(sides); + pt(POLYGON_UNIT_RADIUS * a.cos(), POLYGON_UNIT_RADIUS * a.sin()) + } + + fn ends(sp: &SubPath) -> Vec { + sp.segments + .iter() + .map(|s| match *s { + Segment::Line(e) | Segment::Cubic(_, _, e) => e, + }) + .collect() + } + + fn close(a: &[Pt], b: &[Pt]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.x - q.x).abs() < 1e-6 && (p.y - q.y).abs() < 1e-6) + } + + fn star(sides: u32, step: u32, first: u32, second: u32) -> Path { + let p = crate::layout::for_version(1300).unwrap(); + let base = Path { subpaths: vec![SubPath { start: vertex(0, sides), segments: vec![Segment::Line(vertex(step, sides))], closed: false }] }; + let mut budget = Budget::new(crate::Limits::default()); + let Some(Geometry::Path(path)) = polygon(&base, &polygon_arg(sides, first, second), &p, &mut budget, &mut vec![]) else { + panic!("no polygon") + }; + path + } + + #[test] + fn a_star_whose_sides_skip_a_vertex_chains_its_points() { + // {5/2}: each side runs two vertices on, so the outline visits 2, 4, 1, 3 and 0. + let path = star(5, 2, 2, 0); + assert_eq!(path.subpaths.len(), 1); + let want: Vec = [2, 4, 1, 3, 0].iter().map(|&k| vertex(k, 5)).collect(); + assert!(close(&ends(&path.subpaths[0]), &want), "{:?}", ends(&path.subpaths[0])); + // The base side alone tells the step when the field doesn't. + assert!(close(&ends(&star(5, 2, 0, 0).subpaths[0]), &want)); + } + + #[test] + fn a_star_sharing_a_factor_with_its_sides_draws_one_outline_for_each() { + // {6/2}: two triangles, 0-2-4 and 1-3-5. + let path = star(6, 2, 0, 2); + assert_eq!(path.subpaths.len(), 2); + assert!(close(&ends(&path.subpaths[0]), &[vertex(2, 6), vertex(4, 6), vertex(0, 6)])); + assert!(close(&[path.subpaths[1].start], &[vertex(1, 6)])); + assert!(close(&ends(&path.subpaths[1]), &[vertex(3, 6), vertex(5, 6), vertex(1, 6)])); + } + + #[test] + fn a_plain_polygon_turns_one_vertex_for_each_side() { + let path = star(4, 1, 0, 1); + assert_eq!(path.subpaths.len(), 1); + assert!(close(&ends(&path.subpaths[0]), &[1, 2, 3, 0].map(|k| vertex(k, 4)))); + } +} diff --git a/crates/cdr/src/inline.rs b/crates/cdr/src/inline.rs new file mode 100644 index 0000000000..3d5214f136 --- /dev/null +++ b/crates/cdr/src/inline.rs @@ -0,0 +1,230 @@ +//! What a version 3 object holds as arguments where later versions name records: its transforms +//! (argument 100, R33), its fill (argument 20, R34) and its outline (argument 10, R35). + +use crate::bytes::Rd; +use crate::layout::Profile; +use crate::model::{Cap, Color, Join, Matrix, Outline}; +use crate::records::{self, angle, coord}; +use crate::riff::push; +use crate::{Limits, Warning}; + +/// Transform entry types (R33): a matrix, and an envelope. +const MATRIX: u16 = 0x8c; +const ENVELOPE: u16 = 0x14; +/// The bytes of one transform entry (R33). +const ENTRY: usize = 10; +/// The bytes an outline keeps for its dashes, one byte each (R35). +const DASH_AREA: usize = 10; + +/// The transforms of one object or group. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Placement { + /// The matrices composed in file order, in points. + pub(crate) matrix: Matrix, + /// An envelope bends the shape. The reader doesn't apply envelopes. + pub(crate) envelope: bool, +} + +/// The transforms argument (R33): a u16, the entry count, then 10-byte entries of a type and, at +/// byte 6, where the entry's data starts in the argument. The count is held to the entries the +/// argument holds and to the arguments a record may have. Entries of other types are passed over. +pub(crate) fn transforms(b: &[u8], p: &Profile, limits: &Limits, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + r.skip(2)?; + let stored = usize::from(r.u16()?); + let count = stored.min(r.left() / ENTRY).min(limits.arguments); + if count < stored { + push(warn, Warning::Damaged); + } + let mut out = Placement { matrix: Matrix::IDENTITY, envelope: false }; + for _ in 0..count { + let mut e = Rd::new(r.bytes(ENTRY)?); + let kind = e.u16()?; + e.skip(4)?; + let at = usize::from(e.u16()?); + match kind { + MATRIX => out.matrix = records::fixed_matrix(&mut Rd::at(b, at), p.unit())?.after(&out.matrix), + ENVELOPE => out.envelope = true, + _ => {} + } + } + Some(out) +} + +/// The fill argument (R34): a type byte, 0 for none and 1 for a uniform fill with its color. Fills +/// of other types read as none with a warning. The outer `None` is an argument that can't be read. +pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + match r.u8()? { + 0 => Some(None), + 1 => Some(Some(records::color(&mut r, p, warn)?)), + _ => { + push(warn, Warning::UnsupportedFills); + Some(None) + } + } +} + +/// The outline argument (R35): a flags byte whose bit 0 is set when the object is outlined, the +/// width, the stretch, the nib angle, the color, 7 bytes, the dash count and 10 bytes that hold the +/// dashes, the join and the caps (u16 each), then the two arrowhead ids. An argument that ends +/// after its color gives a solid line with butt caps and miter joins. The outer `None` is an +/// argument that can't be read. +pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + if r.u8()? & 1 == 0 { + return Some(None); + } + let width = coord(&mut r, p)?.abs(); + let _stretch = r.u16()?; + let _nib = angle(&mut r, p)?; + let color = records::color(&mut r, p, warn)?; + let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false }; + let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) }; + let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) }; + if stored > DASH_AREA { + push(warn, Warning::Damaged); + } + let dashes: Vec = area.iter().take(stored).map(|d| f64::from(*d)).collect(); + if dashes.iter().any(|d| *d > 0.0) { + out.dashes = dashes; + } + out.join = match r.u16() { + Some(1) => Join::Round, + Some(2) => Join::Bevel, + _ => Join::Miter, + }; + out.cap = match r.u16() { + Some(1) => Cap::Round, + Some(2) => Cap::Square, + _ => Cap::Butt, + }; + if matches!((r.u32(), r.u32()), (Some(s), Some(e)) if s != 0 || e != 0) { + push(warn, Warning::Arrowheads); + } + Some(Some(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p3() -> Profile { + crate::layout::for_version(300).unwrap() + } + + /// A transforms argument of `entries` (type, data offset), then `data` from byte 4 + 10 for + /// each entry. + fn arg(count: u16, entries: &[(u16, u16)], data: &[i32]) -> Vec { + let mut b = vec![0, 0]; + b.extend(count.to_le_bytes()); + for (kind, at) in entries { + b.extend(kind.to_le_bytes()); + b.extend([0; 4]); + b.extend(at.to_le_bytes()); + b.extend([0; 2]); + } + b.extend(data.iter().flat_map(|v| v.to_le_bytes())); + b + } + + #[test] + fn matrices_compose_in_file_order_and_other_entries_are_passed_over() { + // Scale by 2, then move 1 inch right: entry types 0x8c, an unknown one and 0x8c. + let scale = [131072, 0, 0, 0, 131072, 0]; + let shift = [65536, 0, 1000, 0, 65536, 0]; + let b = arg(3, &[(MATRIX, 34), (0x99, 0), (MATRIX, 58)], &[scale, shift].concat()); + let mut w = vec![]; + let t = transforms(&b, &p3(), &Limits::default(), &mut w).unwrap(); + assert_eq!((t.matrix, t.envelope), (Matrix([2.0, 0.0, 0.0, 2.0, 72.0, 0.0]), false)); + assert!(w.is_empty()); + let b = arg(2, &[(MATRIX, 24), (ENVELOPE, 0)], &scale); + assert!(transforms(&b, &p3(), &Limits::default(), &mut vec![]).unwrap().envelope); + } + + #[test] + fn hostile_transform_arguments_do_not_read_past_their_bytes() { + let scale = [131072, 0, 0, 0, 131072, 0]; + // A count of 65,535 over one entry reads that entry, with the damage warning. + let b = arg(u16::MAX, &[(MATRIX, 14)], &scale); + let mut w = vec![]; + assert_eq!(transforms(&b, &p3(), &Limits::default(), &mut w).unwrap().matrix.0[0], 2.0); + assert_eq!(w, vec![Warning::Damaged]); + // A data offset past the argument, and one that leaves less than a matrix. + for at in [5000, 14 + 4] { + assert!(transforms(&arg(1, &[(MATRIX, at)], &scale), &p3(), &Limits::default(), &mut vec![]).is_none(), "{at}"); + } + // More entries than a record may have arguments. + let many: Vec<(u16, u16)> = vec![(0x99, 0); 100]; + let limits = Limits { arguments: 8, ..Limits::default() }; + let mut w = vec![]; + assert!(transforms(&arg(100, &many, &[]), &p3(), &limits, &mut w).is_some()); + assert_eq!(w, vec![Warning::Damaged]); + for len in 0..4 { + assert!(transforms(&b[..len], &p3(), &Limits::default(), &mut vec![]).is_none()); + } + } + + /// An outline argument: flags, width in 1/1000 inch, black, `dashes`, join, caps, arrowheads. + fn outline_arg(flags: u8, count: u8, dashes: &[u8], join: u16, cap: u16, heads: [u32; 2]) -> Vec { + let mut b = vec![flags]; + b.extend(28i16.to_le_bytes()); + b.extend([100, 0, 0, 0]); + b.extend([1, 0, 0, 0, 100]); + b.extend([0; 7]); + b.push(count); + let mut area = dashes.to_vec(); + area.resize(DASH_AREA, 0); + b.extend(area); + b.extend(join.to_le_bytes()); + b.extend(cap.to_le_bytes()); + b.extend(heads.iter().flat_map(|h| h.to_le_bytes())); + b + } + + #[test] + fn an_outline_reads_its_width_color_dashes_join_and_caps() { + let mut w = vec![]; + let o = outline(&outline_arg(1, 2, &[3, 1], 1, 2, [0, 0]), &p3(), &mut w).unwrap().unwrap(); + assert!((o.width - 2.016).abs() < 1e-9, "{}", o.width); + assert_eq!((o.color, o.join, o.cap, o.dashes), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Join::Round, Cap::Square, vec![3.0, 1.0])); + assert!(w.is_empty()); + // Bit 0 clear: no outline, whatever follows. + assert_eq!(outline(&outline_arg(0, 2, &[3, 1], 1, 2, [7, 0]), &p3(), &mut w), Some(None)); + assert_eq!(outline(&[0], &p3(), &mut w), Some(None)); + assert!(w.is_empty()); + outline(&outline_arg(1, 0, &[], 0, 0, [0, 9]), &p3(), &mut w).unwrap().unwrap(); + assert_eq!(w, vec![Warning::Arrowheads]); + } + + #[test] + fn a_dash_count_past_the_dash_bytes_is_held_to_them() { + let mut w = vec![]; + let o = outline(&outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]), &p3(), &mut w).unwrap().unwrap(); + assert_eq!(o.dashes.len(), DASH_AREA); + assert_eq!(w, vec![Warning::Damaged]); + // An argument that ends inside the dashes keeps a solid line; one cut before the color is + // unreadable. + let full = outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]); + assert_eq!(outline(&full[..25], &p3(), &mut vec![]).unwrap().unwrap().dashes, Vec::::new()); + assert_eq!(outline(&full[..12], &p3(), &mut vec![]).unwrap().unwrap().cap, Cap::Butt); + for len in 0..12 { + assert!(outline(&full[..len], &p3(), &mut vec![]).is_none(), "{len}"); + } + } + + #[test] + fn fills_read_none_uniform_and_other_types() { + let mut w = vec![]; + assert_eq!(fill(&[0], &p3(), &mut w), Some(None)); + assert_eq!(fill(&[1, 1, 100, 0, 0, 0], &p3(), &mut w), Some(Some(Color::Cmyk([1.0, 0.0, 0.0, 0.0])))); + assert!(w.is_empty()); + for kind in [2, 4, 6, 7, 10] { + let mut w = vec![]; + assert_eq!(fill(&[kind, 0, 0], &p3(), &mut w), Some(None)); + assert_eq!(w, vec![Warning::UnsupportedFills], "{kind}"); + } + assert_eq!(fill(&[], &p3(), &mut w), None); + assert_eq!(fill(&[1, 1, 100], &p3(), &mut w), None); + } +} diff --git a/crates/cdr/src/layout.rs b/crates/cdr/src/layout.rs new file mode 100644 index 0000000000..46c28496cf --- /dev/null +++ b/crates/cdr/src/layout.rs @@ -0,0 +1,181 @@ +//! Where the fields of each record lie, by version: one table, resolved once per file. Each field +//! names the `PROVENANCE.md` row it rests on. + +/// The layouts of one range of versions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Profile { + /// Coordinates are i16 in 1/1000 inch, record headers, counts and angles 16-bit (R5, R6, R7). + pub(crate) short: bool, + /// Bytes before the page size in `mcfg` (R10). + pub(crate) mcfg_skip: usize, + /// Bytes before a `trfd` entry's type (R8). + pub(crate) trfd_head: usize, + /// Bytes between a matrix entry's type and its six numbers (R8). + pub(crate) matrix_skip: usize, + /// Fill and outline records start with tagged records (R11, R12). + pub(crate) tagged: bool, + /// Outline: bytes after the join, after the stretch, after the nib angle and after the color + /// (R12). + pub(crate) outl_after_join: usize, + pub(crate) outl_after_stretch: usize, + pub(crate) outl_after_angle: usize, + pub(crate) outl_after_color: usize, + /// Where the start marker id lies after the first dash (R13); `None` where no source says. + pub(crate) marker_after_dash: Option, + /// Rectangles carry four corner radii, not one (R15). + pub(crate) four_radii: bool, + /// Rectangles are f64 sizes with radii as shares of half the shorter side (R29). + pub(crate) f64_rect: bool, + /// The master page flags its guides and desktop layers the way of versions 7 to 13 (R19). + pub(crate) old_master_flags: bool, + /// Object type 0x25 is a path (R30). + pub(crate) paths: bool, + /// Names are UTF-16LE, not Windows-1252 (R9). + pub(crate) utf16_names: bool, + /// An object holds its transform, fill and outline as arguments; there are no `trfd`, `fill` + /// or `outl` records (R33, R34, R35). + pub(crate) inline_styles: bool, + /// Object types count from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4 (R32). + pub(crate) types_from_zero: bool, + /// How a color is laid out (R14, R36). + pub(crate) color: ColorLayout, + /// A matrix is six i32 with its factors in 16.16 fixed point, not six f64 (R37). + pub(crate) fixed_matrix: bool, + /// `mcfg` holds 2 bytes and the page's two corners, not its width and height (R38). + pub(crate) mcfg_corners: bool, +} + +/// The layouts of a color. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ColorLayout { + /// A model byte and four value bytes (R36). + Bytes5, + /// A model u16, four u16 values and 2 bytes (R36). + Words12, + /// A model u16, a palette u16, 4 bytes and four value bytes (R14). + Record12, +} + +const fn profile(from: u16) -> Profile { + let short = from < 600; + Profile { + short, + inline_styles: from < 400, + types_from_zero: from < 400, + color: if from < 400 { + ColorLayout::Bytes5 + } else if from < 500 { + ColorLayout::Words12 + } else { + ColorLayout::Record12 + }, + fixed_matrix: from < 500, + mcfg_corners: from < 400, + mcfg_skip: if from >= 1300 { + 12 + } else if from >= 900 { + 4 + } else if from >= 600 && from < 700 { + 28 + } else { + 0 + }, + trfd_head: if from >= 1300 { 8 } else { 0 }, + matrix_skip: if short { 0 } else { 6 }, + tagged: from >= 1300, + outl_after_join: if from >= 600 && from < 1300 { 2 } else { 0 }, + outl_after_stretch: if short { 0 } else { 2 }, + outl_after_angle: if from >= 1300 { + 46 + } else if !short { + 52 + } else { + 0 + }, + outl_after_color: if short { 10 } else { 16 }, + marker_after_dash: if from >= 1300 { + Some(20) + } else if from >= 600 { + Some(22) + } else { + None + }, + four_radii: from >= 900, + f64_rect: from >= 1500, + old_master_flags: from < 1400, + paths: from >= 1000, + utf16_names: from >= 1200, + } +} + +/// The newest version read: 27, as the `vrsn` chunk names it (R1, R2). +pub(crate) const NEWEST: u16 = 2799; + +/// The first version of each range, with its layouts. Ranges start where a field moves. +const PROFILES: &[(u16, Profile)] = &[ + (300, profile(300)), + (400, profile(400)), + (500, profile(500)), + (600, profile(600)), + (700, profile(700)), + (800, profile(800)), + (900, profile(900)), + (1000, profile(1000)), + (1100, profile(1100)), + (1200, profile(1200)), + (1300, profile(1300)), + (1400, profile(1400)), + (1500, profile(1500)), + (1600, profile(1600)), +]; + +/// The oldest version of a RIFF file read: 3 (R31). Versions 1 and 2 are not RIFF files (`wl.rs`). +pub(crate) const OLDEST_RIFF: u16 = 300; + +/// The layouts of the RIFF file of `version` (hundreds; 801 is the 8.01 variant, 2430 is 24.3), or +/// `None` outside 3 to 27. +pub(crate) fn for_version(version: u16) -> Option { + if !(OLDEST_RIFF..=NEWEST).contains(&version) { + return None; + } + PROFILES.iter().rev().find(|(from, _)| *from <= version).map(|(_, p)| *p) +} + +impl Profile { + /// Points per coordinate unit. + pub(crate) fn unit(&self) -> f64 { + if self.short { 72.0 / 1000.0 } else { 72.0 / 254_000.0 } + } + + /// Bytes of a coordinate, and of header fields and counts. + pub(crate) fn word(&self) -> usize { + if self.short { 2 } else { 4 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_version_from_3_to_27_has_one_profile() { + assert!(for_version(299).is_none() && for_version(2800).is_none()); + assert!(for_version(300).is_some_and(|p| p.short && p.inline_styles && p.types_from_zero && p.mcfg_corners && p.fixed_matrix)); + assert!(for_version(399).is_some_and(|p| p.color == ColorLayout::Bytes5)); + assert!(for_version(400).is_some_and(|p| p.short && !p.inline_styles && !p.mcfg_corners && p.fixed_matrix)); + assert!(for_version(499).is_some_and(|p| p.color == ColorLayout::Words12)); + assert!(for_version(500).is_some_and(|p| !p.fixed_matrix && !p.types_from_zero && p.color == ColorLayout::Record12)); + assert!(for_version(1300).is_some_and(|p| p.old_master_flags)); + assert!(for_version(1400).is_some_and(|p| p.tagged && !p.f64_rect && !p.old_master_flags)); + assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && p.paths)); + assert!(for_version(2430).is_some_and(|p| p.f64_rect && p.paths && p.utf16_names)); + assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0 && p.marker_after_dash.is_none())); + assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28 && p.marker_after_dash == Some(22))); + assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash == Some(22))); + assert!(for_version(999).is_some_and(|p| !p.paths && p.marker_after_dash == Some(22))); + assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names && p.paths)); + assert!(for_version(1300).is_some_and(|p| p.tagged && p.trfd_head == 8 && p.outl_after_angle == 46)); + // The table is in order, so the search finds each range's own row. + assert!(PROFILES.windows(2).all(|w| w[0].0 < w[1].0)); + } +} diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs new file mode 100644 index 0000000000..8eb2d48125 --- /dev/null +++ b/crates/cdr/src/lib.rs @@ -0,0 +1,115 @@ +//! Reader for `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the `WL` files +//! of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, the ZIP +//! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups, +//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads +//! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and +//! curves with uniform fills and outlines. [`preview()`] gives the picture a `.cdr` file keeps of its +//! drawing, without reading the drawing. +//! +//! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source +//! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not +//! panic. Nothing here writes `.cdr` or `.cmx` files. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::fmt; + +mod build; +mod bytes; +mod cmx; +mod geometry; +mod inline; +mod layout; +mod limits; +pub mod model; +mod package; +mod preview; +mod records; +mod riff; +mod styles; +#[cfg(any(test, feature = "synth"))] +pub mod synth; +#[cfg(any(test, feature = "synth"))] +pub mod synth_cmx; +mod wl; +mod zip; + +pub use limits::Limits; +pub use model::{Drawing, Warning}; +pub use preview::{Preview, PreviewFormat, preview}; + +/// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file +/// of version 1 or 2 whose header offsets fit the file? +pub fn is_cdr(bytes: &[u8]) -> bool { + riff::is_cdr_riff(bytes) || package::is_package(bytes) || wl::is_wl(bytes) +} + +/// Does `bytes` start as a `.cmx` exchange file: a RIFF form (or its big-endian RIFX form) of type +/// `CMX1`? +pub fn is_cmx(bytes: &[u8]) -> bool { + cmx::is_cmx(bytes) +} + +/// Why a file can't be read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// Not a `.cdr` drawing. + NotCdr, + /// Not a `.cmx` file. + NotCmx, + /// A drawing of a version this reader doesn't read (hundreds: 2800 is version 28). + Version(u16), + /// A container structure that doesn't parse. + Damaged(&'static str), + /// Past one of the [`Limits`]. + Limit(&'static str), + /// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that + /// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates; a + /// `DISP` preview that is not an uncompressed bitmap with a 40-byte header; a version 2 file's + /// picture. + Unsupported(&'static str), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::NotCdr => write!(f, "not a CDR drawing"), + Error::NotCmx => write!(f, "not a CMX file"), + Error::Version(v) => write!(f, "version {} drawings are not read", v / 100), + Error::Damaged(what) => write!(f, "damaged {what}"), + Error::Limit(what) => write!(f, "past the {what} limit"), + Error::Unsupported(what) => write!(f, "{what} are not read"), + } + } +} + +impl std::error::Error for Error {} + +/// Read a drawing within `limits`. +pub fn read(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + let mut budget = limits::Budget::new(limits); + // Versions 1 and 2 are not RIFF files (R40). + if wl::is_wl(bytes) { + return wl::drawing(bytes, &mut budget); + } + let mut warnings = Vec::new(); + // Versions 14 on save a ZIP package around the RIFF stream (R24, R25, R26). + let (stream, streams) = if zip::is_zip(bytes) { package::open(bytes, &mut budget)? } else { (std::borrow::Cow::Borrowed(bytes), None) }; + let ix = riff::Index::build(&stream, streams, &mut budget, &mut warnings)?; + let mut drawing = build::drawing(&ix, &mut budget, &mut warnings)?; + ix.stream_warnings(&mut drawing.warnings); + Ok(drawing) +} + +/// Read a `.cmx` exchange file within `limits`. Files in big-endian byte order and files with +/// 16-bit coordinates are refused with [`Error::Unsupported`]. Its [`Drawing::version`] is 0. +pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + let mut budget = limits::Budget::new(limits); + cmx::drawing(bytes, &mut budget) +} diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs new file mode 100644 index 0000000000..bb9804557f --- /dev/null +++ b/crates/cdr/src/limits.rs @@ -0,0 +1,168 @@ +//! What one read may take. The values are VectorCraft's own; wasm32 gets half the memory limits. + +use crate::Error; + +/// The most a read may take, checked before every allocation and descent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Bytes of input. + pub input: usize, + /// Bytes inflated from compressed lists and package members, all of one file together. + pub inflated: usize, + /// Bytes of one package member. + pub member: usize, + /// Members of a package. + pub members: usize, + /// Nested lists below the file's own. Deeper content is left out with a warning. + pub depth: usize, + /// Chunks in the index, nested ones included, and the entries and styles of the style table; + /// in a `.cmx` file, its chunks, table entries and page instructions. + pub chunks: usize, + /// Objects mapped (shapes, groups and guidelines). + pub objects: usize, + /// Points of all curves together. + pub coordinates: usize, + /// Arguments of one `loda` record. + pub arguments: usize, + /// Dashes of all outlines together, an outline's counted again for every shape that uses it. + /// Past them a shape's outline is solid, with a warning. + pub dashes: usize, + /// Chunks walked inside clipped groups, all containers together, a group's counted again for + /// every container that names it. Each search of an object's list for its `loda`, `flgs` and + /// `trfd` runs once per read and counts every chunk it looks at. Past them a container's group + /// is left out, with a warning. + pub clipped_chunks: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +const MIB: usize = 1 << 20; + +impl Default for Limits { + #[cfg(not(target_arch = "wasm32"))] + fn default() -> Self { + Limits { + input: 512 * MIB, + inflated: 1024 * MIB, + member: 512 * MIB, + members: 4096, + depth: 256, + chunks: 2_000_000, + objects: 1_000_000, + coordinates: 16_000_000, + arguments: 64, + dashes: 16_000_000, + clipped_chunks: 2_000_000, + } + } + + #[cfg(target_arch = "wasm32")] + fn default() -> Self { + Limits { + input: 256 << 20, + inflated: 512 << 20, + member: 256 << 20, + members: 4096, + depth: 256, + chunks: 2_000_000, + objects: 1_000_000, + coordinates: 16_000_000, + arguments: 64, + dashes: 8_000_000, + clipped_chunks: 2_000_000, + } + } +} + +/// The running counters of one read against its [`Limits`]. +#[derive(Debug)] +pub(crate) struct Budget { + pub(crate) limits: Limits, + inflated: usize, + chunks: usize, + objects: usize, + coordinates: usize, + dashes: usize, + clipped_chunks: usize, + /// A request for coordinates was refused since [`Budget::coordinates_refused`] last asked. + refused: bool, +} + +impl Budget { + pub(crate) fn new(limits: Limits) -> Self { + Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, clipped_chunks: 0, refused: false } + } + + /// Whether a request for coordinates was refused since the last call, which tells a shape + /// left out at the limit from one whose bytes don't parse. + pub(crate) fn coordinates_refused(&mut self) -> bool { + std::mem::take(&mut self.refused) + } + + /// Bytes an inflate may still produce. + pub(crate) fn inflate_left(&self) -> usize { + self.limits.inflated.saturating_sub(self.inflated) + } + + pub(crate) fn take_inflated(&mut self, n: usize) -> Result<(), Error> { + self.inflated = self.inflated.checked_add(n).filter(|&t| t <= self.limits.inflated).ok_or(Error::Limit("inflated size"))?; + Ok(()) + } + + pub(crate) fn take_chunk(&mut self) -> Result<(), Error> { + self.take_chunks(1) + } + + /// `n` more chunks or style table entries. + pub(crate) fn take_chunks(&mut self, n: usize) -> Result<(), Error> { + self.chunks = self.chunks.saturating_add(n); + if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } + } + + /// One more object, or `false` when the drawing already holds as many as a read maps. + pub(crate) fn take_object(&mut self) -> bool { + if self.objects >= self.limits.objects { + return false; + } + self.objects += 1; + true + } + + /// `n` more curve points, or `false` past the limit (nothing is taken then). + pub(crate) fn take_coordinates(&mut self, n: usize) -> bool { + match self.coordinates.checked_add(n).filter(|&t| t <= self.limits.coordinates) { + Some(t) => { + self.coordinates = t; + true + } + None => { + self.refused = true; + false + } + } + } + + /// Dashes the read may still take. + pub(crate) fn dashes_left(&self) -> usize { + self.limits.dashes.saturating_sub(self.dashes) + } + + /// `n` more dashes, or `false` past the limit (nothing is taken then). + pub(crate) fn take_dashes(&mut self, n: usize) -> bool { + match self.dashes.checked_add(n).filter(|&t| t <= self.limits.dashes) { + Some(t) => { + self.dashes = t; + true + } + None => false, + } + } + + /// One more chunk walked inside a clipped group, or `false` past the limit. + pub(crate) fn take_clipped_chunk(&mut self) -> bool { + if self.clipped_chunks >= self.limits.clipped_chunks { + return false; + } + self.clipped_chunks += 1; + true + } +} diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs new file mode 100644 index 0000000000..e4af34f365 --- /dev/null +++ b/crates/cdr/src/model.rs @@ -0,0 +1,255 @@ +//! What a drawing reads as. Lengths are in points (1/72 inch), from the centre of the page, with y +//! pointing up, as the file stores them. + +/// A point in points. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pt { + pub x: f64, + pub y: f64, +} + +/// An affine map `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Matrix(pub [f64; 6]); + +impl Matrix { + pub const IDENTITY: Matrix = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + + /// `self` after `first`: the map that applies `first`, then `self`. + pub fn after(&self, first: &Matrix) -> Matrix { + let [a, b, c, d, e, f] = self.0; + let [p, q, r, s, t, u] = first.0; + Matrix([a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f]) + } + + pub fn apply(&self, p: Pt) -> Pt { + let [a, b, c, d, e, f] = self.0; + Pt { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f } + } +} + +/// One segment after the previous point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Segment { + Line(Pt), + /// Two control points, then the end point. + Cubic(Pt, Pt, Pt), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SubPath { + pub start: Pt, + pub segments: Vec, + pub closed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Path { + pub subpaths: Vec, +} + +/// The shape of an object, in its own space ([`Shape::matrix`] places it). +#[derive(Clone, Debug, PartialEq)] +pub enum Geometry { + Path(Path), + /// A rectangle from the origin to (`w`, `h`) (either may be negative). `radii` round its + /// corners counterclockwise from the one at (`w`, 0): (`w`, 0), (`w`, `h`), (0, `h`), (0, 0). + Rect { + w: f64, + h: f64, + radii: [f64; 4], + }, + /// A whole ellipse in the box from the origin to (`w`, `h`). + Ellipse { + w: f64, + h: f64, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Color { + Rgb([f32; 3]), + Cmyk([f32; 4]), + /// Ink: 0 is white, 1 black. + Gray(f32), + /// Every ink at full strength. + Registration, + /// A color of a named library, printed on its own plate. `look` is its full-strength color + /// when the file stores one (an approximation in sRGB); `tint` is 0 to 1. + Spot { + name: String, + tint: f32, + look: Option<[f32; 3]>, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cap { + Butt, + Round, + Square, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Join { + Miter, + Round, + Bevel, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Outline { + pub width: f64, + pub color: Color, + pub cap: Cap, + pub join: Join, + /// Dash and gap lengths, in outline widths; empty for a solid line. + pub dashes: Vec, + /// Drawn behind the fill, so that a filled shape shows only the outer half of it. + pub behind_fill: bool, + /// Scaled with the shape: the shape's matrix scales the width and dashes as it scales the + /// geometry. + pub scale_with: bool, +} + +/// Whether a layer, group or shape is hidden or locked. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Flags { + pub hidden: bool, + pub locked: bool, +} + +/// How a shape's colors combine with the art below it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Blend { + #[default] + Normal, + Multiply, + Screen, + Overlay, + SoftLight, + HardLight, + ColorDodge, + ColorBurn, + Darken, + Lighten, + Difference, + Exclusion, + Hue, + Saturation, + Color, + Luminosity, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Shape { + pub geometry: Geometry, + pub matrix: Matrix, + pub fill: Option, + pub outline: Option, + /// The fill covers every area its subpaths wind around (nonzero); otherwise subpaths that + /// overlap leave holes (even-odd). + pub nonzero: bool, + /// 1 opaque, 0 clear. + pub opacity: f32, + pub blend: Blend, + pub flags: Flags, +} + +impl Shape { + /// An opaque, shown shape filled even-odd. + pub fn new(geometry: Geometry, matrix: Matrix, fill: Option, outline: Option) -> Shape { + Shape { geometry, matrix, fill, outline, nonzero: false, opacity: 1.0, blend: Blend::Normal, flags: Flags::default() } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Object { + Shape(Box), + Group { + objects: Vec, + flags: Flags, + }, + /// A clipping container and the objects it clips: `objects` (front to back) show only + /// inside the container's shape, with its fill behind them and its outline over them. + Clip { + container: Box, + objects: Vec, + }, +} + +/// A guideline through `at`, at `angle` degrees counterclockwise from horizontal. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Guideline { + pub at: Pt, + pub angle: f64, + /// The guideline, a group around it or its layer is hidden. + pub hidden: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LayerKind { + Drawing, + /// The objects left beside the pages. + Desktop, + Guides, + Grid, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Layer { + pub name: String, + pub kind: LayerKind, + pub flags: Flags, + /// Front to back, as the file lists them. + pub objects: Vec, + pub guides: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Page { + /// Width and height in points, when the page gives its own. + pub size: Option<(f64, f64)>, + /// Front to back, as the file lists them. + pub layers: Vec, +} + +/// What was left out or changed while reading. Each kind is listed once. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Warning { + /// Text, bitmaps, splines and other objects not read yet. + UnsupportedObjects, + /// Fountain, pattern, texture and PostScript fills. + UnsupportedFills, + /// Colors in models not read; shown black. + UnknownColors, + /// Library spot colors whose look the file doesn't store; shown black. + SpotLooks, + /// Outline arrowheads. + Arrowheads, + /// Envelopes, which are not applied: the shapes under them keep their outlines. + Envelopes, + /// Lenses, and object transparency that isn't read, which are not applied: the objects show + /// opaque. + Lenses, + /// Content nested deeper, or past the counts, that a read takes. + TooDeep, + /// Chunks or records that end early or don't parse. + Damaged, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Drawing { + /// In hundreds, as a RIFF file stores it: 300 to 2799. A file of version 1 or 2 stores no + /// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. A + /// `.cmx` file gives 0. + pub version: u16, + /// Page size from the document settings, in points. + pub page_size: Option<(f64, f64)>, + pub pages: Vec, + /// Layers every page shows, from the master page. + pub master: Vec, + /// Guidelines every page shows, kept outside any layer. + pub guides: Vec, + pub warnings: Vec, +} diff --git a/crates/cdr/src/package.rs b/crates/cdr/src/package.rs new file mode 100644 index 0000000000..6d7fd7e1e3 --- /dev/null +++ b/crates/cdr/src/package.rs @@ -0,0 +1,152 @@ +//! The packages of versions 14 on (R25, R26): a ZIP archive holding the RIFF stream as +//! `content/riffData.cdr` (14 and 15), or as `content/root.dat` with its chunk bodies in the data +//! streams that `content/dataFileList.dat` names (16 on). A data stream is inflated only when a +//! chunk the reader reads, or a list it splits, points into it. + +use std::borrow::Cow; +use std::cell::{Cell, OnceCell}; + +use crate::limits::{Budget, Limits}; +use crate::riff::push; +use crate::zip::{self, Archive}; +use crate::{Error, Warning}; + +const RIFF_DATA: &[u8] = b"content/riffData.cdr"; +const ROOT: &[u8] = b"content/root.dat"; +const DATA_FILE_LIST: &[u8] = b"content/dataFileList.dat"; +const DATA_DIR: &[u8] = b"content/data/"; + +/// Is `bytes` a ZIP archive with a `.cdr` drawing's root stream? +pub(crate) fn is_package(bytes: &[u8]) -> bool { + zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| holds_drawing(&a)) +} + +/// Does the archive `zip` hold a `.cdr` drawing's root stream? +pub(crate) fn holds_drawing(zip: &Archive) -> bool { + zip.find(RIFF_DATA).or_else(|| zip.find(ROOT)).is_some() +} + +/// The RIFF stream of the package `bytes`, and its data streams when it has them (16 on). +pub(crate) fn open<'a>(bytes: &'a [u8], budget: &mut Budget) -> Result<(Cow<'a, [u8]>, Option>), Error> { + let zip = Archive::open(bytes, budget.limits.members)?; + if let Some(i) = zip.find(RIFF_DATA) { + return Ok((member(&zip, i, budget)?, None)); + } + let root = zip.find(ROOT).ok_or(Error::NotCdr)?; + let root = member(&zip, root, budget)?; + let list = match zip.find(DATA_FILE_LIST) { + Some(i) => member(&zip, i, budget)?, + None => Cow::Borrowed(&[][..]), + }; + // One name for each line; a line feed after the last name ends it. + let list = list.strip_suffix(b"\n").unwrap_or(&list); + let mut members = Vec::new(); + if !list.is_empty() { + for line in list.split(|&b| b == b'\n') { + if members.len() == budget.limits.members { + return Err(Error::Limit("package member count")); + } + let name = line.strip_suffix(b"\r").unwrap_or(line); + let found = zip.find(&[DATA_DIR, name].concat()); + // A data stream that is encrypted or packed some other way refuses the file, as the + // root stream does. + if let Some(i) = found { + zip.check(i)?; + } + members.push(found); + } + } + let loaded = (0..zip.count()).map(|_| OnceCell::new()).collect(); + let streams = Streams { zip, members, loaded, member_limit: budget.limits.member, damaged: Cell::new(false) }; + Ok((root, Some(streams))) +} + +/// Member `i` within the member limit and, when deflated, what is left to inflate. +fn member<'a>(zip: &Archive<'a>, i: usize, budget: &mut Budget) -> Result, Error> { + let m = zip.read(i, budget.limits.member, budget.inflate_left())?; + if let Cow::Owned(v) = &m { + budget.take_inflated(v.len())?; + } + Ok(m) +} + +/// What reading one package member gave. +#[derive(Debug)] +enum Slot<'a> { + Read(Cow<'a, [u8]>), + Damaged, + PastLimit, +} + +/// The data streams of a version 16+ package, in `dataFileList.dat` order (R26). +#[derive(Debug)] +pub(crate) struct Streams<'a> { + zip: Archive<'a>, + /// The member holding each stream; `None` when the archive lacks it. + members: Vec>, + /// Each member's bytes once read, so that streams naming one member read it once. + loaded: Vec>>, + member_limit: usize, + /// A stream, or a chunk's bytes in one, could not be found. + damaged: Cell, +} + +impl<'a> Streams<'a> { + /// The member holding stream `s`; `None` when there is no such stream. + pub(crate) fn member_of(&self, s: usize) -> Option { + *self.members.get(s)? + } + + /// The size the archive gives stream `s`; `None` when there is no such stream. + pub(crate) fn size(&self, s: usize) -> Option { + Some(self.zip.size(self.member_of(s)?)) + } + + /// Stream `s`, its member read on first use within the member limit and, when deflated, + /// within `left` more inflated bytes (which it takes from). + pub(crate) fn get(&self, s: usize, left: &Cell) -> Option<&[u8]> { + let Some(i) = self.member_of(s) else { + self.damaged.set(true); + return None; + }; + let slot = self.loaded.get(i)?.get_or_init(|| { + let read = self.zip.read(i, self.member_limit, left.get()); + if !matches!(read, Err(Error::Limit(_))) { + left.set(left.get().saturating_sub(self.zip.inflate_cost(i))); + } + match read { + Ok(b) => Slot::Read(b), + Err(Error::Limit(_)) => Slot::PastLimit, + Err(_) => { + self.damaged.set(true); + Slot::Damaged + } + } + }); + match slot { + Slot::Read(b) => Some(b.as_ref()), + Slot::Damaged | Slot::PastLimit => None, + } + } + + /// Was stream `s` left out because it is past a limit? Chunks in it are then not damage. + pub(crate) fn past_limit(&self, s: usize) -> bool { + let slot = self.member_of(s).and_then(|i| self.loaded.get(i)).and_then(OnceCell::get); + matches!(slot, Some(Slot::PastLimit)) + } + + /// Mark a chunk whose stream bytes could not be found. + pub(crate) fn note_damage(&self) { + self.damaged.set(true); + } + + /// The warnings for streams that were left out. + pub(crate) fn warnings(&self, warn: &mut Vec) { + if self.damaged.get() { + push(warn, Warning::Damaged); + } + if self.loaded.iter().any(|s| matches!(s.get(), Some(Slot::PastLimit))) { + push(warn, Warning::TooDeep); + } + } +} diff --git a/crates/cdr/src/preview.rs b/crates/cdr/src/preview.rs new file mode 100644 index 0000000000..95edefeffd --- /dev/null +++ b/crates/cdr/src/preview.rs @@ -0,0 +1,530 @@ +//! The picture a drawing keeps of itself: the `DISP` chunk of a RIFF file (R75), or the thumbnail +//! member of a package (R76). Reading it walks only the RIFF form's own chunks, or reads one +//! package member, so it does not depend on the drawing's records. + +use std::borrow::Cow; + +use crate::bytes::Rd; +use crate::zip::{self, Archive}; +use crate::{Error, Limits, package, riff, wl}; + +const DISP: [u8; 4] = *b"DISP"; +/// The bytes of a `DISP` body before its bitmap info header (R75). +const DISP_LEAD: usize = 4; +/// The shortest bitmap info header, and the one whose color masks follow it (R75). +const INFO_LEN: usize = 40; +/// The compression values of uncompressed pixels, and of pixels that three color masks describe +/// (R75). +const RGB: u32 = 0; +const BITFIELDS: u32 = 3; +const COMPRESSED: &str = "compressed previews"; +const WL_PICTURE: &str = "pictures of version 2 files"; +const OTHER_HEADER: &str = "preview bitmap headers of other lengths"; +const OTHER_DISP: &str = "previews of other kinds than a bitmap"; +/// The lead bytes of every `DISP` chunk in the sample files, before a bitmap (R75). +const DISP_BITMAP: [u8; DISP_LEAD] = [8, 0, 0, 0]; +/// A BMP file header: `BM`, the file length, 4 reserved bytes and where the pixels start (R75). +const FILE_HEADER_LEN: usize = 14; +/// The package members that hold the drawing's picture (R76), in the order they are looked for. +const PNG_THUMBNAIL: &[u8] = b"previews/thumbnail.png"; +const BMP_THUMBNAIL: &[u8] = b"metadata/thumbnails/thumbnail.bmp"; +const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; +const BMP_SIGNATURE: &[u8] = b"BM"; + +/// How a [`Preview`]'s bytes are encoded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewFormat { + /// A BMP file. + Bmp, + /// A PNG file. + Png, +} + +/// The picture a drawing keeps of itself, still encoded: the caller decodes it within its own +/// image limits. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Preview<'a> { + pub format: PreviewFormat, + pub bytes: Cow<'a, [u8]>, +} + +/// The picture the drawing `bytes` keeps of itself, within `limits`, without reading the drawing: +/// a version 4 to 13 file's `DISP` chunk as a BMP file, or a package's thumbnail member: +/// `previews/thumbnail.png` when the package has one (versions 17 on), else +/// `metadata/thumbnails/thumbnail.bmp` (versions 14 to 16). The package's drawing stream is not +/// read, so the member is chosen by its name, not by the drawing's version. `None` when the file +/// keeps no picture, as versions 1 and 3 do; the 1-bit picture of a version 2 file is not read, and +/// such a file is refused. The drawing's version is not checked, so a RIFF file +/// that [`read`](crate::read) refuses for its version still gives its `DISP` picture. A `DISP` +/// chunk that is not a bitmap, and a bitmap that is compressed or has another header than the +/// 40-byte one, are refused. A package member is read within the member and inflate limits, and its +/// CRC-32 is checked. +pub fn preview(bytes: &[u8], limits: Limits) -> Result>, Error> { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + if zip::is_zip(bytes) { + return thumbnail(bytes, limits); + } + if riff::is_cdr_riff(bytes) { + return disp(bytes, limits); + } + if wl::is_wl(bytes) { + // Version 1 (marker `e`) keeps no picture; version 2's 1-bit picture is not read (R40). + return if bytes.get(2) == Some(&b'e') { Ok(None) } else { Err(Error::Unsupported(WL_PICTURE)) }; + } + Err(Error::NotCdr) +} + +/// A package's thumbnail member (R76). +fn thumbnail(bytes: &[u8], limits: Limits) -> Result>, Error> { + let zip = Archive::open(bytes, limits.members)?; + if !package::holds_drawing(&zip) { + return Err(Error::NotCdr); + } + for (name, format, signature) in [(PNG_THUMBNAIL, PreviewFormat::Png, PNG_SIGNATURE), (BMP_THUMBNAIL, PreviewFormat::Bmp, BMP_SIGNATURE)] { + if let Some(i) = zip.find(name) { + let bytes = zip.read(i, limits.member, limits.inflated)?; + if !bytes.starts_with(signature) { + return Err(Error::Damaged("preview")); + } + return Ok(Some(Preview { format, bytes })); + } + } + Ok(None) +} + +/// The `DISP` chunk among the RIFF form's own chunks, as a BMP file (R75). A file cut short still +/// gives a `DISP` chunk it holds whole. When there is none, the last chunk must end where the form's +/// length says the form ends; otherwise the file is damaged. +fn disp(bytes: &[u8], limits: Limits) -> Result>, Error> { + let declared = Rd::at(bytes, 4).u32().ok_or(Error::NotCdr)? as usize; + // A form length past the file is taken to the file's end; one too short for the form type + // leaves no chunk to walk. + let end = declared.checked_add(8).filter(|e| *e <= bytes.len()).unwrap_or(bytes.len()); + let mut at: usize = 12; + let mut chunks = 0; + // Why the last `DISP` chunk passed over was not read: another kind than a bitmap, or a bitmap + // this reader does not read. + let mut passed: Option = None; + while at.checked_add(8).is_some_and(|h| h <= end) { + chunks += 1; + if chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + let mut r = Rd::at(bytes, at); + let (id, len) = (r.fourcc(), r.u32().map(|n| n as usize)); + let (Some(id), Some(len)) = (id, len) else { break }; + let body = at + 8; + if id == DISP { + let data = body.checked_add(len).filter(|e| *e <= end).and_then(|e| bytes.get(body..e)).ok_or(Error::Damaged("preview"))?; + match data.get(..DISP_LEAD) { + None => return Err(Error::Damaged("preview")), + Some(lead) if lead == DISP_BITMAP => match bmp(data) { + Ok(b) => return Ok(Some(Preview { format: PreviewFormat::Bmp, bytes: Cow::Owned(b) })), + Err(e @ Error::Unsupported(_)) => passed = Some(e), + Err(e) => return Err(e), + }, + Some(_) => passed = Some(Error::Unsupported(OTHER_DISP)), + } + } + // Chunks are padded to an even length. + at = body.saturating_add(len).saturating_add(len & 1); + } + // A chunk past the end, a partial chunk header or a file cut short may hide a `DISP` chunk. + if at > bytes.len() || declared.checked_add(8) != Some(at) { + return Err(Error::Damaged("preview")); + } + passed.map_or(Ok(None), Err) +} + +/// The bitmap of a `DISP` body as a BMP file: a file header before its info header, color masks or +/// table and pixels (R75). +fn bmp(disp: &[u8]) -> Result, Error> { + let damaged = || Error::Damaged("preview"); + let dib = disp.get(DISP_LEAD..).ok_or_else(damaged)?; + let mut r = Rd::new(dib); + let info = r.u32().ok_or_else(damaged)? as usize; + // A header too short for its own length field, or longer than the chunk. + if info < 4 || info > dib.len() { + return Err(damaged()); + } + // Only the 40-byte header is read (R75). + if info != INFO_LEN { + return Err(Error::Unsupported(OTHER_HEADER)); + } + let (width, height) = (r.i32().ok_or_else(damaged)?, r.i32().ok_or_else(damaged)?); + // The planes, the bit count and compression; the image size and resolution, then the colors + // used. + let planes = r.u16().ok_or_else(damaged)?; + let bits = r.u16().ok_or_else(damaged)?; + let compression = r.u32().ok_or_else(damaged)?; + let size = r.u32().ok_or_else(damaged)?; + r.skip(8).ok_or_else(damaged)?; + let used = r.u32().ok_or_else(damaged)? as usize; + // Only uncompressed pixels are read: color masks are valid at 16 and 32 bits (R75). + match compression { + RGB if matches!(bits, 1 | 4 | 8 | 16 | 24 | 32) => {} + BITFIELDS if matches!(bits, 16 | 32) => {} + RGB | BITFIELDS => return Err(damaged()), + _ => return Err(Error::Unsupported(COMPRESSED)), + } + if planes != 1 { + return Err(damaged()); + } + // A table of 2^bits colors when the header names none for 8 bits or fewer, and never more. + let colors = if bits <= 8 && used == 0 { 1usize << bits } else { used }; + if bits < 32 && colors as u64 > 1u64 << bits { + return Err(damaged()); + } + // Three masks follow the header. + let masks = if compression == BITFIELDS { 12 } else { 0 }; + let pixels = colors.checked_mul(4).and_then(|t| (FILE_HEADER_LEN + info + masks).checked_add(t)).ok_or_else(damaged)?; + let total = FILE_HEADER_LEN + dib.len(); + // The pixels are rows of whole 32-bit words, as many as the height says (R75). + let width = u64::try_from(width).ok().filter(|w| *w > 0).ok_or_else(damaged)?; + if height == 0 { + return Err(damaged()); + } + let rows = ((width * u64::from(bits)).div_ceil(32) * 4).checked_mul(u64::from(height.unsigned_abs())); + // The image size is 0 or the rows' size. + if size != 0 && rows != Some(u64::from(size)) { + return Err(damaged()); + } + // The file ends with the last row; bytes after it in the chunk are left out. + let end = rows.and_then(|n| n.checked_add(pixels as u64)).filter(|e| *e <= total as u64).ok_or_else(damaged)? as usize; + let (end32, pixels32) = (u32::try_from(end).map_err(|_| damaged())?, u32::try_from(pixels).map_err(|_| damaged())?); + let mut out = Vec::new(); + out.try_reserve_exact(end).map_err(|_| Error::Limit("preview size"))?; + out.extend(BMP_SIGNATURE); + out.extend(end32.to_le_bytes()); + out.extend([0; 4]); + out.extend(pixels32.to_le_bytes()); + out.extend(dib.get(..end - FILE_HEADER_LEN).ok_or_else(damaged)?); + Ok(out) +} + +#[cfg(test)] +mod tests { + use proptest::prelude::*; + + use super::*; + use crate::synth::{self, Member, chunk}; + + /// A `DISP` body: the lead bytes, a 40-byte info header for `bits` per pixel and `used` + /// colors, the color table and `rows` rows of `width` pixels. + fn disp_body(width: u32, rows: u32, bits: u16, used: u32) -> Vec { + let mut b = 8u32.to_le_bytes().to_vec(); + b.extend(40u32.to_le_bytes()); + b.extend(width.to_le_bytes()); + b.extend(rows.to_le_bytes()); + b.extend(1u16.to_le_bytes()); + b.extend(bits.to_le_bytes()); + b.extend([0; 16]); + b.extend(used.to_le_bytes()); + b.extend([0; 4]); + let colors = if bits <= 8 && used == 0 { 1 << bits } else { used }; + b.extend((0..colors * 4).map(|i| i as u8)); + let stride = (width * u32::from(bits)).div_ceil(32) * 4; + b.extend((0..stride * rows).map(|i| (i * 7) as u8)); + b + } + + fn with_disp(version: u16, body: Vec) -> Vec { + let mut content = vec![chunk(b"vrsn", version.to_le_bytes().to_vec()), chunk(b"DISP", body)]; + content.extend(synth::sample_content(version)); + synth::riff(version, &content) + } + + fn png() -> Vec { + [PNG_SIGNATURE, b"rest of the picture"].concat() + } + + fn package16(extra: &[Member]) -> Vec { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + synth::package16(1700, &body, true, extra) + } + + fn member(name: &str, data: Vec, deflate: bool) -> Member { + Member { name: name.into(), data, deflate } + } + + #[test] + fn a_riff_files_disp_chunk_is_a_bmp_file_around_its_bitmap() { + for (bits, used) in [(8, 256), (8, 0), (4, 0), (4, 16), (1, 2)] { + let body = disp_body(9, 5, bits, used); + let file = with_disp(1100, body.clone()); + let p = preview(&file, Limits::default()).unwrap().unwrap(); + assert_eq!(p.format, PreviewFormat::Bmp); + let b = &p.bytes; + assert!(b.starts_with(b"BM")); + assert_eq!(&b[FILE_HEADER_LEN..], &body[DISP_LEAD..], "the bitmap follows the file header unchanged"); + assert_eq!(u32::from_le_bytes(b[2..6].try_into().unwrap()) as usize, b.len()); + // The pixels start after the info header and the whole color table. + let colors = if used == 0 { 1 << bits } else { used } as usize; + assert_eq!(u32::from_le_bytes(b[10..14].try_into().unwrap()) as usize, FILE_HEADER_LEN + 40 + colors * 4, "{bits} bits, {used} colors"); + } + // Bytes after the last row are left out of the file. + let body = disp_body(9, 5, 8, 0); + let trailing = [body.as_slice(), &[0xAA; 64]].concat(); + let file = with_disp(1100, trailing); + let p = preview(&file, Limits::default()).unwrap().unwrap(); + assert_eq!(&p.bytes[FILE_HEADER_LEN..], &body[DISP_LEAD..]); + assert_eq!(u32::from_le_bytes(p.bytes[2..6].try_into().unwrap()) as usize, p.bytes.len()); + } + + #[test] + fn a_file_without_a_picture_has_no_preview() { + assert_eq!(preview(&synth::sample(300, false), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::sample(1100, true), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::wl_sample(b'e'), Limits::default()), Ok(None)); + assert_eq!(preview(&package16(&[]), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::package14(synth::sample(1500, true), true), Limits::default()), Ok(None)); + } + + #[test] + fn a_package_gives_its_thumbnail_member() { + let bmp = with_disp(1100, disp_body(3, 2, 8, 0)); + let bmp = preview(&bmp, Limits::default()).unwrap().unwrap().bytes.into_owned(); + let v15 = synth::zip( + &[member("content/riffData.cdr", synth::sample(1500, true), true), member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), true)], + b"", + ); + assert_eq!(preview(&v15, Limits::default()), Ok(Some(Preview { format: PreviewFormat::Bmp, bytes: Cow::Owned(bmp) }))); + // A stored member is lent, not copied. + let v16 = package16(&[member("previews/page1.png", vec![1; 10], false), member("previews/thumbnail.png", png(), false)]); + let p = preview(&v16, Limits::default()).unwrap().unwrap(); + assert_eq!(p.format, PreviewFormat::Png); + assert!(matches!(p.bytes, Cow::Borrowed(b) if b == png().as_slice())); + } + + #[test] + fn a_thumbnail_that_is_not_its_format_is_damage() { + let v16 = package16(&[member("previews/thumbnail.png", b"BM not a PNG".to_vec(), false)]); + assert_eq!(preview(&v16, Limits::default()), Err(Error::Damaged("preview"))); + let v15 = synth::zip( + &[member("content/riffData.cdr", synth::sample(1500, false), false), member("metadata/thumbnails/thumbnail.bmp", png(), false)], + b"", + ); + assert_eq!(preview(&v15, Limits::default()), Err(Error::Damaged("preview"))); + } + + #[test] + fn a_disp_chunk_too_short_for_its_bitmap_is_damage() { + let body = disp_body(4, 4, 8, 0); + // Cut inside the info header, inside the color table, and before the lead bytes end. + for cut in [DISP_LEAD + 20, DISP_LEAD + 40 + 100, 2] { + let file = with_disp(1100, body[..cut].to_vec()); + assert_eq!(preview(&file, Limits::default()), Err(Error::Damaged("preview")), "cut at {cut}"); + } + // An info header longer than the chunk or too short for its length field, and a plane + // count other than 1. + for info in [u32::MAX, 0, 3] { + let mut b = body.clone(); + b[DISP_LEAD..DISP_LEAD + 4].copy_from_slice(&info.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "info {info}"); + } + for planes in [0u16, 2] { + let mut b = body.clone(); + b[DISP_LEAD + 12..DISP_LEAD + 14].copy_from_slice(&planes.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "{planes} planes"); + } + // Header lengths other than 40 bytes. + for info in [12u32, 44, 52, 56, 64, 108, 124] { + let mut b = body.clone(); + b[DISP_LEAD..DISP_LEAD + 4].copy_from_slice(&info.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Unsupported(OTHER_HEADER)), "info {info}"); + } + // A whole 12-byte core header of a 1-by-1 24-bit bitmap, shorter than the 40-byte fields. + let mut core = 8u32.to_le_bytes().to_vec(); + core.extend(12u32.to_le_bytes()); + core.extend([1, 0, 1, 0, 1, 0, 24, 0]); + core.extend([1, 2, 3, 0]); + assert_eq!(preview(&with_disp(1100, core), Limits::default()), Err(Error::Unsupported(OTHER_HEADER))); + // A color count past the chunk. + let mut b = body.clone(); + b[DISP_LEAD + 32..DISP_LEAD + 36].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview"))); + // Pixel rows cut short, and a width or bit count that gives no rows. + let rows = with_disp(1100, body[..body.len() - 1].to_vec()); + assert_eq!(preview(&rows, Limits::default()), Err(Error::Damaged("preview"))); + for (at, v) in [(4, 0u32.to_le_bytes().to_vec()), (14, 2u16.to_le_bytes().to_vec())] { + let mut b = body.clone(); + b[DISP_LEAD + at..DISP_LEAD + at + v.len()].copy_from_slice(&v); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "field at {at}"); + } + // A chunk that runs past the end of the RIFF form, though not past the file. + let mut past = with_disp(1100, body.clone()); + let at = past.windows(4).position(|w| w == b"DISP").unwrap(); + let form_len = (at + 8 + body.len() - 1 - 8) as u32; + past[4..8].copy_from_slice(&form_len.to_le_bytes()); + assert_eq!(preview(&past, Limits::default()), Err(Error::Damaged("preview"))); + // A chunk whose length runs past the file. + let mut file = with_disp(1100, body); + let at = file.windows(4).position(|w| w == b"DISP").unwrap(); + file[at + 4..at + 8].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(preview(&file, Limits::default()), Err(Error::Damaged("preview"))); + } + + #[test] + fn color_masks_after_a_40_byte_header_come_before_the_pixels() { + let plain = disp_body(2, 2, 16, 0); + let mut body = plain[..DISP_LEAD + 40].to_vec(); + body[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&BITFIELDS.to_le_bytes()); + body.extend([0x00, 0xF8, 0, 0, 0xE0, 0x07, 0, 0, 0x1F, 0, 0, 0]); + body.extend(&plain[DISP_LEAD + 40..]); + let pixels_at = |file: Vec| { + let p = preview(&file, Limits::default()).unwrap().unwrap(); + u32::from_le_bytes(p.bytes[10..14].try_into().unwrap()) as usize + }; + assert_eq!(pixels_at(with_disp(1100, body)), FILE_HEADER_LEN + 40 + 12); + // Without the masks the pixels start right after the header. + assert_eq!(pixels_at(with_disp(1100, plain)), FILE_HEADER_LEN + 40); + } + + #[test] + fn the_limits_hold() { + let file = with_disp(1100, disp_body(4, 4, 8, 0)); + assert_eq!(preview(&file, Limits { input: file.len() - 1, ..Limits::default() }), Err(Error::Limit("input size"))); + // The `DISP` chunk is the second chunk. + assert_eq!(preview(&file, Limits { chunks: 1, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert!(preview(&file, Limits { chunks: 2, ..Limits::default() }).unwrap().is_some()); + let big = vec![7; 4000]; + let v16 = package16(&[member("previews/thumbnail.png", [PNG_SIGNATURE, &big].concat(), true)]); + assert_eq!(preview(&v16, Limits { member: 4000, ..Limits::default() }), Err(Error::Limit("package member size"))); + assert_eq!(preview(&v16, Limits { inflated: 4000, ..Limits::default() }), Err(Error::Limit("inflated size"))); + assert_eq!(preview(&v16, Limits { members: 1, ..Limits::default() }), Err(Error::Limit("package member count"))); + } + + #[test] + fn a_walk_that_stops_short_of_the_forms_end_is_damage() { + let file = synth::sample(1100, true); + assert_eq!(preview(&file, Limits::default()), Ok(None)); + // A chunk whose length runs past the form, before any `DISP` chunk. + let mut past = file.clone(); + past[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(preview(&past, Limits::default()), Err(Error::Damaged("preview"))); + // A form length too short for the form type, with a `DISP` chunk after it. + let mut short = with_disp(1100, disp_body(4, 4, 8, 0)); + short[4..8].copy_from_slice(&2u32.to_le_bytes()); + assert_eq!(preview(&short, Limits::default()), Err(Error::Damaged("preview"))); + // A partial chunk header at the end: the start of a `DISP` chunk whose length is cut off. + let mut partial = file.clone(); + partial.extend(b"DISP"); + let form_len = (partial.len() - 8) as u32; + partial[4..8].copy_from_slice(&form_len.to_le_bytes()); + assert_eq!(preview(&partial, Limits::default()), Err(Error::Damaged("preview"))); + // A file without a `DISP` chunk cut inside its last chunk. + assert_eq!(preview(&file[..file.len() - 1], Limits::default()), Err(Error::Damaged("preview"))); + // A file cut where its `DISP` chunk would start, and one cut after it. + let whole = with_disp(1100, disp_body(4, 4, 8, 0)); + let at = whole.windows(4).position(|w| w == b"DISP").unwrap(); + assert_eq!(preview(&whole[..at], Limits::default()), Err(Error::Damaged("preview"))); + assert!(preview(&whole[..whole.len() - 1], Limits::default()).unwrap().is_some()); + } + + #[test] + fn a_disp_chunk_that_is_not_a_bitmap_is_passed_over() { + let text = [[1u8, 0, 0, 0].as_slice(), b"some text"].concat(); + let bitmap = disp_body(3, 2, 8, 0); + // A bitmap with a 12-byte header, which is not read. + let core = [[8u8, 0, 0, 0, 12, 0, 0, 0, 1, 0, 1, 0, 1, 0, 24, 0].as_slice(), &[1, 2, 3, 0]].concat(); + // A run-length bitmap, whose other fields are not checked: here a plane count of 0. + let mut rle = bitmap.clone(); + rle[DISP_LEAD + 12..DISP_LEAD + 14].copy_from_slice(&0u16.to_le_bytes()); + rle[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&1u32.to_le_bytes()); + let mut content = + vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), chunk(b"DISP", text.clone()), chunk(b"DISP", core), chunk(b"DISP", rle)]; + content.push(chunk(b"DISP", bitmap.clone())); + content.extend(synth::sample_content(1100)); + let file = synth::riff(1100, &content); + let p = preview(&file, Limits::default()).unwrap().unwrap(); + assert_eq!(&p.bytes[FILE_HEADER_LEN..], &bitmap[DISP_LEAD..]); + // With no bitmap after it, the file has a picture that is not read. + assert_eq!(preview(&with_disp(1100, text), Limits::default()), Err(Error::Unsupported(OTHER_DISP))); + } + + #[test] + fn a_color_table_larger_than_the_bit_count_allows_is_damage() { + assert!(preview(&with_disp(1100, disp_body(4, 4, 1, 2)), Limits::default()).unwrap().is_some()); + assert_eq!(preview(&with_disp(1100, disp_body(4, 4, 1, 3)), Limits::default()), Err(Error::Damaged("preview"))); + assert_eq!(preview(&with_disp(1100, disp_body(1, 1, 16, 65_537)), Limits::default()), Err(Error::Damaged("preview"))); + } + + #[test] + fn the_image_size_is_0_or_the_rows_size() { + // 4 rows of 4 bytes. + let body = disp_body(4, 4, 8, 0); + for (size, ok) in [(16u32, true), (17, false), (16 + 64, false)] { + let mut b = [body.as_slice(), &[0; 64]].concat(); + b[DISP_LEAD + 20..DISP_LEAD + 24].copy_from_slice(&size.to_le_bytes()); + let file = with_disp(1100, b); + assert_eq!(preview(&file, Limits::default()).is_ok(), ok, "size {size}"); + } + } + + #[test] + fn a_version_2_files_picture_is_not_read() { + for marker in *b"ml" { + assert_eq!(preview(&synth::wl_sample(marker), Limits::default()), Err(Error::Unsupported(WL_PICTURE))); + } + } + + #[test] + fn a_package_with_both_members_gives_the_png() { + let bmp = with_disp(1100, disp_body(3, 2, 8, 0)); + let bmp = preview(&bmp, Limits::default()).unwrap().unwrap().bytes.into_owned(); + for extra in [ + [member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), false), member("previews/thumbnail.png", png(), false)], + [member("previews/thumbnail.png", png(), false), member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), false)], + ] { + assert_eq!(preview(&package16(&extra), Limits::default()).unwrap().unwrap().format, PreviewFormat::Png); + } + } + + #[test] + fn a_compressed_or_masked_bitmap_outside_the_header_rules_is_refused() { + let body = disp_body(4, 4, 8, 0); + let with = |compression: u32, bits: u16| { + let mut b = body.clone(); + b[DISP_LEAD + 14..DISP_LEAD + 16].copy_from_slice(&bits.to_le_bytes()); + b[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&compression.to_le_bytes()); + preview(&with_disp(1100, b), Limits::default()).map(|p| p.map(|p| p.format)) + }; + // Run-length, JPEG, PNG and alpha-mask compression, and a bit count of 0. + for (compression, bits) in [(1, 8), (2, 4), (4, 0), (5, 0), (6, 32)] { + assert_eq!(with(compression, bits), Err(Error::Unsupported(COMPRESSED)), "compression {compression}"); + } + // Color masks are valid only at 16 and 32 bits, and no bit count of 0 is uncompressed. + for (compression, bits) in [(BITFIELDS, 8), (BITFIELDS, 24), (BITFIELDS, 1), (RGB, 0)] { + assert_eq!(with(compression, bits), Err(Error::Damaged("preview")), "compression {compression}, {bits} bits"); + } + } + + #[test] + fn other_files_are_not_drawings() { + assert_eq!(preview(b"not a drawing", Limits::default()), Err(Error::NotCdr)); + let zip = synth::zip(&[member("previews/thumbnail.png", png(), false)], b""); + assert_eq!(preview(&zip, Limits::default()), Err(Error::NotCdr)); + } + + proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_mutated_files(package: bool, cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = if package { + package16(&[member("previews/thumbnail.png", png(), false)]) + } else { + with_disp(900, disp_body(5, 3, 4, 0)) + }; + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = preview(&b, Limits::default()); + let _ = preview(&b[..cut % (n + 1)], Limits::default()); + } + } +} diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs new file mode 100644 index 0000000000..49adcedc7e --- /dev/null +++ b/crates/cdr/src/records.rs @@ -0,0 +1,659 @@ +//! Hand-written decoders of the records a drawing's objects refer to: the `loda` argument table +//! (R6), transforms (R8), colors (R14), fills (R11) and outlines (R12, R13). + +use crate::bytes::Rd; +use crate::layout::{ColorLayout, Profile}; +use crate::model::{Blend, Cap, Color, Join, Matrix, Outline}; +use crate::riff::push; +use crate::{Limits, Warning}; + +/// The tag of a record's current layout in tagged files (R11, R12). +const TAG_1300: u32 = 1300; +/// The most tagged records skipped before a fill's own (R11). +const MAX_SKIPPED: usize = 4; +/// The most records skipped before an outline's own (R12). +const MAX_OUTLINE_RECORDS: usize = 16; +/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of +/// a layer's. +const MAX_NAME: usize = 256; + +/// A header field: u16 in short files, u32 otherwise. +fn word(r: &mut Rd, p: &Profile) -> Option { + if p.short { r.u16().map(usize::from) } else { r.u32().map(|v| v as usize) } +} + +/// A coordinate in points. +pub(crate) fn coord(r: &mut Rd, p: &Profile) -> Option { + let raw = if p.short { f64::from(r.i16()?) } else { f64::from(r.i32()?) }; + Some(raw * p.unit()) +} + +/// An angle in degrees: tenths in short files, millionths otherwise (R7). +pub(crate) fn angle(r: &mut Rd, p: &Profile) -> Option { + if p.short { Some(f64::from(r.i16()?) / 10.0) } else { Some(f64::from(r.i32()?) / 1_000_000.0) } +} + +/// A `loda` record (R6): its object type and arguments as (type, bytes). +pub(crate) struct Loda<'a> { + pub(crate) kind: u32, + pub(crate) args: Vec<(u32, &'a [u8])>, +} + +impl<'a> Loda<'a> { + pub(crate) fn arg(&self, kind: u32) -> Option<&'a [u8]> { + self.args.iter().find(|(k, _)| *k == kind).map(|(_, b)| *b) + } +} + +pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + let (_len, count, offsets_at, types_at, kind) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); + // The types table is indexed from the stored count, however many arguments are read. + let stored = count; + let count = if count > limits.arguments { + push(warn, Warning::Damaged); + limits.arguments + } else { + count + }; + let table_bytes = count.checked_add(1)?.checked_mul(p.word())?; + if offsets_at.checked_add(table_bytes)? > b.len() { + return None; + } + let mut offsets = Vec::with_capacity(count + 1); + let mut ro = Rd::at(b, offsets_at); + for _ in 0..=count { + offsets.push(word(&mut ro, p)?); + } + let mut args = Vec::with_capacity(count); + for i in 0..count { + // The types table runs the other way: offset i pairs with type stored - 1 - i. + let kind = word(&mut Rd::at(b, types_at.checked_add((stored - 1 - i).checked_mul(p.word())?)?), p)? as u32; + let (start, end) = (*offsets.get(i)?, *offsets.get(i + 1)?); + match b.get(start..end) { + Some(body) => args.push((kind, body)), + None => push(warn, Warning::Damaged), + } + } + Some(Loda { kind: kind as u32, args }) +} + +/// The matrices of a `trfd` record composed in file order, in points (R8). Each entry ends where +/// the next offset points, and the last at the offset after it (R51); an entry too short for its +/// matrix makes the record unreadable. +pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); + let mut m = Matrix::IDENTITY; + let k = p.unit(); + // Each entry takes at least its offset's bytes, which bounds the count by the record's size. + for i in 0..count.min(b.len() / p.word()) { + let slot = offsets_at.checked_add(i.checked_mul(p.word())?)?; + let start = word(&mut Rd::at(b, slot), p)?; + // A table that stops before the last entry's end offset leaves that entry the rest of the + // record. + let end = word(&mut Rd::at(b, slot.checked_add(p.word())?), p).unwrap_or(b.len()); + let mut e = Rd::at(b.get(start..end)?, p.trfd_head); + if e.u16()? != 8 { + continue; + } + e.skip(p.matrix_skip)?; + let next = if p.fixed_matrix { + fixed_matrix(&mut e, k)? + } else { + let (a, c, tx, bb, d, ty) = (e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?); + Matrix([a, bb, c, d, tx * k, ty * k]) + }; + m = next.after(&m); + } + Some(m) +} + +/// A number in 16.16 fixed point. +pub(crate) fn fixed(r: &mut Rd) -> Option { + Some(f64::from(r.i32()?) / 65536.0) +} + +/// A matrix of versions 3 and 4 (R37): six i32 `a c tx b d ty`, the factors in 16.16 fixed point +/// and `tx` and `ty` in coordinate units of `k` points. +pub(crate) fn fixed_matrix(r: &mut Rd, k: f64) -> Option { + let (a, c, tx) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?)); + let (b, d, ty) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?)); + Some(Matrix([a, b, c, d, tx * k, ty * k])) +} + +/// A color in the layout of the file's version (R14, R36). Unknown models read as black with a +/// warning. +pub(crate) fn color(r: &mut Rd, p: &Profile, warn: &mut Vec) -> Option { + match p.color { + ColorLayout::Record12 => { + let model = r.u16()?; + let palette = r.u16()?; + r.skip(4)?; + let v: [u8; 4] = r.bytes(4)?.try_into().ok()?; + Some(model_color(model, palette, v, warn)) + } + ColorLayout::Words12 => { + let model = r.u16()?; + let w = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; + r.skip(2)?; + // The models take 8-bit values, as in the other layouts; a larger value reads as 255. + Some(early_color(model, w.map(|x| u8::try_from(x).unwrap_or(u8::MAX)), w[0], w[1], warn)) + } + ColorLayout::Bytes5 => Some(color5(r.bytes(5)?.try_into().ok()?, warn)), + } +} + +/// A 5-byte color (R36): a model byte and four value bytes. +pub(crate) fn color5(b: [u8; 5], warn: &mut Vec) -> Color { + let [model, v @ ..] = b; + early_color(u16::from(model), v, u16::from_le_bytes([v[0], v[1]]), u16::from_le_bytes([v[2], v[3]]), warn) +} + +/// A color of versions 1 to 4 (R36). Model 1 is CMYK in percent. Model 0 is a numbered ink and +/// its tint in percent: 0 is black, 1 is white, and other numbers are inks of a library the file +/// doesn't store. Other models read as in later versions. +fn early_color(model: u16, v: [u8; 4], index: u16, tint: u16, warn: &mut Vec) -> Color { + let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0); + match (model, index) { + (1, _) => Color::Cmyk(v.map(|x| pct(f32::from(x)))), + (0, 0) => Color::Gray(pct(f32::from(tint))), + (0, 1) => Color::Gray(0.0), + (0, number) => { + push(warn, Warning::SpotLooks); + Color::Spot { name: format!("Spot 0:{number}"), tint: pct(f32::from(tint)), look: None } + } + _ => model_color(model, 0, v, warn), + } +} + +/// The color of `model` with the four value bytes `v`, from version 5 (R14). +fn model_color(model: u16, palette: u16, v: [u8; 4], warn: &mut Vec) -> Color { + let (v0, v1, v2, v3) = (f32::from(v[0]), f32::from(v[1]), f32::from(v[2]), f32::from(v[3])); + let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0); + let byte = |x: f32| x / 255.0; + match model { + 2 => Color::Cmyk([pct(v0), pct(v1), pct(v2), pct(v3)]), + 3 | 17 => Color::Cmyk([byte(v0), byte(v1), byte(v2), byte(v3)]), + 4 => Color::Cmyk([byte(v0), byte(v1), byte(v2), 0.0]), + 5 | 21 => Color::Rgb([byte(v2), byte(v1), byte(v0)]), + 9 => Color::Gray(1.0 - byte(v0)), + 20 => Color::Registration, + 1 | 14 | 25 => { + let number = u16::from_le_bytes([v[0], v[1]]); + let tint = pct(f32::from(u16::from_le_bytes([v[2], v[3]]))); + push(warn, Warning::SpotLooks); + // Each library numbers its own colors: the name holds the palette and the number. + Color::Spot { name: format!("Spot {palette}:{number}"), tint, look: None } + } + _ => { + push(warn, Warning::UnknownColors); + Color::Rgb([0.0; 3]) + } + } +} + +/// A UTF-16 name stored as a character count and its code units. Every shape that uses the color +/// gets its own copy of the name: a name longer than [`MAX_NAME`] units keeps its first ones and a +/// hash of the whole name, with a warning, so two long names that start alike stay apart. +fn counted_utf16(r: &mut Rd, warn: &mut Vec) -> Option { + let n = r.u32()? as usize; + let b = r.bytes(n.checked_mul(2)?)?; + // Trailing NULs are padding. + let all = b.as_chunks::<2>().0; + let all = all.get(..all.iter().rposition(|c| *c != [0, 0]).map_or(0, |i| i + 1)).unwrap_or_default(); + let units = all.iter().map(|c| u16::from_le_bytes(*c)); + if all.len() <= MAX_NAME { + let units: Vec = units.collect(); + return Some(String::from_utf16_lossy(&units)); + } + push(warn, Warning::TooDeep); + // FNV-1a over the code units. + let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u64::from(u)).wrapping_mul(0x0100_0000_01b3)); + let kept: Vec = units.take(MAX_NAME).collect(); + Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept))) +} + +/// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color +/// record, named by the library name it carries. +pub(crate) fn property_color(b: &[u8], p: &Profile, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + let (mut found, mut name) = (None, None); + while r.left() >= 5 { + let kind = r.u8()?; + let len = r.u32()? as usize; + if kind == 0 { + break; + } + let body = r.bytes(len)?; + let mut br = Rd::new(body); + match kind { + 1 => found = color(&mut br, p, warn), + 8 => name = br.skip(16).and_then(|_| counted_utf16(&mut br, warn)), + 3 => name = name.or_else(|| counted_utf16(&mut br, warn)), + _ => {} + } + } + match (found?, name.filter(|n| !n.is_empty())) { + // A library color with its name: the record's sRGB has the tint applied already. + (Color::Rgb(rgb), Some(name)) => { + let tint = b_tint(b).unwrap_or(1.0); + Some(Color::Spot { name, tint, look: Some(untinted(rgb, tint)) }) + } + (c, _) => Some(c), + } +} + +/// The tint byte of the first color property of a property list (model 21 keeps it last). +fn b_tint(b: &[u8]) -> Option { + let mut r = Rd::new(b); + while r.left() >= 5 { + let kind = r.u8()?; + let len = r.u32()? as usize; + let body = r.bytes(len)?; + if kind == 1 { + let mut c = Rd::new(body); + return (c.u16()? == 21).then(|| f32::from(*body.get(11).unwrap_or(&100)) / 100.0).map(|t| t.clamp(0.0, 1.0)); + } + } + None +} + +/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white). +fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { + if tint <= 0.0 { + return rgb; + } + rgb.map(|v| (1.0 - (1.0 - v) / tint).clamp(0.0, 1.0)) +} + +/// A fill record: its id, and its color (`None`: no fill). Fills of other kinds read as none with +/// a warning (R11). +pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { + let mut r = Rd::new(b); + let id = r.u32()?; + let body = if p.tagged { tagged_body(&mut r)? } else { r.bytes(r.left())? }; + let mut r = Rd::new(body); + let kind = r.u16()?; + let color = match kind { + 0 => None, + 1 if p.tagged => { + if r.u32()? != TAG_1300 { + push(warn, Warning::Damaged); + return Some((id, None)); + } + // A uniform fill whose color can't be read is damage, not a fill of none. + let len = r.u32()? as usize; + Some(property_color(r.bytes(len.min(r.left()))?, p, warn)?) + } + 1 => { + r.skip(2)?; + Some(color(&mut r, p, warn)?) + } + _ => { + push(warn, Warning::UnsupportedFills); + None + } + }; + Some((id, color)) +} + +/// The body of the record tagged 1300 that follows tagged records of later layouts (R11). +fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> { + for _ in 0..=MAX_SKIPPED { + let (tag, len) = (r.u32()?, r.u32()? as usize); + let body = r.bytes(len.min(r.left()))?; + if tag == TAG_1300 { + return Some(body); + } + } + None +} + +/// An outline record: its id and the outline (`None`: no outline) (R12, R13). +pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { + let mut r = Rd::new(b); + let id = r.u32()?; + // A library color named in a record of type 2, with the warnings its read gave. + let mut named = None; + if p.tagged { + let mut found = false; + for _ in 0..MAX_OUTLINE_RECORDS { + let (rec, len) = (r.u32()?, r.u32()? as usize); + if rec == 1 { + found = true; + break; + } + let body = r.bytes(len)?; + // Type 2 holds the outline's color as a property list, as a uniform fill does (R12). + // Only a library color with its name is taken from it; any other color comes from + // the fixed field below. + if rec == 2 { + let mut w = Vec::new(); + if let Some(c @ Color::Spot { look: Some(_), .. }) = property_color(body, p, &mut w) { + named = Some((c, w)); + } + } + } + if !found { + return None; + } + } + let (line_type, cap, join) = (r.u16()?, r.u16()?, r.u16()?); + r.skip(p.outl_after_join)?; + let width = coord(&mut r, p)?.abs(); + let _stretch = r.u16()?; + r.skip(p.outl_after_stretch)?; + let _nib = angle(&mut r, p)?; + r.skip(p.outl_after_angle)?; + let color = match named { + Some((named, w)) => { + color(&mut r, p, &mut Vec::new())?; + for x in w { + push(warn, x); + } + named + } + None => color(&mut r, p, warn)?, + }; + r.skip(p.outl_after_color)?; + let count = usize::from(r.u16()?); + let first_dash = r.pos(); + let fits = r.left() / 2; + if count > fits { + push(warn, Warning::Damaged); + } + // At most 65,535; the read's dash limit is applied where shapes use them. + let dashes: Vec = (0..count.min(fits)).filter_map(|_| r.u16().map(f64::from)).collect(); + if let Some(after) = p.marker_after_dash { + let mut m = Rd::at(b, first_dash + after); + if matches!((m.u32(), m.u32()), (Some(s), Some(e)) if s != 0 || e != 0) { + push(warn, Warning::Arrowheads); + } + } + // Bit 0 of the line type: no outline (R13). + if line_type & 1 != 0 { + return Some((id, None)); + } + let cap = match cap { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }; + let join = match join { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }; + // Bit 2 of the line type marks the outline dashed; without it the dashes stored are not drawn + // (R48). + let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() }; + // Bit 4 of the line type: behind the fill (R49). + let behind_fill = line_type & 0x10 != 0; + // Bit 5 of the line type: scaled with the shape (R50). + let scale_with = line_type & 0x20 != 0; + Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with }))) +} + +/// The opacity and blend of argument 8000 from version 13 (R47): records of a u32 version, a u32 +/// length and a body. A body of version 1300 that is [`UNIFORM_LEN`] bytes long is a uniform +/// transparency: an f64 at byte 61 and the merge mode at byte 77. VectorCraft reads the f64 as the +/// transparency in percent, 0 opaque and 100 clear. `None` for any other argument, such as a lens, +/// and for a value out of range or a merge mode without a VectorCraft blend mode. +pub(crate) fn transparency(b: &[u8]) -> Option<(f32, Blend)> { + let mut r = Rd::new(b); + while r.left() >= 8 { + let (since, len) = (r.u32()?, r.u32()? as usize); + let body = r.bytes(len)?; + if since != TAG_1300 { + continue; + } + if body.len() != UNIFORM_LEN { + return None; + } + let value = Rd::at(body, 61).f64()?; + if !(0.0..=100.0).contains(&value) { + return None; + } + return Some(((1.0 - value / 100.0) as f32, blend(*body.get(77)?)?)); + } + None +} + +/// The length of a uniform transparency's record body (R47). +const UNIFORM_LEN: usize = 117; + +/// The blend mode of a transparency's merge mode byte (R47); `None` for the modes VectorCraft has +/// no blend mode for. +fn blend(mode: u8) -> Option { + Some(match mode { + 0 => Blend::Normal, + 9 => Blend::Multiply, + 11 => Blend::Lighten, + 12 => Blend::Darken, + 14 => Blend::Color, + 15 => Blend::Hue, + 16 => Blend::Saturation, + 17 => Blend::Luminosity, + 24 => Blend::Difference, + 28 => Blend::Screen, + 29 => Blend::Overlay, + 30 => Blend::SoftLight, + 31 => Blend::HardLight, + 33 => Blend::ColorDodge, + 34 => Blend::ColorBurn, + 36 => Blend::Exclusion, + _ => return None, + }) +} + +/// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name +/// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a +/// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does. +pub(crate) fn name(b: &[u8], p: &Profile, warn: &mut Vec) -> String { + if p.utf16_names { + let units = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0); + let (mut kept, hash) = capped(units, warn); + if hash.is_some() && kept.last().is_some_and(|u| (0xD800..0xDC00).contains(u)) { + kept.pop(); + } + with_hash(String::from_utf16_lossy(&kept), hash) + } else { + let bytes = b.iter().copied().take_while(|c| *c != 0); + let (kept, hash) = capped(bytes, warn); + with_hash(kept.into_iter().map(windows_1252).collect(), hash) + } +} + +/// The first [`MAX_NAME`] of `units`, and when there are more, an FNV-1a hash of them all, with a +/// warning. +fn capped>(units: impl Iterator + Clone, warn: &mut Vec) -> (Vec, Option) { + if units.clone().nth(MAX_NAME).is_none() { + return (units.collect(), None); + } + push(warn, Warning::TooDeep); + let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u.into()).wrapping_mul(0x0100_0000_01b3)); + (units.take(MAX_NAME).collect(), Some(hash)) +} + +/// `name`, followed by `hash` in hexadecimal when there is one. +fn with_hash(name: String, hash: Option) -> String { + match hash { + Some(h) => format!("{name} {h:016x}"), + None => name, + } +} + +/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes +/// are Latin-1. +const CP1252_HIGH: [char; 32] = [ + '€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–', + '—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ', +]; + +fn windows_1252(c: u8) -> char { + match c { + 0x80..=0x9F => CP1252_HIGH.get(usize::from(c - 0x80)).copied().unwrap_or('\u{FFFD}'), + _ => char::from(c), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An outline that names an arrowhead says so with a warning, in each version whose arrowhead + /// ids have a known place: 22 bytes after the first dash in versions 6 to 12, 20 from 13. + #[test] + fn arrowheads_are_named_from_version_6() { + let pen = crate::synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }; + let color = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100]; + for (version, place) in [ + (500, None), + (600, Some(22)), + (700, Some(22)), + (800, Some(22)), + (900, Some(22)), + (1000, Some(22)), + (1100, Some(22)), + (1200, Some(22)), + (1300, Some(20)), + (1700, Some(20)), + ] { + let p = crate::layout::for_version(version).unwrap(); + let plain = crate::synth::V(version).outline(7, pen, &color, &[]); + // The record ends with 32 bytes after its dashes, and this one has none. + let first_dash = plain.len() - 32; + let mut w = vec![]; + assert!(outline(&plain, &p, &mut w).is_some_and(|(id, o)| id == 7 && o.is_some()), "{version}"); + assert!(w.is_empty(), "{version}: {w:?}"); + let Some(place) = place else { continue }; + let mut arrow = plain.clone(); + arrow[first_dash + place..first_dash + place + 4].copy_from_slice(&9u32.to_le_bytes()); + let mut w = vec![]; + assert!(outline(&arrow, &p, &mut w).is_some(), "{version}"); + assert_eq!(w, vec![Warning::Arrowheads], "{version}"); + } + } + + #[test] + fn single_byte_names_read_as_windows_1252() { + let p = crate::layout::for_version(1100).unwrap(); + assert_eq!(name(b"Caf\xe9 \x80\x96\0junk", &p, &mut vec![]), "Café €–"); + let p = crate::layout::for_version(1200).unwrap(); + assert_eq!(name(&[0x41, 0, 0x42, 0, 0, 0, 0x43, 0], &p, &mut vec![]), "AB"); + } + + /// A layer name longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones and a hash + /// of the whole name, with a warning, in both encodings. A cut never keeps half of a surrogate + /// pair. + #[test] + fn long_layer_names_are_cut_with_a_hash() { + for version in [1100, 1200] { + let p = crate::layout::for_version(version).unwrap(); + let bytes = + |s: &str| if p.utf16_names { s.encode_utf16().flat_map(u16::to_le_bytes).collect::>() } else { s.as_bytes().to_vec() }; + let mut w = vec![]; + let a = name(&bytes(&"N".repeat(100_000)), &p, &mut w); + let b = name(&bytes(&format!("{}M", "N".repeat(99_999))), &p, &mut vec![]); + assert_ne!(a, b, "{version}"); + assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{version}: {}", a.len()); + assert_eq!(w, vec![Warning::TooDeep], "{version}"); + let mut w = vec![]; + assert_eq!(name(&bytes(&"N".repeat(MAX_NAME)), &p, &mut w), "N".repeat(MAX_NAME), "{version}"); + assert!(w.is_empty(), "{version}"); + } + let p = crate::layout::for_version(1200).unwrap(); + let emoji: Vec = format!("N{}", "\u{1F600}".repeat(200)).encode_utf16().flat_map(u16::to_le_bytes).collect(); + let cut = name(&emoji, &p, &mut vec![]); + assert!(!cut.contains('\u{FFFD}'), "{cut}"); + assert_eq!(cut.chars().filter(|c| *c == '\u{1F600}').count(), (MAX_NAME - 1) / 2); + } + + #[test] + fn colors_read_in_their_models() { + let p = crate::layout::for_version(500).unwrap(); + let rec = |model: u16, v: [u8; 4]| { + let mut b = model.to_le_bytes().to_vec(); + b.extend([0; 6]); + b.extend(v); + let mut w = vec![]; + (color(&mut Rd::new(&b), &p, &mut w), w) + }; + assert_eq!(rec(2, [100, 50, 0, 10]).0, Some(Color::Cmyk([1.0, 0.5, 0.0, 0.1]))); + assert_eq!(rec(5, [255, 0, 0, 0]).0, Some(Color::Rgb([0.0, 0.0, 1.0]))); + assert_eq!(rec(9, [255, 0, 0, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(rec(25, [7, 0, 40, 0]).0, Some(Color::Spot { name: "Spot 0:7".into(), tint: 0.4, look: None })); + // The same number in another library is another color. + let mut other = 25u16.to_le_bytes().to_vec(); + other.extend(3u16.to_le_bytes()); + other.extend([0; 4]); + other.extend([7, 0, 40, 0]); + assert_eq!(color(&mut Rd::new(&other), &p, &mut vec![]), Some(Color::Spot { name: "Spot 3:7".into(), tint: 0.4, look: None })); + let (c, w) = rec(6, [1, 2, 3, 4]); + assert_eq!((c, w), (Some(Color::Rgb([0.0; 3])), vec![Warning::UnknownColors])); + } + + #[test] + fn colors_of_versions_3_and_4_read_models_0_and_1() { + let read = |version: u16, model: u8, v: [u16; 4]| { + let p = crate::layout::for_version(version).unwrap(); + let b: Vec = if version < 400 { + std::iter::once(model).chain(v.map(|x| x as u8)).collect() + } else { + u16::from(model).to_le_bytes().into_iter().chain(v.iter().flat_map(|x| x.to_le_bytes())).chain([0, 0]).collect() + }; + let mut r = Rd::new(&b); + let mut w = vec![]; + let c = color(&mut r, &p, &mut w); + assert_eq!(r.left(), 0, "{version}"); + (c, w) + }; + for version in [300, 400] { + // Model 1 is CMYK in percent, not a library color as from version 5. + assert_eq!(read(version, 1, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}"); + assert_eq!(read(version, 2, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}"); + } + // Model 0: an ink number and a tint. Version 3 stores each as a u16 in its four bytes. + assert_eq!(read(300, 0, [0, 0, 60, 0]).0, Some(Color::Gray(0.6))); + assert_eq!(read(300, 0, [1, 0, 60, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(read(300, 0, [44, 1, 60, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks])); + assert_eq!(read(400, 0, [0, 60, 0, 0]).0, Some(Color::Gray(0.6))); + assert_eq!(read(400, 0, [1, 60, 0, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(read(400, 0, [300, 60, 0, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks])); + } + + #[test] + fn a_fixed_point_matrix_reads_its_factors_and_offsets() { + let raw: Vec = [65536i32, -32768, 1000, 131072, 16384, -500].iter().flat_map(|v| v.to_le_bytes()).collect(); + let m = fixed_matrix(&mut Rd::new(&raw), 0.5).unwrap(); + assert_eq!(m, Matrix([1.0, 2.0, -0.5, 0.25, 500.0, -250.0])); + assert!(fixed_matrix(&mut Rd::new(&raw[..23]), 0.5).is_none()); + } + + #[test] + fn long_names_that_start_alike_stay_apart() { + let read = |name: &str| { + let mut b = (name.encode_utf16().count() as u32).to_le_bytes().to_vec(); + b.extend(name.encode_utf16().flat_map(u16::to_le_bytes)); + let mut w = vec![]; + (counted_utf16(&mut Rd::new(&b), &mut w).unwrap(), w) + }; + let (a, w) = read(&"N".repeat(300)); + let (b, _) = read(&format!("{}M", "N".repeat(299))); + assert_ne!(a, b); + assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{a}"); + assert_eq!(w, vec![Warning::TooDeep]); + assert_eq!(read("Sky Blue"), ("Sky Blue".to_string(), vec![])); + // Padding doesn't count toward the length or the name. + let (padded, w) = read(&format!("{}\0\0", "N".repeat(MAX_NAME - 1))); + assert_eq!((padded, w), ("N".repeat(MAX_NAME - 1), vec![])); + } + + #[test] + fn a_tint_mixes_toward_white_and_comes_off_again() { + let shown = [0.6, 0.8, 1.0]; + let base = untinted(shown, 0.5); + assert!((base[0] - 0.2).abs() < 1e-6 && (base[1] - 0.6).abs() < 1e-6 && base[2] == 1.0); + } +} diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs new file mode 100644 index 0000000000..3f041b4c37 --- /dev/null +++ b/crates/cdr/src/riff.rs @@ -0,0 +1,465 @@ +//! The chunk index: one flat table of every chunk, a list's children contiguous, built without +//! recursion. Payloads are not copied: an entry names a range of the RIFF stream, of the bytes +//! inflated from `LIST cmpr`, or of a package's data stream (layouts R1 to R4, R27). + +use std::cell::Cell; +use std::collections::BTreeMap; +use std::io::Read as _; + +use crate::bytes::{Rd, u32_at}; +use crate::layout; +use crate::limits::Budget; +use crate::package::Streams; +use crate::{Error, Warning}; + +pub(crate) const LIST: [u8; 4] = *b"LIST"; +const CMPR: [u8; 4] = *b"cmpr"; +const CPNG: [u8; 4] = *b"CPng"; +/// What follows `CPng` before the zlib stream (R3). +const CPNG_HEAD: [u8; 4] = [1, 0, 4, 0]; +/// The size of a redirect record, and the stream number of one that holds its body (R27). +const REDIRECT: usize = 16; +const INLINE: u32 = u32::MAX; + +/// One chunk: 28 bytes. `start` and `len` give the payload (after a list's form type) in its +/// source: 0 is the RIFF stream followed by the inflated bytes, `s + 1` is data stream `s`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Chunk { + pub(crate) id: [u8; 4], + /// A list's form type; zeros for other chunks. + pub(crate) form: [u8; 4], + src: u32, + start: u32, + len: u32, + first: u32, + count: u32, +} + +impl Chunk { + pub(crate) fn is_list(&self, form: &[u8; 4]) -> bool { + self.id == LIST && &self.form == form + } +} + +/// Every chunk of a file, and the bytes they point into. +pub(crate) struct Index<'a> { + input: &'a [u8], + inflated: Vec, + chunks: Vec, + /// The version the form type names: hundreds, as `vrsn` stores it (0 when the `vrsn` chunk + /// decides). + pub(crate) form_version: u16, + /// A version 16+ package's data streams; chunks of 16 bytes are redirect records then. + streams: Option>, + /// Bytes that inflating may still produce. + left: Cell, + /// The bytes redirected lists have taken: (package member, start) to end. + lists: Cell>, + /// The bytes other redirected chunks have taken, the same way. + leaves: Cell>, + /// Bytes that redirects to bytes another chunk already took may still read. + shared_left: Cell, + /// The first `vrsn` chunk among the file's own chunks, once seen, and the version it names + /// (`None` when it can't be read) (R2). + vrsn: Option>, +} + +/// A list still to be split into its children. +struct Pending { + entry: usize, + src: u32, + /// Its children's bytes. + start: usize, + end: usize, + /// The size pool of a compressed list's stream (`start..end` in source 0). + pool: Option<(usize, usize)>, + depth: usize, +} + +/// What reading one chunk header gives. +enum Read { + Chunk(Chunk), + /// A redirect record whose body can't be found: the chunk is left out, its list read on. + Lost, + /// A redirect record into a data stream past a limit: the chunk is left out without the + /// damage warning. + PastLimit, + /// A redirect record to bytes another chunk took, past the shared-bytes limit: the chunk is + /// left out with the limit warning. + SharedPastLimit, +} + +/// The version the RIFF form type names (R1): `CDR5`..`CDR9`, `CDRA` (10) to `CDRH` (17) with `I` +/// unused, then `J` (18) on; `CDR ` is version 3. Some files use a lower-case `cdr`, which names +/// the same versions except that `cdr8` is the 8.01 variant. Templates of version 21 have the form +/// type `CDTQ`; for `CDT` the `vrsn` chunk names the version, so this gives 0 (R28). +pub(crate) fn form_version(form: [u8; 4]) -> Option { + let [a, b, c, v] = form; + match (&[a, b, c], v) { + (b"cdr", b'8') => Some(801), + (b"CDR" | b"cdr", b' ') => Some(300), + (b"CDR" | b"cdr", b'1'..=b'9') => Some(100 * u16::from(v - b'0')), + (b"CDR" | b"cdr", b'A'..=b'H') => Some(100 * u16::from(v - b'A' + 10)), + (b"CDR" | b"cdr", b'J'..=b'W') => Some(100 * u16::from(v - b'J' + 18)), + (b"CDT", b'A'..=b'Z') => Some(0), + _ => None, + } +} + +/// Does `bytes` start like a RIFF `.cdr` drawing (not the `CDRX` exchange variant)? +pub(crate) fn is_cdr_riff(bytes: &[u8]) -> bool { + bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12).and_then(|f| f.try_into().ok()).and_then(form_version).is_some() +} + +impl<'a> Index<'a> { + pub(crate) fn build(input: &'a [u8], streams: Option>, budget: &mut Budget, warn: &mut Vec) -> Result { + if input.len() > budget.limits.input { + return Err(Error::Limit("input size")); + } + let mut r = Rd::new(input); + if r.fourcc() != Some(*b"RIFF") { + return Err(Error::NotCdr); + } + let declared = r.u32().ok_or(Error::NotCdr)? as usize; + let form = r.fourcc().ok_or(Error::NotCdr)?; + let version = form_version(form).ok_or(Error::NotCdr)?; + // A file cut short keeps what it holds: its last chunk is truncated with a warning. A + // length that ends inside the form type is damage too, and the chunks after it are read. + let end = match declared.checked_add(8) { + Some(e) if (12..=input.len()).contains(&e) => e, + _ => { + push(warn, Warning::Damaged); + input.len() + } + }; + let left = Cell::new(budget.inflate_left()); + let mut ix = Index { + input, + inflated: Vec::new(), + chunks: Vec::new(), + form_version: version, + streams, + left, + lists: Cell::default(), + leaves: Cell::default(), + shared_left: Cell::new(budget.limits.member), + vrsn: None, + }; + ix.chunks.push(Chunk { id: *b"RIFF", form, src: 0, start: 12, len: 0, first: 0, count: 0 }); + let mut queue = vec![Pending { entry: 0, src: 0, start: 12, end, pool: None, depth: 0 }]; + while let Some(p) = queue.pop() { + ix.split(p, &mut queue, budget, warn)?; + } + Ok(ix) + } + + /// The bytes `start..end` of source `src`, or `None` when the range crosses its end. A data + /// stream is read on first use. + fn span(&self, src: u32, start: usize, end: usize) -> Option<&[u8]> { + if src > 0 { + let s = self.streams.as_ref()?; + return s.get(src as usize - 1, &self.left)?.get(start..end); + } + let n = self.input.len(); + if end <= n { + self.input.get(start..end) + } else if start >= n { + self.inflated.get(start - n..end - n) + } else { + None + } + } + + pub(crate) fn data(&self, c: &Chunk) -> &[u8] { + let start = c.start as usize; + match self.span(c.src, start, start + c.len as usize) { + Some(b) => b, + None => { + if let Some(s) = &self.streams + && !self.past_limit(c.src) + { + s.note_damage(); + } + &[] + } + } + } + + /// Was source `src` a data stream left out because it is past a limit? Its chunks are then + /// left out with that warning alone. + fn past_limit(&self, src: u32) -> bool { + src > 0 && self.streams.as_ref().is_some_and(|s| s.past_limit(src as usize - 1)) + } + + pub(crate) fn children(&self, c: &Chunk) -> &[Chunk] { + let first = c.first as usize; + self.chunks.get(first..first + c.count as usize).unwrap_or_default() + } + + pub(crate) fn root(&self) -> Option<&Chunk> { + self.chunks.first() + } + + /// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1, + /// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names + /// (R28). Letters count differently from the version 24 update on (R1), so when both name a + /// version after 27 the `vrsn` chunk's is the one refused. The `cdr8` form type alone makes a + /// file the 8.01 variant, whatever its `vrsn` chunk names (R1). + pub(crate) fn version(&self) -> u16 { + match self.vrsn.flatten() { + _ if self.form_version == 801 => 801, + Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v, + Some(v) if self.form_version == 0 => v, + Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v, + _ => self.form_version, + } + } + + /// The warnings for data streams that were left out. + pub(crate) fn stream_warnings(&self, warn: &mut Vec) { + if let Some(s) = &self.streams { + s.warnings(warn); + } + } + + /// Split list `p` into its children, appended to the table together; their lists are queued. + fn split(&mut self, p: Pending, queue: &mut Vec, budget: &mut Budget, warn: &mut Vec) -> Result<(), Error> { + let first = self.chunks.len(); + let mut at = p.start; + let mut lists = Vec::new(); + while at < p.end { + let Some((read, next, cut)) = self.read_chunk(p.src, at, p.end, p.pool) else { + push(warn, Warning::Damaged); + break; + }; + if cut { + push(warn, Warning::Damaged); + } + at = next; + // A redirect record whose body can't be found counts as well, so that lists redirected + // to again and again can't repeat such records past the limit. + budget.take_chunk()?; + let chunk = match read { + Read::Chunk(chunk) => chunk, + Read::Lost => { + push(warn, Warning::Damaged); + continue; + } + Read::PastLimit => continue, + Read::SharedPastLimit => { + push(warn, Warning::TooDeep); + continue; + } + }; + if p.entry == 0 && chunk.id == *b"vrsn" && self.vrsn.is_none() { + let at = chunk.start as usize; + self.vrsn = Some(self.span(chunk.src, at, at + chunk.len as usize).and_then(|b| Rd::new(b).u16())); + } + if chunk.id == LIST { + lists.push(self.chunks.len()); + } + self.chunks.push(chunk); + } + let count = (self.chunks.len() - first) as u32; + if let Some(parent) = self.chunks.get_mut(p.entry) { + parent.first = first as u32; + parent.count = count; + } + for i in lists { + let Some(c) = self.chunks.get(i).copied() else { continue }; + // From version 7 a `LIST stlt` holds the style tables, not chunks (R4); its body is read + // whole (R45). Before version 7 it holds chunks. The file's own chunks, its `vrsn` + // among them, are all read before this. + if c.form == *b"stlt" && self.version() >= 700 { + continue; + } + if p.depth + 1 > budget.limits.depth { + push(warn, Warning::TooDeep); + continue; + } + let (start, end) = (c.start as usize, c.start as usize + c.len as usize); + if c.form == CMPR && p.pool.is_none() { + match self.inflate_cmpr(c.src, start, end) { + Ok((s, e, pool)) => queue.push(Pending { entry: i, src: 0, start: s, end: e, pool: Some(pool), depth: p.depth + 1 }), + Err(Error::Limit(what)) => return Err(Error::Limit(what)), + Err(_) => push(warn, Warning::Damaged), + } + } else { + queue.push(Pending { entry: i, src: c.src, start, end, pool: p.pool, depth: p.depth + 1 }); + } + } + Ok(()) + } + + /// The chunk at `at` (before `end`) of source `src`, and where the next one starts. In a + /// compressed stream the size field is an index into the size pool (R3); in a version 16+ + /// package a chunk of 16 bytes outside one is a redirect record (R27). The flag is set for a + /// list cut short at `end`. + fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize, bool)> { + let head = self.span(src, at, at.checked_add(8)?.min(end))?; + let id: [u8; 4] = head.get(..4)?.try_into().ok()?; + let raw = u32_at(head, 4)? as usize; + let size = match pool { + None => raw, + Some((ps, pe)) => { + let off = raw.checked_mul(4)?.checked_add(ps)?; + (off.checked_add(4)? <= pe).then_some(())?; + u32_at(self.span(0, off, off + 4)?, 0)? as usize + } + }; + let body = at + 8; + // A list cut short by the end of its parent keeps the bytes it has, so the children + // before the cut are read; the caller warns that it is damaged. Other chunks are lost. + let (size, cut) = match body.checked_add(size) { + Some(e) if e <= end => (size, false), + _ if id == LIST => (end.checked_sub(body)?, true), + _ => return None, + }; + let next = (body + size + (size & 1)).min(end); + if cut { + return Some((self.chunk(id, src, body, size).map_or(Read::Lost, Read::Chunk), next, true)); + } + if self.streams.is_some() && pool.is_none() && size == REDIRECT { + let read = match self.redirect(id, src, body) { + Some(read) => read, + None if self.redirect_past_limit(src, body) => Read::PastLimit, + None => Read::Lost, + }; + return Some((read, next, false)); + } + Some((Read::Chunk(self.chunk(id, src, body, size)?), next, false)) + } + + /// Chunk `id` whose body is `len` bytes at `body` of source `src`; a list's body starts with + /// its form type. + fn chunk(&self, id: [u8; 4], src: u32, body: usize, len: usize) -> Option { + let (form, start) = if id == LIST { + let f: [u8; 4] = self.span(src, body, body.checked_add(4).filter(|_| len >= 4)?)?.try_into().ok()?; + (f, body + 4) + } else { + ([0; 4], body) + }; + let len = len - (start - body); + Some(Chunk { id, form, src, start: u32::try_from(start).ok()?, len: u32::try_from(len).ok()?, first: 0, count: 0 }) + } + + /// The chunk the redirect record at `body` of `src` stands for (R27): stream, length, offset + /// and a reserved u32. Stream `0xFFFFFFFF` holds at most 8 bytes in the record itself, after + /// the length. The body is not read again as a redirect record. `None` when the body can't + /// be found. + /// + /// A redirected list whose bytes overlap those of an earlier redirected list, in any stream of + /// the same package member, is left out, so that no list is split twice. Other chunks may + /// share bytes: each one after the first to read them takes their length from the + /// shared-bytes limit (the member limit), so that many redirects to one body can't decode it + /// without end. + fn redirect(&self, id: [u8; 4], src: u32, body: usize) -> Option { + let mut r = Rd::new(self.span(src, body, body + REDIRECT)?); + let stream = r.u32()?; + let len = r.u32()? as usize; + if stream == INLINE { + return (len <= 8).then(|| self.chunk(id, src, body + 8, len).map(Read::Chunk))?; + } + let off = r.u32()? as usize; + let streams = self.streams.as_ref()?; + let size = streams.size(stream as usize)?; + let end = off.checked_add(len).filter(|&e| e <= size)?; + let member = streams.member_of(stream as usize)?; + if id == LIST { + if !claim(&self.lists, member, off, end) { + return None; + } + } else if !claim(&self.leaves, member, off, end) { + let left = self.shared_left.get(); + if len > left { + return Some(Read::SharedPastLimit); + } + self.shared_left.set(left - len); + } + // Only a list's form type is read now; other bodies are read when the mapping asks. + self.chunk(id, stream.checked_add(1)?, off, len).map(Read::Chunk) + } + + /// Does the redirect record at `body` of `src` point into a data stream past a limit? + fn redirect_past_limit(&self, src: u32, body: usize) -> bool { + let stream = self.span(src, body, body + 4).and_then(|b| u32_at(b, 0)); + stream.is_some_and(|s| s != INLINE && self.past_limit(s.saturating_add(1))) + } + + /// Inflate the two blocks of a `LIST cmpr` body at `start..end` of `src` (R3) → the chunk + /// stream and the size pool, as ranges of source 0. + fn inflate_cmpr(&mut self, src: u32, start: usize, end: usize) -> Result<(usize, usize, (usize, usize)), Error> { + let body = self.span(src, start, end).ok_or(Error::Damaged("compressed list"))?; + let mut r = Rd::new(body); + let c1 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize; + r.skip(4).ok_or(Error::Damaged("compressed list"))?; + let c2 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize; + let block = |at: usize, len: usize| -> Result<&[u8], Error> { + let b = body.get(at..at.checked_add(len).ok_or(Error::Damaged("compressed list"))?).ok_or(Error::Damaged("compressed list"))?; + let mut h = Rd::new(b); + if h.fourcc() != Some(CPNG) || h.fourcc() != Some(CPNG_HEAD) { + return Err(Error::Damaged("compressed block")); + } + Ok(b.get(8..).unwrap_or_default()) + }; + let second_at = c1.checked_add(16).ok_or(Error::Damaged("compressed list"))?; + let (first, second) = (block(16, c1)?.to_vec(), block(second_at, c2)?.to_vec()); + let base = self.input.len(); + let stream = self.inflate(&first)?; + let pool = self.inflate(&second)?; + Ok((base + stream.0, base + stream.1, (base + pool.0, base + pool.1))) + } + + /// Inflate zlib `data` onto the end of the inflated bytes, within what is left → its range + /// there. + fn inflate(&mut self, data: &[u8]) -> Result<(usize, usize), Error> { + let at = self.inflated.len(); + let left = self.left.get(); + let reader = flate2::read::ZlibDecoder::new(data); + // One byte past what is left tells a stream that is too long from one that just fits. + let got = match reader.take((left as u64).saturating_add(1)).read_to_end(&mut self.inflated) { + Ok(n) => n, + Err(_) => { + // What a stream inflated before it failed counts toward the limit too, so that + // streams that fail late can't inflate past it again and again. + let produced = self.inflated.len().saturating_sub(at); + self.left.set(left.saturating_sub(produced)); + self.inflated.truncate(at); + return Err(Error::Damaged("compressed block")); + } + }; + if got > left { + self.inflated.truncate(at); + return Err(Error::Limit("inflated size")); + } + self.left.set(left - got); + if self.input.len().saturating_add(self.inflated.len()) > u32::MAX as usize { + return Err(Error::Limit("inflated size")); + } + Ok((at, at + got)) + } +} + +/// Take bytes `start..end` of package member `member` in `claimed`, or `false` when an earlier +/// redirect there took any of them. Empty ranges take nothing. +fn claim(claimed: &Cell>, member: usize, start: usize, end: usize) -> bool { + if start == end { + return true; + } + let mut taken = claimed.take(); + let before = taken.range(..=(member, start)).next_back().is_some_and(|(&(m, _), &e)| m == member && e > start); + let after = taken.range((member, start)..).next().is_some_and(|(&(m, s), _)| m == member && s < end); + let free = !before && !after; + if free { + taken.insert((member, start), end); + } + claimed.set(taken); + free +} + +/// Add `w` to the warnings once. +pub(crate) fn push(warn: &mut Vec, w: Warning) { + if !warn.contains(&w) { + warn.push(w); + } +} diff --git a/crates/cdr/src/styles.rs b/crates/cdr/src/styles.rs new file mode 100644 index 0000000000..e4022563c2 --- /dev/null +++ b/crates/cdr/src/styles.rs @@ -0,0 +1,258 @@ +//! The style table in a `LIST stlt` of versions 7 to 15 (R45): the fill and outline records that a +//! style gives the objects that name it and have no fill or outline argument of their own. + +use std::collections::{HashMap, HashSet}; + +use crate::Error; +use crate::bytes::{Rd, u32_at}; +use crate::limits::Budget; + +/// One style: its parent, and the fill and outline table entries it names (0: none). +#[derive(Clone, Copy)] +struct Style { + parent: u32, + fill: u32, + outline: u32, +} + +/// The styles of a drawing: for each style id, the fill and outline records it gives, its +/// parents' included. +#[derive(Default)] +pub(crate) struct Styles { + fills: HashMap, + outlines: HashMap, +} + +impl Styles { + /// The style table in body `b` of a `LIST stlt` of `version` (R45), or `None` when it doesn't + /// parse to its end. Its fill and outline entries and its styles count toward the chunks a + /// read takes. + pub(crate) fn read(b: &[u8], version: u16, budget: &mut Budget) -> Result, Error> { + let mut limit = None; + let styles = parse(b, version, &mut |n| match budget.take_chunks(n) { + Ok(()) => true, + Err(e) => { + limit = Some(e); + false + } + }); + match limit { + Some(e) => Err(e), + None => Ok(styles), + } + } + + /// The fill record that style `id` gives. + pub(crate) fn fill(&self, id: u32) -> Option { + self.fills.get(&id).copied() + } + + /// The outline record that style `id` gives. + pub(crate) fn outline(&self, id: u32) -> Option { + self.outlines.get(&id).copied() + } +} + +/// The style table in `b`. `take` is asked for each count of entries or styles before they are +/// read; a `false` stops the read. +fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option { + let mut r = Rd::new(b); + let count = r.u32()? as usize; + if count == 0 { + return (r.left() == 0).then(Styles::default); + } + // Fill entries carry 48 more bytes from version 13. + let fills = table(&mut r, if version >= 1300 { 60 } else { 12 }, take)?; + let outlines = table(&mut r, 12, take)?; + // The text style tables: fonts, alignments, spacings, two tables of fixed records, bullets, + // indents, hyphenation and drop caps, and from version 8.01 one more. + skip_table(&mut r, if version >= 1000 { 60 } else { 44 })?; + skip_table(&mut r, 12)?; + skip_table(&mut r, 52)?; + skip_table(&mut r, 152)?; + skip_table(&mut r, 784)?; + let bullets = r.u32()?; + for _ in 0..bullets { + bullet(&mut r, version)?; + } + skip_table(&mut r, 28)?; + skip_table(&mut r, if version >= 1300 { 36 } else { 32 })?; + skip_table(&mut r, 28)?; + if version >= 801 { + skip_table(&mut r, 12)?; + } + // Each style is at least 32 bytes. + if count > r.left() / 32 || !take(count) { + return None; + } + let mut styles = HashMap::new(); + for _ in 0..count { + let (id, s) = style(&mut r, version)?; + styles.entry(id).or_insert(s); + } + if r.left() != 0 { + return None; + } + let mut work = 0; + Some(Styles { fills: resolve(&styles, &fills, |s| s.fill, &mut work), outlines: resolve(&styles, &outlines, |s| s.outline, &mut work) }) +} + +/// For each style, the record of `table` that its own entry names, or the nearest parent's where +/// its entry is 0. Each style is resolved once, and each path forgets only the styles on it, so a +/// chain of any length takes time in proportion to the styles; a chain that comes back to a style +/// on it, or reaches a style that isn't there, gives no record. `work` counts the styles visited +/// and forgotten. +fn resolve(styles: &HashMap, table: &HashMap, entry: impl Fn(&Style) -> u32, work: &mut usize) -> HashMap { + // `None`: resolved to no record. + let mut done: HashMap> = HashMap::new(); + let mut path = Vec::new(); + let mut on_path = HashSet::new(); + for &start in styles.keys() { + let mut id = start; + let found = loop { + *work += 1; + if let Some(&known) = done.get(&id) { + break known; + } + let Some(s) = styles.get(&id) else { break None }; + // Back at a style on this path: a cycle. + if !on_path.insert(id) { + break None; + } + path.push(id); + match entry(s) { + 0 => id = s.parent, + e => break table.get(&e).copied(), + } + }; + for id in path.drain(..) { + *work += 1; + on_path.remove(&id); + done.insert(id, found); + } + } + done.into_iter().filter_map(|(id, r)| Some((id, r?))).collect() +} + +/// A table of a u32 count and entries of `size` bytes, each a table id, 4 bytes and a record id. +fn table(r: &mut Rd, size: usize, take: &mut dyn FnMut(usize) -> bool) -> Option> { + let n = r.u32()? as usize; + if n > r.left() / size || !take(n) { + return None; + } + let mut out = HashMap::new(); + for _ in 0..n { + let e = r.bytes(size)?; + out.entry(u32_at(e, 0)?).or_insert(u32_at(e, 8)?); + } + Some(out) +} + +/// A table of a u32 count and entries of `size` bytes, passed over. +fn skip_table(r: &mut Rd, size: usize) -> Option<()> { + let n = r.u32()? as usize; + r.skip(n.checked_mul(size)?) +} + +/// A bullet record, passed over: its length depends on a u32 inside it. +fn bullet(r: &mut Rd, version: u16) -> Option<()> { + r.skip(40)?; + if version >= 1300 { + if version >= 1400 { + r.skip(4)?; + } + let more = r.u32()?; + return r.skip(if more != 0 { 68 } else { 12 }); + } + r.skip(if version >= 1000 { 28 } else { 20 })?; + let more = r.u32()?; + if more != 0 { + r.skip(8)?; + } + r.skip(8) +} + +/// A style record: its kind (u32), id, parent, 8 bytes, a name length and the name (bytes before +/// version 12, UTF-16 units from it), the fill and outline entries, then the entries of text +/// styles (kinds 2 and 3). +fn style(r: &mut Rd, version: u16) -> Option<(u32, Style)> { + let kind = r.u32()?; + let (id, parent) = (r.u32()?, r.u32()?); + r.skip(8)?; + let len = r.u32()? as usize; + r.skip(len.checked_mul(if version >= 1200 { 2 } else { 1 })?)?; + let (fill, outline) = (r.u32()?, r.u32()?); + if kind > 1 { + r.skip(if version >= 801 { 20 } else { 16 })?; + } + if kind > 2 { + r.skip(20)?; + } + Some((id, Style { parent, fill, outline })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::synth::{self, V}; + + fn read(b: &[u8], version: u16) -> Option { + Styles::read(b, version, &mut Budget::new(Limits::default())).unwrap() + } + + #[test] + fn styles_that_name_each_other_as_parents_end() { + let looped = [synth::Style { id: 0x10, parent: 0x11, fill: 0, outline: 0 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let s = read(&synth::stlt_body(V(700), &[(0x100, 1)], &[], &looped, false), 700).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x11), s.fill(0x12)), (None, None, None)); + } + + #[test] + fn a_long_chain_of_parents_reaches_the_style_that_names_an_entry() { + let mut chain = vec![synth::Style { id: 1, parent: 0, fill: 0x100, outline: 0 }]; + chain.extend((2..=500).map(|id| synth::Style { id, parent: id - 1, fill: 0, outline: 0 })); + let s = read(&synth::stlt_body(V(1100), &[(0x100, 7)], &[], &chain, false), 1100).unwrap(); + assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None)); + } + + /// A loop of 2,000 styles, which every walk into it follows around, leaves the walks of 20,000 + /// other styles no more work than the styles they visit. + #[test] + fn one_long_walk_does_not_slow_the_walks_after_it() { + let mut styles: HashMap = (1..=2000).map(|id| (id, Style { parent: id % 2000 + 1, fill: 0, outline: 0 })).collect(); + styles.extend((10_001..=30_000).map(|id| (id, Style { parent: 0, fill: 0x100, outline: 0 }))); + let table = HashMap::from([(0x100, 7)]); + let mut work = 0; + let fills = resolve(&styles, &table, |s| s.fill, &mut work); + assert_eq!((fills.get(&1), fills.get(&10_001), fills.len()), (None, Some(&7), 20_000)); + assert!(work <= 4 * styles.len(), "{work}"); + } + + #[test] + fn an_entry_missing_from_its_table_names_no_record() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }]; + let s = read(&synth::stlt_body(V(1300), &[(0x100, 1)], &[(0x200, 2)], &styles, false), 1300).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x10)), (None, Some(2))); + } + + #[test] + fn counts_past_the_body_do_not_parse() { + let mut b = synth::stlt_body(V(900), &[], &[], &[], false); + b[..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(read(&b, 900).is_none()); + let empty = 0u32.to_le_bytes(); + assert!(read(&empty, 900).is_some()); + assert!(read(&[], 900).is_none()); + } + + #[test] + fn entries_and_styles_count_toward_the_chunk_limit() { + let styles: Vec<_> = (1..=10).map(|id| synth::Style { id, parent: 0, fill: 0x100, outline: 0 }).collect(); + let b = synth::stlt_body(V(1000), &[(0x100, 1)], &[], &styles, false); + let mut budget = Budget::new(Limits { chunks: 10, ..Limits::default() }); + assert_eq!(Styles::read(&b, 1000, &mut budget).err(), Some(Error::Limit("chunk count"))); + let mut budget = Budget::new(Limits { chunks: 11, ..Limits::default() }); + assert!(Styles::read(&b, 1000, &mut budget).is_ok_and(|s| s.is_some())); + } +} diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs new file mode 100644 index 0000000000..e109d8bf1d --- /dev/null +++ b/crates/cdr/src/synth.rs @@ -0,0 +1,1083 @@ +//! Synthetic drawings for tests and fuzz seeds, built from the layouts in `PROVENANCE.md`. Not a +//! `.cdr` writer: nothing checks that other programs open these files. + +use std::io::Write as _; + +/// A chunk or a list, before it is laid out. +#[derive(Clone, Debug)] +pub enum Node { + Chunk([u8; 4], Vec), + List([u8; 4], Vec), +} + +pub fn chunk(id: &[u8; 4], data: Vec) -> Node { + Node::Chunk(*id, data) +} + +pub fn list(form: &[u8; 4], children: Vec) -> Node { + Node::List(*form, children) +} + +fn put(out: &mut Vec, id: &[u8; 4], size: u32, body: &[u8], len: usize) { + out.extend(id); + out.extend(size.to_le_bytes()); + out.extend(body); + if len % 2 == 1 { + out.push(0); + } +} + +/// `n` laid out with real sizes. +pub fn plain(n: &Node) -> Vec { + let mut out = Vec::new(); + match n { + Node::Chunk(id, data) => put(&mut out, id, data.len() as u32, data, data.len()), + Node::List(form, kids) => { + let mut body = form.to_vec(); + body.extend(kids.iter().flat_map(plain)); + put(&mut out, b"LIST", body.len() as u32, &body, body.len()); + } + } + out +} + +/// `n` laid out for a compressed stream: each size field is an index into `pool`. +fn pooled(n: &Node, pool: &mut Vec) -> Vec { + let mut out = Vec::new(); + let (id, body) = match n { + Node::Chunk(id, data) => (*id, data.clone()), + Node::List(form, kids) => { + let mut body = form.to_vec(); + for k in kids { + body.extend(pooled(k, pool)); + } + (*b"LIST", body) + } + }; + let index = pool.len() as u32; + pool.push(body.len() as u32); + put(&mut out, &id, index, &body, body.len()); + out +} + +fn zlib(data: &[u8]) -> Vec { + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// A `LIST cmpr` holding `children` (R3). +pub fn cmpr(children: &[Node]) -> Node { + let mut pool = Vec::new(); + let stream: Vec = children.iter().flat_map(|c| pooled(c, &mut pool)).collect(); + let sizes: Vec = pool.iter().flat_map(|s| s.to_le_bytes()).collect(); + let block = |raw: &[u8]| { + let mut b = b"CPng".to_vec(); + b.extend([1, 0, 4, 0]); + b.extend(zlib(raw)); + b + }; + let (b1, b2) = (block(&stream), block(&sizes)); + let mut body = Vec::new(); + for (c, u) in [(b1.len(), stream.len()), (b2.len(), sizes.len())] { + body.extend((c as u32).to_le_bytes()); + body.extend((u as u32).to_le_bytes()); + } + body.extend(b1); + body.extend(b2); + Node::Chunk(*b"LIST", [b"cmpr".to_vec(), body].concat()) +} + +/// The form type letter of `version` (hundreds) (R1). +pub fn form(version: u16) -> [u8; 4] { + let n = (version / 100) as u8; + let c = match n { + // Version 3 has a space where later versions have their character. + 3 => b' ', + 0..=9 => b'0' + n, + 10..=17 => b'A' + n - 10, + _ => b'J' + n - 18, + }; + [b'C', b'D', b'R', c] +} + +/// A RIFF file of `version` holding `children`. +pub fn riff(version: u16, children: &[Node]) -> Vec { + let mut body = form(version).to_vec(); + for c in children { + body.extend(match c { + // A prebuilt `LIST cmpr` carries its own form type. + Node::Chunk(id, data) if id == b"LIST" => { + let mut o = Vec::new(); + put(&mut o, id, data.len() as u32, data, data.len()); + o + } + _ => plain(c), + }); + } + let mut out = b"RIFF".to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// Field writers for one version. +#[derive(Clone, Copy, Debug)] +pub struct V(pub u16); + +impl V { + pub fn short(self) -> bool { + self.0 < 600 + } + + pub fn word(self, v: usize) -> Vec { + if self.short() { (v as u16).to_le_bytes().to_vec() } else { (v as u32).to_le_bytes().to_vec() } + } + + /// Rectangle coordinates of `w` × `h` points with corners of `radius` points: coordinates + /// before version 15 (R15), from 15 f64 sizes and radii as shares of half the shorter side + /// (R29). + pub fn rect(self, w: f64, h: f64, radius: f64) -> Vec { + if self.0 < 1500 { + let n = if self.0 >= 900 { 4 } else { 1 }; + let mut out = [self.coord(w), self.coord(h)].concat(); + for _ in 0..n { + out.extend(self.coord(radius)); + } + return out; + } + let units = |pt: f64| pt / 72.0 * 254_000.0; + let mut out = Vec::new(); + for v in [units(w), units(h), 1.0, 1.0] { + out.extend(v.to_le_bytes()); + } + out.extend([0; 8]); + let share = radius / (w.abs().min(h.abs()) / 2.0); + for k in 0..4 { + if k > 0 { + out.extend([0; 16]); + } + out.extend(share.to_le_bytes()); + } + out + } + + /// A length in points as a coordinate. + pub fn coord(self, pt: f64) -> Vec { + if self.short() { + ((pt / 72.0 * 1000.0).round() as i16).to_le_bytes().to_vec() + } else { + ((pt / 72.0 * 254_000.0).round() as i32).to_le_bytes().to_vec() + } + } + + pub fn angle(self, deg: f64) -> Vec { + if self.short() { ((deg * 10.0).round() as i16).to_le_bytes().to_vec() } else { ((deg * 1_000_000.0).round() as i32).to_le_bytes().to_vec() } + } + + /// A `loda` record of object type `kind` (R6): header, arguments, offsets, then the types in + /// reverse. + pub fn loda(self, kind: u32, args: &[(u32, Vec)]) -> Vec { + let w = if self.short() { 2 } else { 4 }; + let head = 5 * w; + let mut body: Vec = Vec::new(); + let mut offsets = Vec::new(); + for (_, a) in args { + offsets.push(head + body.len()); + body.extend(a); + } + offsets.push(head + body.len()); + let offsets_at = head + body.len(); + let types_at = offsets_at + offsets.len() * w; + let total = types_at + args.len() * w; + let mut out = Vec::new(); + for f in [total, args.len(), offsets_at, types_at, kind as usize] { + out.extend(self.word(f)); + } + out.extend(body); + for o in offsets { + out.extend(self.word(o)); + } + for (t, _) in args.iter().rev() { + out.extend(self.word(*t as usize)); + } + out + } + + /// A `trfd` of `matrices` `[a, b, c, d, e, f]` with offsets in points (R8); before version 5 + /// each matrix is in fixed point (R37). + pub fn trfd(self, matrices: &[[f64; 6]]) -> Vec { + let w = if self.short() { 2 } else { 4 }; + let head = 3 * w; + let table = head; + let mut entries = Vec::new(); + let mut offsets = Vec::new(); + // The table holds one offset more than the entries: the record's end (R51). + let first = table + (matrices.len() + 1) * w; + for m in matrices { + offsets.push(first + entries.len()); + if self.0 >= 1300 { + entries.extend([0; 8]); + } + entries.extend(8u16.to_le_bytes()); + if !self.short() { + entries.extend([0; 6]); + } + if self.0 < 500 { + entries.extend(fixed_matrix(m)); + continue; + } + let unit = if self.short() { 1000.0 / 72.0 } else { 254_000.0 / 72.0 }; + let [a, b, c, d, e, f] = *m; + for v in [a, c, e * unit, b, d, f * unit] { + entries.extend(v.to_le_bytes()); + } + } + offsets.push(first + entries.len()); + let mut out = Vec::new(); + for f in [first + entries.len(), matrices.len(), table] { + out.extend(self.word(f)); + } + for o in offsets { + out.extend(self.word(o)); + } + out.extend(entries); + out + } + + /// A curve's point list (R16). + pub fn points(self, pts: &[(f64, f64, u8)]) -> Vec { + let mut out = (pts.len() as u32).to_le_bytes().to_vec(); + for (x, y, _) in pts { + out.extend(self.coord(*x)); + out.extend(self.coord(*y)); + } + out.extend(pts.iter().map(|p| p.2)); + out + } + + /// A uniform fill record (R11) of 12-byte color `color`. + pub fn fill(self, id: u32, color: &[u8; 12]) -> Vec { + let mut out = id.to_le_bytes().to_vec(); + if self.0 >= 1300 { + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(color); + props.extend([0, 0, 0, 0, 0]); + let mut solid = 1300u32.to_le_bytes().to_vec(); + solid.extend((props.len() as u32).to_le_bytes()); + solid.extend(props); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(solid); + out.extend(1300u32.to_le_bytes()); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + } else { + out.extend(1u16.to_le_bytes()); + out.extend([0, 0]); + out.extend(color); + } + out + } + + /// An outline record (R12) of `pen`, `color` and `dashes`. + pub fn outline(self, id: u32, pen: Pen, color: &[u8; 12], dashes: &[u16]) -> Vec { + let Pen { line_type, width, cap, join } = pen; + let mut out = id.to_le_bytes().to_vec(); + if self.0 >= 1300 { + out.extend(1u32.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + } + for f in [line_type, cap, join] { + out.extend(f.to_le_bytes()); + } + let v = self.0; + out.extend(vec![0; if (600..1300).contains(&v) { 2 } else { 0 }]); + out.extend(self.coord(width)); + out.extend(100u16.to_le_bytes()); + out.extend(vec![0; if self.short() { 0 } else { 2 }]); + out.extend(self.angle(0.0)); + out.extend(vec![ + 0; + if v >= 1300 { + 46 + } else if self.short() { + 0 + } else { + 52 + } + ]); + out.extend(color); + out.extend(vec![0; if self.short() { 10 } else { 16 }]); + out.extend((dashes.len() as u16).to_le_bytes()); + for d in dashes { + out.extend(d.to_le_bytes()); + } + out.extend([0; 32]); + out + } +} + +/// An outline's line type (bit 0: none), width in points, cap and join. +#[derive(Clone, Copy, Debug)] +pub struct Pen { + pub line_type: u16, + pub width: f64, + pub cap: u16, + pub join: u16, +} + +/// A 12-byte color record (R14) of `model` and its four value bytes. +pub fn color(model: u16, v: [u8; 4]) -> [u8; 12] { + let mut c = [0; 12]; + c[..2].copy_from_slice(&model.to_le_bytes()); + c[8..].copy_from_slice(&v); + c +} + +/// A version 4 color (R36): `model` and its four values as u16, then 2 bytes. +pub fn color4(model: u16, v: [u16; 4]) -> [u8; 12] { + let mut c = [0; 12]; + c[..2].copy_from_slice(&model.to_le_bytes()); + for (k, x) in v.into_iter().enumerate() { + c[2 + 2 * k..4 + 2 * k].copy_from_slice(&x.to_le_bytes()); + } + c +} + +/// A color of versions 1 to 3 (R36): `model` and its four value bytes. +pub fn color3(model: u8, v: [u8; 4]) -> [u8; 5] { + [model, v[0], v[1], v[2], v[3]] +} + +/// A matrix `[a, b, c, d, e, f]` with offsets in points as six i32 `a c tx b d ty`: the factors in +/// 16.16 fixed point, the offsets in 1/1000 inch (R37). +fn fixed_matrix(m: &[f64; 6]) -> Vec { + let [a, b, c, d, e, f] = *m; + let fixed = |v: f64| (v * 65536.0).round() as i32; + let units = |pt: f64| (pt / 72.0 * 1000.0).round() as i32; + [fixed(a), fixed(c), units(e), fixed(b), fixed(d), units(f)].iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// The transforms argument (100) of a version 3 object or group (R33): one matrix entry for each +/// of `matrices` `[a, b, c, d, e, f]` with offsets in points, applied in the order given. +pub fn transforms3(matrices: &[[f64; 6]]) -> Vec { + let first = 4 + 10 * matrices.len(); + let mut out = vec![0, 0]; + out.extend((matrices.len() as u16).to_le_bytes()); + for i in 0..matrices.len() { + out.extend(0x8cu16.to_le_bytes()); + out.extend([0; 4]); + out.extend(((first + 24 * i) as u16).to_le_bytes()); + out.extend([0; 2]); + } + out.extend(matrices.iter().flat_map(fixed_matrix)); + out +} + +/// The fill argument (20) of a version 3 object (R34): the type byte, then `color` for a uniform +/// fill (type 1). +pub fn fill3(kind: u8, color: &[u8]) -> Vec { + let mut out = vec![kind]; + out.extend(color); + out +} + +/// The outline argument (10) of a version 3 object (R35) of `pen`, `color` and `dashes`; bit 0 of +/// its flags is set unless the pen's line type says no outline. +pub fn outline3(pen: Pen, color: [u8; 5], dashes: &[u8]) -> Vec { + let v = V(300); + let mut out = vec![u8::from(pen.line_type & 1 == 0)]; + out.extend(v.coord(pen.width)); + out.extend(100u16.to_le_bytes()); + out.extend(v.angle(0.0)); + out.extend(color); + out.extend([0; 7]); + out.push(dashes.len() as u8); + let mut area = dashes.to_vec(); + area.resize(10, 0); + out.extend(area); + out.extend(pen.join.to_le_bytes()); + out.extend(pen.cap.to_le_bytes()); + out.extend([0; 8]); + out +} + +/// A version 3 group (R33): its own `lobj` with the transforms that place `objects`, then the +/// objects. +pub fn group3(matrices: &[[f64; 6]], objects: Vec) -> Node { + let mut kids = vec![chunk(b"flgs", vec![0, 0, 0, 0x10]), chunk(b"lobj", V(300).loda(0, &[(100, transforms3(matrices))]))]; + kids.extend(objects); + list(b"grp ", kids) +} + +/// An object list: flags, then a `lgob` list with the `loda` and an optional transform in a `trfl` +/// list (R22). A version 3 object is a `lobj` whose type counts from 0 (R32) and whose transform is +/// its argument 100 (R33). +pub fn object(v: V, kind: u32, args: &[(u32, Vec)], matrix: Option<[f64; 6]>) -> Node { + if v.0 < 400 { + let kind = if (1..=5).contains(&kind) { kind - 1 } else { kind }; + let mut args = args.to_vec(); + args.extend(matrix.map(|m| (100, transforms3(&[m])))); + return list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), chunk(b"lobj", v.loda(kind, &args))]); + } + let mut own = vec![chunk(b"loda", v.loda(kind, args))]; + if let Some(m) = matrix { + own.push(list(b"trfl", vec![chunk(b"trfd", v.trfd(&[m]))])); + } + list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), list(b"lgob", own)]) +} + +/// A layer list of `kind` flags named `name` holding `objects`, its `loda` in a `lgob` list (R22), +/// with the object type that layers of such flags have in sample files (R19). +pub fn layer(v: V, flags: [u8; 4], name: &str, objects: Vec) -> Node { + let kind = match flags { + [b0, ..] if (b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02) && b0 & 0x10 != 0 => 11, + [b0, ..] if b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02 => 12, + [b0, _, b2, _] if b0 & 0x0f == 0x08 && b2 != 0 => 17, + [0, 1, 1, _] => 17, + _ => 0, + }; + // Version 3 counts its types from 0, one less (R32). + let kind = if v.0 < 400 && kind > 0 { kind - 1 } else { kind }; + layer_of_type(v, flags, kind, name, objects) +} + +/// A layer list as [`layer`] writes it, with the object type `kind` in its `loda`. +pub fn layer_of_type(v: V, flags: [u8; 4], kind: u32, name: &str, objects: Vec) -> Node { + let name: Vec = + if v.0 >= 1200 { name.encode_utf16().chain([0]).flat_map(|u| u.to_le_bytes()).collect() } else { name.bytes().chain([0]).collect() }; + let mut kids = vec![chunk(b"flgs", flags.to_vec()), list(b"lgob", vec![chunk(b"loda", v.loda(kind, &[(1000, name)]))])]; + kids.extend(objects); + list(b"layr", kids) +} + +/// A page list: flags (byte 2 set for the master page), then its layers in a `gobj` list (R22). +pub fn page(master: bool, layers: Vec) -> Node { + list(b"page", vec![chunk(b"flgs", vec![0, 0, u8::from(master), 0x90]), list(b"gobj", layers)]) +} + +/// The `mcfg` chunk of `version` with a page of `w` × `h` points (R10); in version 3, 2 bytes and +/// the page's top left and bottom right corners (R38). +pub fn mcfg(v: V, w: f64, h: f64) -> Node { + if v.0 < 400 { + let mut b = vec![0; 2]; + b.extend([v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + b.extend([0; 16]); + return chunk(b"mcfg", b); + } + let skip = if v.0 >= 1300 { + 12 + } else if v.0 >= 900 { + 4 + } else if (600..700).contains(&v.0) { + 28 + } else { + 0 + }; + let mut b = vec![0; skip]; + b.extend(v.coord(w)); + b.extend(v.coord(h)); + b.extend([0; 16]); + chunk(b"mcfg", b) +} + +/// A style of a [`stlt_body`]: its id, its parent's id, and its fill and outline table entries. +#[derive(Clone, Copy, Debug)] +pub struct Style { + pub id: u32, + pub parent: u32, + pub fill: u32, + pub outline: u32, +} + +/// The body of a `LIST stlt` of `v` (R45): the style count, the fill table (`(entry, fild id)`) and +/// the outline table (`(entry, outl id)`), the text style tables (each with one record when +/// `text`), then `styles` as styles of kind 1, and when `text` a style of kind 2 and one of kind 3. +pub fn stlt_body(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Vec { + let version = v.0; + let u32s = |vals: &[u32]| -> Vec { vals.iter().flat_map(|x| x.to_le_bytes()).collect() }; + let count = styles.len() + if text { 2 } else { 0 }; + let mut b = u32s(&[count as u32]); + // A table without styles holds nothing else. + if count == 0 { + return b; + } + for (table, size) in [(fills, if version >= 1300 { 60 } else { 12 }), (outlines, 12)] { + b.extend(u32s(&[table.len() as u32])); + for (entry, record) in table { + let mut e = u32s(&[*entry, 0, *record]); + e.resize(size, 0); + b.extend(e); + } + } + let n = u32::from(text); + let fixed = |size: usize| -> Vec { + let mut t = n.to_le_bytes().to_vec(); + t.extend(vec![0x5a; size * n as usize]); + t + }; + // Fonts, alignments, spacings and two tables of fixed records. + for size in [if version >= 1000 { 60 } else { 44 }, 12, 52, 152, 784] { + b.extend(fixed(size)); + } + // One bullet, whose u32 inside asks for the longer form. + b.extend(n.to_le_bytes()); + if text { + b.extend([0x5a; 40]); + if version >= 1300 { + if version >= 1400 { + b.extend([0x5a; 4]); + } + b.extend(u32s(&[1])); + b.extend([0x5a; 68]); + } else { + b.extend(vec![0x5a; if version >= 1000 { 28 } else { 20 }]); + b.extend(u32s(&[1])); + b.extend([0x5a; 16]); + } + } + // Indents, hyphenation, drop caps, and from version 8.01 one more table. + for size in [28, if version >= 1300 { 36 } else { 32 }, 28] { + b.extend(fixed(size)); + } + if version >= 801 { + b.extend(fixed(12)); + } + let text_styles = [(2, Style { id: 0x7f02, parent: 0, fill: 0, outline: 0 }), (3, Style { id: 0x7f03, parent: 0x7f02, fill: 0, outline: 0 })]; + let all = styles.iter().map(|s| (1u32, *s)).chain(text_styles.into_iter().filter(|_| text)); + for (kind, s) in all { + b.extend(u32s(&[kind, s.id, s.parent, 1, 1])); + if version >= 1200 { + b.extend(u32s(&[7])); + b.extend("Graphic".encode_utf16().flat_map(u16::to_le_bytes)); + } else { + b.extend(u32s(&[8])); + b.extend(b"Graphic\0"); + } + b.extend(u32s(&[s.fill, s.outline])); + if kind > 1 { + b.extend(vec![0; if version >= 801 { 20 } else { 16 }]); + } + if kind > 2 { + b.extend([0; 20]); + } + } + b +} + +/// A `LIST stlt` of [`stlt_body`]. +pub fn stlt(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Node { + Node::Chunk(*b"LIST", [b"stlt".to_vec(), stlt_body(v, fills, outlines, styles, text)].concat()) +} + +/// A `LIST clpt` of clipped groups (R46): each a `LIST grp ` with its `spnd` id, then its objects. +pub fn clpt(groups: Vec<(u32, Vec)>) -> Node { + let groups = groups + .into_iter() + .map(|(id, objects)| { + let mut kids = vec![chunk(b"spnd", id.to_le_bytes().to_vec())]; + kids.extend(objects); + list(b"grp ", kids) + }) + .collect(); + list(b"clpt", groups) +} + +/// The container argument (8005) naming clipped group `id` (R46), laid out as sample files lay it +/// out. +pub fn container(id: u32) -> (u32, Vec) { + (8005, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect()) +} + +/// The argument 8000 of a uniform transparency from version 13 (R47): one record of version 1300 +/// whose 117-byte body holds `percent` at byte 61 and `merge` at byte 77. +pub fn transparency(percent: f64, merge: u8) -> (u32, Vec) { + let mut body = vec![0; 117]; + body[61..69].copy_from_slice(&percent.to_le_bytes()); + body[77] = merge; + let mut out = 1300u32.to_le_bytes().to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + (8000, out) +} + +/// A property list (R11, R12) of 12-byte color `color` and, when `name` is given, a type 8 +/// property with that library name. +pub fn properties(color: &[u8; 12], name: Option<&str>) -> Vec { + let mut out = vec![1]; + out.extend(12u32.to_le_bytes()); + out.extend(color); + if let Some(name) = name { + let mut body = vec![0; 16]; + body.extend((name.encode_utf16().count() as u32).to_le_bytes()); + body.extend(name.encode_utf16().flat_map(u16::to_le_bytes)); + out.push(8); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + } + out.extend([0, 0, 0, 0, 0]); + out +} + +/// `n` (an object, group or layer list) with its `flgs` chunk replaced by `flags` (R19). +pub fn flagged(n: Node, flags: [u8; 4]) -> Node { + match n { + Node::List(form, kids) => { + let kids = kids + .into_iter() + .map(|k| if matches!(&k, Node::Chunk(id, _) if id == b"flgs") { chunk(b"flgs", flags.to_vec()) } else { k }) + .collect(); + Node::List(form, kids) + } + chunk => chunk, + } +} + +/// A RIFF drawing of `version` (7 to 13) with a style table, a clipping container and a lens: a rectangle +/// that takes its fill and outline from its style, a container that clips two rectangles, one +/// with an outline behind the fill, a rectangle with a lens, a hidden and locked rectangle with a +/// winding flag and a uniform transparency, and a hidden group whose rectangle's outline names a +/// library color from version 13; compressed when `compress`. Before version 7, the [`sample`]. +pub fn feature_sample(version: u16, compress: bool) -> Vec { + if version < 700 { + return sample(version, false); + } + let v = V(version); + let black = color(2, [0, 0, 0, 100]); + let rect = |w: f64, extra: Vec<(u32, Vec)>, at: f64| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + object(v, 1, &args, Some([1.0, 0.0, 0.0, 1.0, at, at])) + }; + let style = (200, 0x10u32.to_le_bytes().to_vec()); + let clipped = + vec![rect(30.0, vec![style.clone()], 10.0), rect(30.0, vec![(10, 3u32.to_le_bytes().to_vec()), (20, 1u32.to_le_bytes().to_vec())], -10.0)]; + // From version 13 outline 4 names a library color in a record of type 2 (R12). + let mut named = v.outline(4, Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &color(25, [7, 0, 100, 0]), &[]); + if version >= 1300 { + let props = properties(&color(5, [0, 0, 255, 0]), Some("Sky Blue")); + let mut record = 2u32.to_le_bytes().to_vec(); + record.extend((props.len() as u32).to_le_bytes()); + record.extend(props); + named.splice(4..4, record); + } + let doc = list( + b"doc ", + vec![ + mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(b"fild", v.fill(1, &color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, Pen { line_type: 4, width: 2.0, cap: 1, join: 1 }, &black, &[3, 1])), + chunk(b"outl", v.outline(3, Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])), + chunk(b"outl", named), + ], + ), + stlt(v, &[(0x100, 1)], &[(0x200, 2)], &[Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }], true), + clpt(vec![(7, clipped)]), + ], + ); + let objects = vec![ + rect(20.0, vec![style.clone()], 0.0), + rect(40.0, vec![style.clone(), container(7)], 50.0), + rect(20.0, vec![style.clone(), (8000, vec![1, 0, 0, 0])], -50.0), + // Hidden and locked, filled nonzero, 25% transparent with merge mode 9 (R19, R47, R52). + flagged(rect(10.0, vec![style.clone(), (14001, vec![1, 0, 0, 0]), transparency(25.0, 9)], 80.0), [0x10, 1, 0, 0x08]), + list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), rect(10.0, vec![(10, 4u32.to_le_bytes().to_vec())], -80.0)]), + ]; + let page = page(false, vec![layer(v, [0, 0, 0, 0x98], "Art", objects)]); + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + if compress { + body.push(cmpr(&[doc, page])); + } else { + body.extend([doc, page]); + } + riff(version, &body) +} + +/// A file of `version` holding `content` as the program of that version saves it: a RIFF file +/// before 14, then a package (R25, R26). +pub fn file_of(version: u16, content: Vec) -> Vec { + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(content); + match version { + ..1400 => riff(version, &body), + 1400..1600 => package14(riff(version, &body), false), + _ => package16(version, &body, false, &[]), + } +} + +/// The document list and pages of the [`sample`] of `version`. +pub fn sample_content(version: u16) -> Vec { + let v = V(version); + // Before version 5 the sample's colors are CMYK in percent, model 1 (R36). + let (red, black) = + if version < 500 { (color4(1, [0, 100, 100, 0]), color4(1, [0, 0, 0, 100])) } else { (color(5, [0, 0, 255, 0]), color(2, [0, 0, 0, 100])) }; + let (round, none) = (Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }); + let mut settings = vec![mcfg(v, 612.0, 792.0)]; + // Version 3 keeps fills and outlines in the objects (R34, R35). + if version >= 400 { + settings.push(list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &red))])); + settings.push(list(b"otlt", vec![chunk(b"outl", v.outline(2, round, &black, &[])), chunk(b"outl", v.outline(3, none, &black, &[]))])); + } + let doc = list(b"doc ", settings); + // Fill 1 is red and 0 none; outline 2 is 2 pt with round caps and joins, 3 none. + let style = |fill: u32, outline: u32| { + if version >= 400 { + return vec![(20, fill.to_le_bytes().to_vec()), (10, outline.to_le_bytes().to_vec())]; + } + let fill = if fill == 1 { fill3(1, &color3(1, [0, 100, 100, 0])) } else { fill3(0, &[]) }; + vec![(20, fill), (10, outline3(if outline == 2 { round } else { none }, color3(1, [0, 0, 0, 100]), &[]))] + }; + let mut rect_args = style(1, 2); + rect_args.push((30, v.rect(100.0, 50.0, 5.0))); + let mut ellipse_args = style(1, 3); + ellipse_args.push((30, [v.coord(40.0), v.coord(-40.0), v.angle(0.0), v.angle(0.0), v.word(0)].concat())); + let mut curve_args = style(0, 2); + curve_args.push((30, v.points(&[(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0xC0), (20.0, 50.0, 0xC0), (0.0, 50.0, 0x88)]))); + let mut arc_args = style(0, 2); + arc_args.push((30, [v.coord(30.0), v.coord(30.0), v.angle(0.0), v.angle(90.0), v.word(1)].concat())); + let side = POLYGON_SIDE; + let mut poly_args = style(1, 2); + poly_args.push((30, v.points(&[(0.0, side, 0x0C), (side * 0.587, side * 0.809, 0x44), (side * 0.951, side * 0.309, 0x44)]))); + let mut poly = if version >= 1300 { vec![] } else { vec![0; 4] }; + poly.extend(5u32.to_le_bytes()); + poly.extend([0; 8]); + if version >= 1300 { + poly.extend([0; 4]); + } + poly.extend(0.05f64.to_le_bytes()); + poly.extend(0.05f64.to_le_bytes()); + poly.extend([v.coord(0.0), v.coord(0.0)].concat()); + poly_args.push((11000, poly)); + let art = layer( + v, + [0, 0, 0, 0x98], + "Art", + vec![ + object(v, 1, &rect_args, Some([1.0, 0.0, 0.0, 1.0, -100.0, 100.0])), + object(v, 2, &ellipse_args, Some([1.0, 0.0, 0.0, 1.0, 50.0, -50.0])), + object(v, 3, &curve_args, None), + list(b"grp ", vec![chunk(b"flgs", vec![0, 0, 0, 0x10]), object(v, 0x14, &poly_args, None), object(v, 2, &arc_args, None)]), + object(v, 4, &[(30, [v.coord(0.0), v.coord(0.0)].concat())], None), + ], + ); + let mut guide = vec![0; 12]; + guide.extend((90_000_000i32).to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0), v.coord(36.0), v.coord(100.0), v.coord(36.0), v.coord(0.0)].concat()); + let guides = layer(v, [0x0a, 0, 1, 0x98], "Guides", vec![object(v, 0x16, &[(16000, guide)], None)]); + let desktop = + layer(v, [0x08, 0, 1, 0x98], "Desktop", vec![object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], Some([1.0, 0.0, 0.0, 1.0, 400.0, 0.0]))]); + let pages = vec![page(true, vec![guides, desktop]), page(false, vec![art])]; + std::iter::once(doc).chain(pages).collect() +} + +/// A drawing of `version` with one page of each kind of object this reader reads, a text object +/// it doesn't, a master page with a guideline and a desktop object; compressed (version 7 on) +/// when `compress`. +pub fn sample(version: u16, compress: bool) -> Vec { + let content = sample_content(version); + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + if compress { + body.push(cmpr(&content)); + } else { + body.extend(content); + } + riff(version, &body) +} + +/// The sample of `version` as the program of that version saves it: a RIFF file before 14, then +/// a package (R25, R26); `compress` compresses the RIFF stream before 16 and deflates the package +/// members. +pub fn sample_file(version: u16, compress: bool) -> Vec { + match version { + ..1400 => sample(version, compress), + 1400..1600 => package14(sample(version, compress), compress), + _ => { + // The full version chunk comes first from 16; the reader doesn't use it. + let fver: Vec = [u32::from(version), 1, 0, u32::from(version / 100)].iter().flat_map(|v| v.to_le_bytes()).collect(); + let mut body = vec![chunk(b"fver", fver), chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(sample_content(version)); + package16(version, &body, compress, &[]) + } + } +} + +/// One member of a synthetic ZIP archive. +#[derive(Clone, Debug)] +pub struct Member { + pub name: String, + pub data: Vec, + pub deflate: bool, +} + +fn deflate(data: &[u8]) -> Vec { + let mut e = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// A ZIP archive of `members`, stored or deflated, with `comment` after the end record (R24). +pub fn zip(members: &[Member], comment: &[u8]) -> Vec { + let (mut out, mut dir) = (Vec::new(), Vec::new()); + for m in members { + let packed = if m.deflate { deflate(&m.data) } else { m.data.clone() }; + let method: u16 = if m.deflate { 8 } else { 0 }; + // Version needed, flags, method, time, date, CRC-32, packed and full sizes, name length. + let mut common = Vec::new(); + common.extend(20u16.to_le_bytes()); + common.extend(0u16.to_le_bytes()); + common.extend(method.to_le_bytes()); + common.extend([0; 4]); + common.extend(crc32fast::hash(&m.data).to_le_bytes()); + common.extend((packed.len() as u32).to_le_bytes()); + common.extend((m.data.len() as u32).to_le_bytes()); + common.extend((m.name.len() as u16).to_le_bytes()); + let at = out.len() as u32; + out.extend(0x0403_4b50u32.to_le_bytes()); + out.extend(&common); + out.extend(0u16.to_le_bytes()); + out.extend(m.name.as_bytes()); + out.extend(&packed); + dir.extend(0x0201_4b50u32.to_le_bytes()); + dir.extend(20u16.to_le_bytes()); + dir.extend(&common); + // Extra and comment lengths, disk, internal and external attributes, header offset. + dir.extend([0; 12]); + dir.extend(at.to_le_bytes()); + dir.extend(m.name.as_bytes()); + } + let dir_at = out.len() as u32; + let n = members.len() as u16; + out.extend(&dir); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend(n.to_le_bytes()); + out.extend(n.to_le_bytes()); + out.extend((dir.len() as u32).to_le_bytes()); + out.extend(dir_at.to_le_bytes()); + out.extend((comment.len() as u16).to_le_bytes()); + out.extend(comment); + out +} + +/// A version 14 or 15 package: the RIFF file `riff` as `content/riffData.cdr` (R25). +pub fn package14(riff: Vec, deflate: bool) -> Vec { + zip(&[Member { name: "content/riffData.cdr".into(), data: riff, deflate }], b"") +} + +/// A version 16+ package of a drawing of `version` holding `children` (R26, R27): the chunk tree +/// in `content/root.dat`, each chunk body of more than 8 bytes moved to a data stream (the +/// document's and other chunks' to `data1.dat`, each page's to `page.dat`, each other list's +/// to a stream named after its form type) behind a redirect record, and shorter bodies kept in +/// theirs. Lists stay in the tree. `extra` members are added to the archive. +pub fn package16(version: u16, children: &[Node], deflate: bool, extra: &[Member]) -> Vec { + package16_with(version, children, deflate, extra, &[]) +} + +/// [`package16`], moving the lists whose form types are in `moved_lists` whole into their stream. +pub fn package16_with(version: u16, children: &[Node], deflate: bool, extra: &[Member], moved_lists: &[[u8; 4]]) -> Vec { + let mut members = package16_members(version, children, deflate, moved_lists); + members.extend(extra.iter().cloned()); + zip(&members, b"") +} + +/// The members of a [`package16_with`] archive. +pub fn package16_members(version: u16, children: &[Node], deflate: bool, moved_lists: &[[u8; 4]]) -> Vec { + let mut streams: Vec<(String, Vec)> = vec![("data1.dat".into(), Vec::new())]; + let mut body = form(version).to_vec(); + for c in children { + let s = match c { + Node::List(f, _) if *f != *b"doc " => { + let name = if *f == *b"page" { format!("page{}", streams.len()) } else { String::from_utf8_lossy(f).trim().to_string() }; + streams.push((format!("{name}.dat"), Vec::new())); + streams.len() - 1 + } + _ => 0, + }; + body.extend(redirected(c, s, &mut streams, moved_lists)); + } + let mut root = b"RIFF".to_vec(); + root.extend((body.len() as u32).to_le_bytes()); + root.extend(body); + let list: Vec = streams.iter().map(|(n, _)| n.clone()).collect(); + let mut members = vec![ + Member { name: "content/root.dat".into(), data: root, deflate }, + Member { name: "content/dataFileList.dat".into(), data: list.join("\n").into_bytes(), deflate }, + ]; + members.extend(streams.into_iter().map(|(n, data)| Member { name: format!("content/data/{n}"), data, deflate })); + members +} + +/// `n` laid out for `root.dat`, its bodies moved into stream `s`. +fn redirected(n: &Node, s: usize, streams: &mut [(String, Vec)], moved_lists: &[[u8; 4]]) -> Vec { + let mut out = Vec::new(); + match n { + Node::List(f, kids) if !moved_lists.contains(f) => { + let mut body = f.to_vec(); + body.extend(kids.iter().flat_map(|k| redirected(k, s, streams, moved_lists))); + put(&mut out, b"LIST", body.len() as u32, &body, body.len()); + } + _ => { + // A moved list's children are laid out in the stream by the same rule. + let (id, data) = match n { + Node::Chunk(id, data) => (*id, data.clone()), + Node::List(f, kids) => { + let mut body = f.to_vec(); + for k in kids { + body.extend(redirected(k, s, streams, moved_lists)); + } + (*b"LIST", body) + } + }; + let mut rec = Vec::new(); + if data.len() <= 8 && id != *b"LIST" { + rec.extend(u32::MAX.to_le_bytes()); + rec.extend((data.len() as u32).to_le_bytes()); + rec.extend(&data); + rec.resize(16, 0); + } else { + let Some((_, stream)) = streams.get_mut(s) else { return out }; + rec.extend((s as u32).to_le_bytes()); + rec.extend((data.len() as u32).to_le_bytes()); + rec.extend((stream.len() as u32).to_le_bytes()); + rec.extend(0u32.to_le_bytes()); + stream.extend(&data); + } + put(&mut out, &id, 16, &rec, 16); + } + } + out +} + +/// The radius the base curve of a polygon lies on, 1000 mm, in points (R18). +pub const POLYGON_SIDE: f64 = 1000.0 / 25.4 * 72.0; + +/// The shape of a drawn object in a file of version 1 or 2 (R43, R44), sizes in points. +#[derive(Clone, Debug)] +pub enum WlShape { + Rect { + w: f64, + h: f64, + radius: f64, + }, + /// The two angle fields are written as given. + Ellipse { + w: f64, + h: f64, + angles: (i16, i16), + }, + /// Points with their type bytes, as [`V::points`] takes them. + Curve(Vec<(f64, f64, u8)>), + Text, +} + +/// A drawn object's record of a version 1 file (R42, R43, R44): `shape` placed by `matrix` +/// `[a, b, c, d, e, f]` with offsets in points, a uniform fill of `fill` and an outline of a width +/// in points and a color. The record's point holds the matrix's x offset and its `ty` the y +/// offset. [`wl_file`] moves the fill and the shape to their places in a version 2 file. +pub fn wl_object(shape: WlShape, matrix: [f64; 6], fill: Option<[u8; 5]>, outline: Option<(f64, [u8; 5])>) -> Vec { + let v = V(300); + let (kind, body): (u8, Vec) = match shape { + WlShape::Rect { w, h, radius } => (0, [v.coord(w), v.coord(h), v.coord(radius), vec![0; 2]].concat()), + WlShape::Ellipse { w, h, angles } => (1, [v.coord(w), v.coord(h), angles.0.to_le_bytes().to_vec(), angles.1.to_le_bytes().to_vec()].concat()), + WlShape::Curve(points) => (2, v.points(&points)), + WlShape::Text => (3, vec![0; 30]), + }; + let mut r = vec![0u8; (114 + body.len()).max(118)]; + r[..4].copy_from_slice(&WL_RECORD_START); + r[26] = 0x40; + r[27] = 0x20; + let size = (r.len() - 32) as u16; + r[28..30].copy_from_slice(&size.to_le_bytes()); + let [a, b, c, d, e, f] = matrix; + r[32..34].copy_from_slice(&v.coord(e)); + let fixed = |x: f64| ((x * 65536.0).round() as i32).to_le_bytes(); + // a, b, tx, c, d, ty: x' = a x + b y + tx, y' = c x + d y + ty. + for (k, x) in [a, c, 0.0, b, d, f / 72.0 * 1000.0].into_iter().enumerate() { + r[36 + 4 * k..40 + 4 * k].copy_from_slice(&fixed(x)); + } + r[60] = kind; + if let Some((width, color)) = outline { + r[67] = 1; + r[68..70].copy_from_slice(&v.coord(width)); + r[74..79].copy_from_slice(&color); + } + if let Some(color) = fill { + r[94] = 1; + r[95..100].copy_from_slice(&color); + } + r[114..114 + body.len()].copy_from_slice(&body); + r +} + +/// The u32 that starts every record of a version 1 or 2 file (R42). +const WL_RECORD_START: [u8; 4] = 24u32.to_le_bytes(); + +/// A group or layer record of a version 1 or 2 file (R42): 28 bytes. +pub fn wl_group() -> Vec { + let mut r = vec![0u8; 28]; + r[..4].copy_from_slice(&WL_RECORD_START); + r[26] = 1; + r[27] = 0x60; + r +} + +/// A drawn object's record of a version 1 file laid out as in a version 2 file (R43): 11 more bytes +/// before the fill and 11 more before the shape. Group records stay as they are. +fn wl_v2_record(rec: &[u8]) -> Vec { + if rec.get(26).is_none_or(|flags| flags & 0x40 == 0) || rec.len() < 114 { + return rec.to_vec(); + } + let mut out = [&rec[..94], &[0; 11], &rec[94..114], &[0; 11], &rec[114..]].concat(); + let size = (out.len() - 32) as u16; + out[28..30].copy_from_slice(&size.to_le_bytes()); + out +} + +/// A file of version 1 or 2 (R40, R41): the header with `marker` (`e` for version 1, `l` or `m` +/// for version 2), a page of `page` points, the `records` and an empty font table. A version 1 +/// file's settings start after the header; a version 2 file's start further on, where a picture +/// lies in the files of that version, and its drawn objects are laid out as [`wl_v2_record`] says. +pub fn wl_file(marker: u8, page: (f64, f64), records: &[Vec]) -> Vec { + let v = V(300); + let settings = if marker == b'e' { 28u32 } else { 40 }; + let start = 64u32; + let mut out = vec![0u8; start as usize]; + out[..4].copy_from_slice(&[b'W', b'L', marker, 0]); + let (w, h) = page; + let page_box = settings as usize + 2; + out[page_box..page_box + 8].copy_from_slice(&[v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + for r in records { + if marker == b'e' { + out.extend(r); + } else { + out.extend(wl_v2_record(r)); + } + } + let end = out.len() as u32; + out.extend([0; 2]); + let trailer = out.len() as u32; + for (k, offset) in [settings, start, end, trailer, trailer - 2].into_iter().enumerate() { + out[4 + 4 * k..8 + 4 * k].copy_from_slice(&offset.to_le_bytes()); + } + out +} + +/// A drawing of version 1 or 2 with a group record and one of each kind of object: a rounded +/// rectangle with a fill and an outline, an ellipse, a closed curve and a text object, front to +/// back. +pub fn wl_sample(marker: u8) -> Vec { + let (red, black) = (color3(1, [0, 100, 100, 0]), color3(1, [0, 0, 0, 100])); + let curve = vec![(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0xC0), (20.0, 50.0, 0xC0), (0.0, 50.0, 0x88)]; + let records = [ + wl_object(WlShape::Rect { w: 100.0, h: 50.0, radius: 5.0 }, [1.0, 0.0, 0.0, 1.0, -100.0, 100.0], Some(red), Some((2.0, black))), + wl_group(), + wl_object(WlShape::Ellipse { w: 40.0, h: -40.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 50.0, -50.0], Some(red), None), + wl_object(WlShape::Curve(curve), [2.0, 0.0, 0.0, 2.0, 0.0, 0.0], None, Some((2.0, black))), + wl_object(WlShape::Text, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(black), None), + ]; + wl_file(marker, (612.0, 792.0), &records) +} diff --git a/crates/cdr/src/synth_cmx.rs b/crates/cdr/src/synth_cmx.rs new file mode 100644 index 0000000000..c70fd8545c --- /dev/null +++ b/crates/cdr/src/synth_cmx.rs @@ -0,0 +1,287 @@ +//! Synthetic `.cmx` files for tests and fuzz seeds, built from the layouts in `PROVENANCE.md` (R53 +//! to R63). Not a `.cmx` writer: nothing checks that other programs open these files. + +/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53). +pub fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + if body.len() % 2 == 1 { + out.push(0); + } + out +} + +/// A `LIST` chunk of form `form`. +pub fn list(form: &[u8; 4], children: &[Vec]) -> Vec { + let mut body = form.to_vec(); + body.extend(children.concat()); + chunk(b"LIST", &body) +} + +/// The RIFF form `CMX1` around `children`. +pub fn riff(children: &[Vec]) -> Vec { + let mut body = b"CMX1".to_vec(); + body.extend(children.concat()); + chunk(b"RIFF", &body) +} + +/// The header (R54): `coord` is the coordinate size digit (`b'4'` or `b'2'`) and `meters` the size +/// of a coordinate unit. The header string and the system name, which the reader doesn't read, +/// are left as zeros. +pub fn cont(coord: u8, meters: f64) -> Vec { + let mut c = vec![0u8; 180]; + c[48] = b'2'; + c[52] = coord; + c[54] = b'2'; + c[64..72].copy_from_slice(&meters.to_le_bytes()); + chunk(b"cont", &c) +} + +/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). +pub fn field(tag: u8, data: &[u8]) -> Vec { + let mut f = vec![tag]; + f.extend(((data.len() + 3) as u16).to_le_bytes()); + f.extend(data); + f +} + +/// A field list: the fields, then 0xff (R55). +pub fn fields(fields: &[Vec]) -> Vec { + let mut l = fields.concat(); + l.push(0xff); + l +} + +/// A table chunk: a u16 count, then the entries (field lists) (R55). +pub fn table(id: &[u8; 4], entries: &[Vec]) -> Vec { + let mut d = (entries.len() as u16).to_le_bytes().to_vec(); + d.extend(entries.concat()); + chunk(id, &d) +} + +/// A color entry in the older form: the model and palette bytes in field 1, the values in field 2 +/// (R56). +pub fn color(model: u8, values: &[u8]) -> Vec { + fields(&[field(1, &[model, 5]), field(2, values)]) +} + +/// A color entry with a property list in field 10 whose color record (part 1) holds `model` and +/// the four value bytes `v` (R56). +pub fn color_record(model: u16, v: [u8; 4]) -> Vec { + color_record_named(model, v, None) +} + +/// A color entry as [`color_record`], with a name part (part 3: a u32 count and UTF-16 units) +/// after the color when `name` is given (R56). +pub fn color_record_named(model: u16, v: [u8; 4], name: Option<&str>) -> Vec { + let mut part = vec![1u8]; + part.extend(12u32.to_le_bytes()); + part.extend(model.to_le_bytes()); + part.extend(5u16.to_le_bytes()); + part.extend([0; 4]); + part.extend(v); + if let Some(name) = name { + let units: Vec = name.encode_utf16().collect(); + part.push(3); + part.extend((4 + 2 * units.len() as u32).to_le_bytes()); + part.extend((units.len() as u32).to_le_bytes()); + part.extend(units.iter().flat_map(|u| u.to_le_bytes())); + } + let mut rec = (part.len() as u32).to_le_bytes().to_vec(); + rec.extend(part); + fields(&[field(10, &rec)]) +} + +/// A pen entry (R57): the width in coordinate units, an aspect of 100 and no angle, with the +/// identity matrix. +pub fn pen(width: u32) -> Vec { + let mut d = width.to_le_bytes().to_vec(); + d.extend(100u16.to_le_bytes()); + d.extend(0i32.to_le_bytes()); + d.extend(1u16.to_le_bytes()); + fields(&[field(1, &d)]) +} + +/// A line type entry (R57): its flags and the caps (low 4 bits) and join (high 4 bits). +pub fn line_type(flags: u8, caps_join: u8) -> Vec { + fields(&[field(1, &[flags, caps_join])]) +} + +/// A dash pattern entry (R57): the lengths in outline widths. +pub fn dashes(lengths: &[u16]) -> Vec { + let mut d = (lengths.len() as u16).to_le_bytes().to_vec(); + d.extend(lengths.iter().flat_map(|l| l.to_le_bytes())); + fields(&[field(1, &d)]) +} + +/// An outline entry (R58): 1-based indexes of the line type, screen, color, arrowhead pair, pen and +/// dash pattern. +pub fn outline(parts: [u16; 6]) -> Vec { + fields(&[field(1, &parts.iter().flat_map(|p| p.to_le_bytes()).collect::>())]) +} + +/// The arrowhead pairs chunk (R59): a u16 count, then start and end (u16 each). +pub fn arrowheads(pairs: &[(u16, u16)]) -> Vec { + let mut d = (pairs.len() as u16).to_le_bytes().to_vec(); + for (s, e) in pairs { + d.extend(s.to_le_bytes()); + d.extend(e.to_le_bytes()); + } + chunk(b"rota", &d) +} + +/// An instruction in the short form: a u16 size counting the whole instruction, the code, the +/// body (R60). +pub fn instr(code: i16, body: &[u8]) -> Vec { + let mut i = ((body.len() + 4) as u16).to_le_bytes().to_vec(); + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// An instruction in the long form: 0xFFFF, a u32 size counting the whole instruction, the code, +/// the body (R60). +pub fn long_instr(code: i16, body: &[u8]) -> Vec { + let mut i = 0xFFFFu16.to_le_bytes().to_vec(); + i.extend(((body.len() + 8) as u32).to_le_bytes()); + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// Begin a page (R61), with its width and height in coordinate units in field 4 when given. +pub fn begin_page(size: Option<(u32, u32)>) -> Vec { + let mut f = vec![field(1, &[1, 0, 0, 0, 0, 0])]; + if let Some((w, h)) = size { + let mut d = w.to_le_bytes().to_vec(); + d.extend(h.to_le_bytes()); + f.push(field(4, &d)); + } + instr(9, &fields(&f)) +} + +/// Begin a page (R61) without a size of its own, with the drawing's left, top, right and bottom +/// edges in field 1. +pub fn begin_page_in_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Vec { + let mut d = vec![1, 0, 0, 0, 0, 0]; + for v in [left, top, right, bottom] { + d.extend(v.to_le_bytes()); + } + instr(9, &fields(&[field(1, &d)])) +} + +/// Begin a layer (R62) named in 8-bit characters in field 1 from byte 12, and in UTF-16 in +/// field 4 when `wide` is given. +pub fn begin_layer(name: &str, wide: Option<&str>) -> Vec { + let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + d.extend((name.len() as u16).to_le_bytes()); + d.extend(name.bytes()); + let mut f = vec![field(1, &d)]; + if let Some(w) = wide { + let units: Vec = w.encode_utf16().collect(); + let mut d = (units.len() as u32).to_le_bytes().to_vec(); + d.extend(units.iter().flat_map(|u| u.to_le_bytes())); + f.push(field(4, &d)); + } + instr(11, &fields(&f)) +} + +pub fn end_layer() -> Vec { + instr(12, &[]) +} + +pub fn end_page() -> Vec { + instr(10, &[]) +} + +pub fn begin_group() -> Vec { + instr(13, &fields(&[field(1, &[0; 26])])) +} + +pub fn end_group() -> Vec { + instr(14, &[]) +} + +/// Rendering attributes (R63): a uniform fill of color `fill` and the outline `outline` (1-based +/// indexes; `None` leaves the part out of the mask), and `lens` sets the lens bit. +pub fn attrs(fill: Option, outline: Option, lens: bool) -> Vec { + let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1) | (u8::from(lens) << 2); + let mut a = vec![mask]; + if let Some(c) = fill { + let mut v = 1u16.to_le_bytes().to_vec(); + let mut uniform = c.to_le_bytes().to_vec(); + uniform.extend(0u16.to_le_bytes()); + v.extend(fields(&[field(1, &uniform)])); + a.extend(fields(&[field(1, &v)])); + } + if let Some(o) = outline { + a.extend(fields(&[field(1, &o.to_le_bytes())])); + } + a +} + +/// Rendering attributes with a fill of type `kind` and no settings of its own. +pub fn attrs_fill_type(kind: u16) -> Vec { + let mut a = vec![1u8]; + a.extend(fields(&[field(1, &kind.to_le_bytes())])); + a +} + +/// A curve (R62): `attrs`, then a u16 count, the points (i32 x, y) and their type bytes. +pub fn curve(attrs: &[u8], points: &[(i32, i32)], types: &[u8]) -> Vec { + let mut g = (points.len() as u16).to_le_bytes().to_vec(); + for (x, y) in points { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend(types); + instr(67, &fields(&[field(1, attrs), field(2, &g), field(3, &[0; 16])])) +} + +/// A closed square of side `side` with its lower left corner at (`x`, `y`). +pub fn square(attrs: &[u8], x: i32, y: i32, side: i32) -> Vec { + curve(attrs, &[(x, y), (x + side, y), (x + side, y + side), (x, y + side), (x, y)], &[0x0c, 0x44, 0x44, 0x44, 0x48]) +} + +/// A `page` chunk of `instructions`. +pub fn page(instructions: &[Vec]) -> Vec { + chunk(b"page", &instructions.concat()) +} + +/// The tables of [`sample`]: colors red (RGB), black (CMYK in percent) and blue (a color record, +/// blue, green, red); pens of 0.5 mm and 1 mm; line types solid with round caps and joins, none, +/// and dashed behind the fill; one dash pattern; three outlines; one empty arrowhead pair. +pub fn tables() -> Vec> { + vec![ + table(b"rclr", &[color(5, &[255, 0, 0]), color(2, &[0, 0, 0, 100]), color_record(5, [255, 0, 0, 0])]), + table(b"rpen", &[pen(5_000), pen(10_000)]), + table(b"rott", &[line_type(2, 0x11), line_type(1, 0), line_type(2 | 4 | 8, 0x02)]), + table(b"rdot", &[dashes(&[3, 1])]), + table(b"rotl", &[outline([1, 1, 2, 1, 1, 1]), outline([2, 1, 2, 1, 1, 1]), outline([3, 1, 3, 1, 2, 1])]), + arrowheads(&[(0, 0)]), + ] +} + +/// One page of 210 x 297 mm with two layers: "Art" holds a red square outlined in black, then a +/// group of a square with no outline and a blue one with the dashed outline; "Top" holds a black +/// square drawn last. Units are 0.1 µm. +pub fn sample() -> Vec { + let p = page(&[ + begin_page(Some((2_100_000, 2_970_000))), + begin_layer("Art", None), + square(&attrs(Some(1), Some(1), false), -500_000, -500_000, 1_000_000), + begin_group(), + square(&attrs(Some(2), Some(2), false), 0, 0, 100_000), + square(&attrs(Some(3), Some(3), false), 200_000, 0, 100_000), + end_group(), + end_layer(), + begin_layer("Top", Some("Top")), + square(&attrs(Some(2), None, false), 0, 0, 10_000), + end_layer(), + end_page(), + ]); + let mut children = vec![cont(b'4', 1e-7), p]; + children.extend(tables()); + riff(&children) +} diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs new file mode 100644 index 0000000000..bae22ba5a0 --- /dev/null +++ b/crates/cdr/src/wl.rs @@ -0,0 +1,358 @@ +//! Drawings of versions 1 and 2: the file before RIFF, which starts with `WL` (R40 to R44). A +//! header of offsets, the settings with the page's box, then one flat list of records: 28 bytes +//! for a group or a layer, and a longer record for each drawn object, which holds its matrix, fill, +//! outline and shape. The reader maps the rectangles, ellipses and curves onto one page with one +//! layer and keeps no groups. + +use crate::bytes::{Rd, u32_at}; +use crate::geometry; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Cap, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape}; +use crate::records::{self, coord, fixed}; +use crate::riff::push; +use crate::{Error, Warning}; + +/// The header: the signature, a marker byte, a zero and five u32 offsets (R40). +const HEADER: usize = 28; +/// The marker bytes read after `WL` (R40): `e` for version 1, `l` and `m` for version 2. +const MARKERS: [u8; 3] = *b"elm"; +/// Where the page's box lies after the start of the settings (R41). +const PAGE_BOX: usize = 2; +/// The bytes of a group or layer record (R42). +const GROUP: usize = 28; +/// The u32 that starts every record (R42). +const RECORD_START: u32 = 24; +/// The flag bit, in byte 26, of a drawn object (R42). +const DRAWN: u8 = 0x40; +/// The bytes after a drawn object's body size (R42). +const AFTER_BODY: usize = 32; +/// Where a drawn object's fields lie (R43, R44). +const POINT: usize = 32; +const KIND: usize = 60; +const OUTLINED: usize = 67; +const OUTLINE_WIDTH: usize = 68; +const OUTLINE_COLOR: usize = 74; + +/// Where a drawn object's fill and shape lie, which differs between the markers (R43, R44). +#[derive(Clone, Copy)] +struct Fields { + fill_kind: usize, + shape: usize, +} + +impl Fields { + fn of(marker: u8) -> Self { + if marker == b'e' { Fields { fill_kind: 94, shape: 114 } } else { Fields { fill_kind: 105, shape: 136 } } + } + + /// The least a drawn object takes: its fixed fields and the 4 bytes of a shape's size. + fn least(self) -> usize { + self.shape + 4 + } +} +/// Object types (R43). +const RECTANGLE: u8 = 0; +const ELLIPSE: u8 = 1; +const CURVE: u8 = 2; +const TEXT: u8 = 3; + +/// Where the settings start, and where the records start and end, when `b` has a `WL` header +/// whose offsets fit the file. +fn header(b: &[u8]) -> Option<(usize, usize, usize)> { + if b.get(..2)? != b"WL" || !MARKERS.contains(b.get(2)?) || *b.get(3)? != 0 { + return None; + } + let (settings, start, end) = (u32_at(b, 4)? as usize, u32_at(b, 8)? as usize, u32_at(b, 12)? as usize); + (settings >= HEADER && settings <= start && start <= end && end <= b.len()).then_some((settings, start, end)) +} + +/// Does `b` start like a drawing of version 1 or 2? The two letters alone are not enough: the +/// marker byte, the zero after it and the record offsets must fit too. +pub(crate) fn is_wl(b: &[u8]) -> bool { + header(b).is_some() +} + +pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result { + let (settings, start, end) = header(b).ok_or(Error::NotCdr)?; + let marker = b.get(2).copied().ok_or(Error::NotCdr)?; + let fields = Fields::of(marker); + // Lengths are i16 in 1/1000 inch, as in version 3 (R5). + let p = layout::for_version(layout::OLDEST_RIFF).ok_or(Error::NotCdr)?; + let mut warn = Vec::new(); + let mut objects = Vec::new(); + let mut at = start; + // Every step takes at least a group record's bytes, so the file's size bounds the steps. + while end - at >= GROUP { + budget.take_chunk()?; + // A record that doesn't start as records do is past one whose length isn't known. + if u32_at(b, at) != Some(RECORD_START) { + break; + } + if b.get(at + 26).is_none_or(|flags| flags & DRAWN == 0) { + at += GROUP; + continue; + } + // A drawn object of another type than rectangle, ellipse, curve and text doesn't say its + // length in the same way, so the records after it can't be found. + if b.get(at + KIND).is_none_or(|kind| *kind > TEXT) { + push(&mut warn, Warning::UnsupportedObjects); + at = end; + break; + } + let len = Rd::at(b, at + 28).u16().map_or(0, |body| usize::from(body) + AFTER_BODY); + let Some(rec) = b.get(at..at + len).filter(|_| len >= fields.least() && at + len <= end) else { + push(&mut warn, Warning::Damaged); + at = end; + break; + }; + at += len; + if !budget.take_object() { + push(&mut warn, Warning::TooDeep); + at = end; + break; + } + objects.extend(object(rec, fields, &p, budget, &mut warn)); + } + if at != end { + push(&mut warn, Warning::Damaged); + } + let version = if marker == b'e' { 100 } else { 200 }; + let layer = Layer { name: String::new(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() }; + let pages = vec![Page { size: None, layers: vec![layer] }]; + Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) +} + +/// The page's size from its box (R41): left, top, right and bottom around the page's centre. +fn page_box(b: &[u8], settings: usize, p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, settings + PAGE_BOX); + let (left, top, right, bottom) = (coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?); + let (w, h) = ((right - left).abs(), (top - bottom).abs()); + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object +/// of another type and for a shape that can't be read. +fn object(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + // A curve left out at the coordinate limit is not damage. + budget.coordinates_refused(); + let read = shape(rec, fields, p, budget, warn); + if read.is_none() && !budget.coordinates_refused() { + push(warn, Warning::Damaged); + } + read?.map(|s| Object::Shape(Box::new(s))) +} + +/// The shape of a record. The outer `None` is a record that can't be read; the inner one an object +/// the reader leaves out, with its warning. +fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option> { + let k = p.unit(); + let mut r = Rd::at(rec, POINT); + let (x, y) = (f64::from(r.i16()?), f64::from(r.i16()?)); + // x' = a x + b y + tx + x of the point, y' = c x + d y + ty + y of the point. + let (a, b, tx, c, d, ty) = (fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?); + let matrix = Matrix([a, c, b, d, (tx + x) * k, (ty + y) * k]); + let body = rec.get(fields.shape..)?; + let geometry = match *rec.get(KIND)? { + RECTANGLE => rect(body, p)?, + ELLIPSE => { + let mut s = Rd::new(body); + let (w, h) = (coord(&mut s, p)?, coord(&mut s, p)?); + // Two angles follow. No source confirms how they make an arc, so an ellipse whose + // angles differ is left out; one whose angles are missing is damage. + let (from, to) = (s.i16()?, s.i16()?); + if from != to { + push(warn, Warning::UnsupportedObjects); + return Some(None); + } + Geometry::Ellipse { w, h } + } + CURVE => Geometry::Path(geometry::point_list(body, p, budget, warn)?), + _ => { + push(warn, Warning::UnsupportedObjects); + return Some(None); + } + }; + let color_at = |at: usize, warn: &mut Vec| Some(records::color5(rec.get(at..at + 5)?.try_into().ok()?, warn)); + let fill = match *rec.get(fields.fill_kind)? { + 0 => None, + 1 => Some(color_at(fields.fill_kind + 1, warn)?), + _ => { + push(warn, Warning::UnsupportedFills); + None + } + }; + let outline = if *rec.get(OUTLINED)? != 0 { + let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k; + Some(Outline { + width, + color: color_at(OUTLINE_COLOR, warn)?, + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }) + } else { + None + }; + Some(Some(Shape::new(geometry, matrix, fill, outline))) +} + +/// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most +/// half the shorter side. +fn rect(body: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(body); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let radius = coord(&mut r, p).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0); + Some(Geometry::Rect { w, h, radii: [radius; 4] }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::model::Color; + use crate::synth::{self, WlShape}; + + fn read(b: &[u8]) -> Result { + drawing(b, &mut Budget::new(Limits::default())) + } + + #[test] + fn the_header_is_taken_only_when_its_offsets_fit() { + let file = synth::wl_file(b'e', (612.0, 792.0), &[synth::wl_group()]); + assert!(is_wl(&file)); + // The two letters, a marker and a zero are not enough. + assert!(!is_wl(b"WLe\0")); + assert!(!is_wl(b"WLe\0 and then some text that is long enough to hold offsets")); + let with = |at: usize, v: u32| { + let mut f = file.clone(); + f[at..at + 4].copy_from_slice(&v.to_le_bytes()); + f + }; + // Records that start inside the header, start after their end, or end past the file. + assert!(!is_wl(&with(8, 27))); + assert!(!is_wl(&with(8, file.len() as u32))); + assert!(!is_wl(&with(12, file.len() as u32 + 1))); + // Settings that start inside the header or after the records. + assert!(!is_wl(&with(4, 27))); + assert!(!is_wl(&with(4, 65))); + let mut other = file.clone(); + other[2] = b'x'; + assert!(!is_wl(&other)); + // No sample shows the marker `d`, so it is not taken. + other[2] = b'd'; + assert!(!is_wl(&other)); + for marker in *b"lm" { + assert!(is_wl(&synth::wl_file(marker, (612.0, 792.0), &[synth::wl_group()]))); + } + other[2] = b'e'; + other[3] = 1; + assert!(!is_wl(&other)); + } + + #[test] + fn a_version_2_file_keeps_its_page_box_fill_and_shape_where_that_version_puts_them() { + let (red, black) = ([1, 0, 100, 100, 0], [1, 0, 0, 0, 100]); + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 9.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(red), Some((2.0, black))); + for marker in *b"elm" { + let file = synth::wl_file(marker, (720.0, 504.0), std::slice::from_ref(&rect)); + // Version 2 files start their settings after a picture, not after the header. + assert_eq!(u32_at(&file, 4) == Some(28), marker == b'e'); + let d = read(&file).unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 0.02; + assert_eq!((d.version, d.warnings.clone()), (if marker == b'e' { 100 } else { 200 }, vec![])); + assert!(d.page_size.is_some_and(|(w, h)| near(w, 720.0) && near(h, 504.0)), "{:?}", d.page_size); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert!( + matches!(s.geometry, Geometry::Rect { w, h, radii } if near(w, 72.0) && near(h, 36.0) && near(radii[0], 9.0)), + "{}", + marker as char + ); + assert_eq!(s.fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0])), "{}", marker as char); + assert!(s.outline.as_ref().is_some_and(|o| near(o.width, 2.0) && o.color == Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{}", marker as char); + } + } + + #[test] + fn a_drawn_object_is_marked_by_its_flag_bit() { + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], None, None); + let mut file = synth::wl_file(b'l', (612.0, 792.0), &[rect]); + // Files with the marker `l` set another flag bit beside it. + file[64 + 26] = 0xc0; + let d = read(&file).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![])); + } + + #[test] + fn the_walk_stops_where_records_can_no_longer_be_found() { + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let rect = || synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, unit, None, None); + // An object of another type doesn't give its length in the same way. + let mut other = rect(); + other[KIND] = 0xff; + let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[rect(), other, rect()])).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::UnsupportedObjects])); + // A record that doesn't start as records do. + let mut lost = rect(); + lost[0] = 0x84; + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), lost, rect()])).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::Damaged])); + } + + #[test] + fn a_rectangle_keeps_a_radius_of_at_most_half_its_shorter_side() { + let p = layout::for_version(300).unwrap(); + let body = |radius: i16| [1000i16, 500, radius].iter().flat_map(|v| v.to_le_bytes()).collect::>(); + let radius_of = |b: &[u8]| match rect(b, &p) { + Some(Geometry::Rect { w, h, radii }) if (w - 72.0).abs() < 1e-9 && (h - 36.0).abs() < 1e-9 => radii[0], + other => panic!("{other:?}"), + }; + assert!((radius_of(&body(200)) - 14.4).abs() < 1e-9); + for radius in [300, -5, 0] { + assert_eq!(radius_of(&body(radius)), 0.0, "{radius}"); + } + // A record that ends after the size has square corners. + assert_eq!(radius_of(&body(200)[..4]), 0.0); + assert_eq!(rect(&body(200)[..3], &p), None); + } + + #[test] + fn a_record_shorter_than_its_fields_ends_the_walk_as_damage() { + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); + let mut short = rect.clone(); + // A body size that leaves less than the fixed fields. + short[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY - 1) as u16).to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect.clone(), short, rect])).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + + #[test] + fn an_ellipse_without_its_angles_is_damage() { + let ellipse = + synth::wl_object(WlShape::Ellipse { w: 72.0, h: 36.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); + let mut cut = ellipse.clone(); + // A body size that ends the record after the ellipse's width and height. + cut[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY) as u16).to_le_bytes()); + cut.truncate(Fields::of(b'e').least()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[ellipse, cut])).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + + #[test] + fn fill_types_other_than_uniform_and_unknown_inks_are_named() { + let mut textured = + synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([0, 9, 0, 50, 0]), None); + let d = read(&synth::wl_file(b'm', (612.0, 792.0), std::slice::from_ref(&textured))).unwrap(); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert_eq!(s.fill, Some(Color::Spot { name: "Spot 0:9".into(), tint: 0.5, look: None })); + assert_eq!((d.version, d.warnings), (200, vec![Warning::SpotLooks])); + textured[Fields::of(b'e').fill_kind] = 5; + let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[textured])).unwrap(); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert_eq!((s.fill.clone(), d.warnings), (None, vec![Warning::UnsupportedFills])); + } +} diff --git a/crates/cdr/src/zip.rs b/crates/cdr/src/zip.rs new file mode 100644 index 0000000000..67994192a0 --- /dev/null +++ b/crates/cdr/src/zip.rs @@ -0,0 +1,308 @@ +//! The ZIP archives of `.cdr` drawings from version 14 on (R24): the central directory, then stored +//! and deflated members read on request. Archives that span disks, ZIP64 archives and encrypted +//! members are refused; so are directories whose members overlap or repeat a name. + +use std::borrow::Cow; +use std::io::Read as _; + +use crate::Error; +use crate::bytes::Rd; + +/// End of central directory record: signature and fixed length. +const END: u32 = 0x0605_4b50; +const END_LEN: usize = 22; +/// The longest archive comment, which the end record may be followed by. +const MAX_COMMENT: usize = 0xFFFF; +/// ZIP64 end of central directory locator, 20 bytes before the end record when present. +const ZIP64_LOCATOR: u32 = 0x0706_4b50; +/// Central directory header: signature and fixed length. +const CENTRAL: u32 = 0x0201_4b50; +const CENTRAL_LEN: usize = 46; +/// Local file header: signature and fixed length. +const LOCAL: u32 = 0x0403_4b50; +const LOCAL_LEN: usize = 30; +/// General purpose flag bit 0: the member is encrypted. +const ENCRYPTED: u16 = 1; +const STORED: u16 = 0; +const DEFLATED: u16 = 8; +/// What members packed by another method are refused as. +const OTHER_METHODS: &str = "package compression methods other than storing and deflate"; + +/// One member, as the central directory and its local header give it. +#[derive(Clone, Copy, Debug)] +struct Entry<'a> { + name: &'a [u8], + flags: u16, + method: u16, + crc: u32, + packed: usize, + size: usize, + /// Where its local header starts and where its packed bytes start. + header: usize, + data: usize, +} + +/// An archive's directory over its bytes. +#[derive(Debug)] +pub(crate) struct Archive<'a> { + bytes: &'a [u8], + entries: Vec>, + /// The entries in name order, for lookups. + by_name: Vec, +} + +/// Does `bytes` start with a local file header? +pub(crate) fn is_zip(bytes: &[u8]) -> bool { + bytes.starts_with(b"PK\x03\x04") +} + +impl<'a> Archive<'a> { + /// The directory of `bytes`, holding at most `max_entries` members. + pub(crate) fn open(bytes: &'a [u8], max_entries: usize) -> Result { + let end = find_end(bytes).ok_or(Error::Damaged("package directory"))?; + if end >= 20 && Rd::at(bytes, end - 20).u32() == Some(ZIP64_LOCATOR) { + return Err(Error::Unsupported("ZIP64 packages")); + } + let mut r = Rd::at(bytes, end + 4); + let dir = || Error::Damaged("package directory"); + let (disk, dir_disk) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?); + let (on_disk, total) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?); + let (dir_len, dir_at) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?); + if total == u16::MAX || dir_len == u32::MAX || dir_at == u32::MAX { + return Err(Error::Unsupported("ZIP64 packages")); + } + if disk != 0 || dir_disk != 0 || on_disk != total { + return Err(Error::Unsupported("packages split across files")); + } + let total = usize::from(total); + if total > max_entries { + return Err(Error::Limit("package member count")); + } + let (dir_at, dir_len) = (dir_at as usize, dir_len as usize); + let dir_end = dir_at.checked_add(dir_len).filter(|&e| e <= end).ok_or_else(dir)?; + let mut r = Rd::at(bytes, dir_at); + let mut entries = Vec::with_capacity(total); + for _ in 0..total { + let e = central_entry(bytes, &mut r, dir_end)?; + entries.push(e); + } + // Each member's bytes end before the next member's header and before the directory. + let mut order: Vec<&Entry> = entries.iter().collect(); + order.sort_unstable_by_key(|e| e.header); + for (i, e) in order.iter().enumerate() { + let stop = order.get(i + 1).map_or(dir_at, |n| n.header); + if e.data.checked_add(e.packed).is_none_or(|x| x > stop) { + return Err(Error::Damaged("package members overlap")); + } + } + let mut by_name: Vec = (0..entries.len()).collect(); + by_name.sort_unstable_by_key(|&i| entries.get(i).map(|e| e.name)); + let name = |i: &usize| entries.get(*i).map(|e| e.name); + if by_name.windows(2).any(|w| name(&w[0]) == name(&w[1])) { + return Err(Error::Damaged("package member named twice")); + } + Ok(Archive { bytes, entries, by_name }) + } + + /// The member named `name`. + pub(crate) fn find(&self, name: &[u8]) -> Option { + let at = self.by_name.binary_search_by(|&i| self.entries.get(i).map(|e| e.name).cmp(&Some(name))).ok()?; + self.by_name.get(at).copied() + } + + /// The size member `i`'s directory entry gives. + pub(crate) fn size(&self, i: usize) -> usize { + self.entries.get(i).map_or(0, |e| e.size) + } + + /// How many members the archive holds. + pub(crate) fn count(&self) -> usize { + self.entries.len() + } + + /// The bytes reading member `i` may inflate: its stated size when it is deflated, else 0. + pub(crate) fn inflate_cost(&self, i: usize) -> usize { + self.entries.get(i).filter(|e| e.method == DEFLATED).map_or(0, |e| e.size) + } + + /// An error when member `i` is encrypted or packed by a method other than storing or deflate. + pub(crate) fn check(&self, i: usize) -> Result<(), Error> { + let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?; + if e.flags & ENCRYPTED != 0 { + return Err(Error::Unsupported("encrypted packages")); + } + if e.method != STORED && e.method != DEFLATED { + return Err(Error::Unsupported(OTHER_METHODS)); + } + Ok(()) + } + + /// Member `i`'s bytes when they come to at most `limit`, and a deflated member's when they + /// also come to at most `inflate_left`. A stored member is borrowed; a deflated one inflates to + /// at most its stated size plus one byte, so a member that inflates past what it states stops + /// there. The length and CRC-32 must match the directory's. + pub(crate) fn read(&self, i: usize, limit: usize, inflate_left: usize) -> Result, Error> { + self.check(i)?; + let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?; + if e.size > limit { + return Err(Error::Limit("package member size")); + } + if e.method == DEFLATED && e.size > inflate_left { + return Err(Error::Limit("inflated size")); + } + let packed = self.bytes.get(e.data..e.data + e.packed).ok_or(Error::Damaged("package member"))?; + let out: Cow<'a, [u8]> = match e.method { + STORED if e.packed == e.size => Cow::Borrowed(packed), + STORED => return Err(Error::Damaged("package member")), + DEFLATED => { + let mut out = Vec::new(); + let got = flate2::read::DeflateDecoder::new(packed) + .take(e.size as u64 + 1) + .read_to_end(&mut out) + .map_err(|_| Error::Damaged("package member"))?; + if got != e.size { + return Err(Error::Damaged("package member")); + } + Cow::Owned(out) + } + _ => return Err(Error::Unsupported(OTHER_METHODS)), + }; + if crc32fast::hash(&out) != e.crc { + return Err(Error::Damaged("package member")); + } + Ok(out) + } +} + +/// Where the end of central directory record starts: searched back from the end over at most the +/// longest comment, among the records whose comment reaches exactly to the end the first that +/// names members in a directory before it, else the first. A comment or a member may hold bytes +/// that look like an empty archive's end record. +fn find_end(bytes: &[u8]) -> Option { + let last = bytes.len().checked_sub(END_LEN)?; + let first = last.saturating_sub(MAX_COMMENT); + let mut found = None; + for at in (first..=last).rev() { + let mut r = Rd::at(bytes, at); + if r.u32() != Some(END) || r.skip(6).is_none() { + continue; + } + let (total, dir_len, dir_at, comment) = (r.u16(), r.u32(), r.u32(), r.u16()); + if !comment.is_some_and(|c| at + END_LEN + usize::from(c) == bytes.len()) { + continue; + } + let names_members = total.is_some_and(|t| t > 0) + && dir_len.zip(dir_at).is_some_and(|(len, dir)| { + (dir as usize).checked_add(len as usize).is_some_and(|e| e <= at) && Rd::at(bytes, dir as usize).u32() == Some(CENTRAL) + }); + if names_members { + return Some(at); + } + found = found.or(Some(at)); + } + found +} + +/// The central directory entry at `r` (before `dir_end`) and its local header. +fn central_entry<'a>(bytes: &'a [u8], r: &mut Rd<'a>, dir_end: usize) -> Result, Error> { + let dir = || Error::Damaged("package directory"); + if r.pos().checked_add(CENTRAL_LEN).is_none_or(|e| e > dir_end) || r.u32() != Some(CENTRAL) { + return Err(dir()); + } + r.skip(4).ok_or_else(dir)?; + let flags = r.u16().ok_or_else(dir)?; + let method = r.u16().ok_or_else(dir)?; + r.skip(4).ok_or_else(dir)?; + let crc = r.u32().ok_or_else(dir)?; + let (packed, size) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?); + let name_len = usize::from(r.u16().ok_or_else(dir)?); + let extra_len = usize::from(r.u16().ok_or_else(dir)?); + let comment_len = usize::from(r.u16().ok_or_else(dir)?); + let disk = r.u16().ok_or_else(dir)?; + r.skip(6).ok_or_else(dir)?; + let header = r.u32().ok_or_else(dir)?; + if packed == u32::MAX || size == u32::MAX || header == u32::MAX { + return Err(Error::Unsupported("ZIP64 packages")); + } + if disk != 0 { + return Err(Error::Unsupported("packages split across files")); + } + let name = r.bytes(name_len).ok_or_else(dir)?; + r.skip(extra_len).and_then(|()| r.skip(comment_len)).ok_or_else(dir)?; + if r.pos() > dir_end { + return Err(dir()); + } + // The local header repeats the name; its own extra field may differ in length. + let header = header as usize; + let mut l = Rd::at(bytes, header); + let local = || Error::Damaged("package member header"); + if l.u32() != Some(LOCAL) { + return Err(local()); + } + // The signature, 22 bytes, then the name and extra field lengths. + l.skip(LOCAL_LEN - 8).ok_or_else(local)?; + let (local_name, local_extra) = (usize::from(l.u16().ok_or_else(local)?), usize::from(l.u16().ok_or_else(local)?)); + if l.bytes(local_name) != Some(name) { + return Err(local()); + } + l.skip(local_extra).ok_or_else(local)?; + Ok(Entry { name, flags, method, crc, packed: packed as usize, size: size as usize, header, data: l.pos() }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::synth::{Member, zip}; + + fn stored(name: &str, data: &[u8]) -> Member { + Member { name: name.into(), data: data.to_vec(), deflate: false } + } + + #[test] + fn stored_and_deflated_members_read_back() { + let bytes = zip(&[stored("a", b"hello"), Member { name: "b".into(), data: vec![7; 5000], deflate: true }], b""); + let a = Archive::open(&bytes, 10).unwrap(); + assert!(matches!(a.read(a.find(b"a").unwrap(), 100, 100).unwrap(), Cow::Borrowed(b"hello"))); + assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 5000).unwrap().as_ref(), &[7; 5000][..]); + assert_eq!(a.read(a.find(b"b").unwrap(), 4999, 5000), Err(Error::Limit("package member size"))); + assert_eq!(a.find(b"c"), None); + // What is left to inflate holds back deflated members only. + assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 4999), Err(Error::Limit("inflated size"))); + assert!(a.read(a.find(b"a").unwrap(), 100, 0).is_ok()); + } + + #[test] + fn the_end_record_is_found_behind_a_comment() { + let bytes = zip(&[stored("a", b"x")], &[b'c'; 300]); + assert!(Archive::open(&bytes, 10).is_ok()); + // A comment longer than the record says leaves no end record to find. + let mut cut = bytes.clone(); + cut.push(0); + assert_eq!(Archive::open(&cut, 10).unwrap_err(), Error::Damaged("package directory")); + // A comment that ends in bytes like an empty archive's end record: the record that names + // members in a directory is the archive's. + let mut fake = END.to_le_bytes().to_vec(); + fake.resize(END_LEN, 0); + let bytes = zip(&[stored("a", b"x")], &fake); + let a = Archive::open(&bytes, 10).unwrap(); + assert_eq!(a.count(), 1); + } + + #[test] + fn a_member_whose_crc_or_length_is_wrong_is_damage() { + let bytes = zip(&[Member { name: "a".into(), data: vec![1; 64], deflate: true }], b""); + let a = Archive::open(&bytes, 10).unwrap(); + // The directory's CRC-32 sits 16 bytes into its entry. + let dir_at = bytes.windows(4).position(|w| w == CENTRAL.to_le_bytes()).unwrap(); + let mut bad = bytes.clone(); + bad[dir_at + 16] ^= 1; + let b = Archive::open(&bad, 10).unwrap(); + assert_eq!(b.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member")); + // A stated size one short: the inflate runs past it. + let mut short = bytes.clone(); + short[dir_at + 24] -= 1; + let s = Archive::open(&short, 10).unwrap(); + assert_eq!(s.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member")); + assert!(a.read(0, 1000, 1000).is_ok()); + } +} diff --git a/crates/cdr/tests/it/bench.rs b/crates/cdr/tests/it/bench.rs new file mode 100644 index 0000000000..6b60a0a5a7 --- /dev/null +++ b/crates/cdr/tests/it/bench.rs @@ -0,0 +1,65 @@ +//! Read time of a large synthetic drawing. Run with +//! `cargo test --release -p craft-cdr --test it bench -- --ignored --nocapture`. + +use craft_cdr::synth::{self, V, chunk, list}; +use craft_cdr::{Limits, read}; + +/// A version 13 drawing of `n` curves of 22 points each, filled and outlined, compressed when +/// `compress`. +fn many_curves(n: usize, compress: bool) -> Vec { + let v = V(1300); + let red = synth::color(5, [0, 0, 255, 0]); + let black = synth::color(2, [0, 0, 0, 100]); + let styles = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]), + list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &black, &[]))]), + ], + ); + let objects: Vec<_> = (0..n) + .map(|i| { + let o = (i % 500) as f64; + // A move, then curves of two control points and an end point each. + let kind = |k: i32| { + if k == 0 { + 0x08 + } else if k % 3 == 0 { + 0x80 + } else { + 0xC0 + } + }; + let pts: Vec<(f64, f64, u8)> = (0..22).map(|k| (o + f64::from(k), o + f64::from(k % 5), kind(k))).collect(); + let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, 2u32.to_le_bytes().to_vec()), (30, v.points(&pts))]; + synth::object(v, 3, &args, Some([1.0, 0.0, 0.0, 1.0, o, -o])) + }) + .collect(); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", objects)]); + let body = vec![styles, page]; + let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())]; + if compress { + kids.push(synth::cmpr(&body)); + } else { + kids.extend(body); + } + synth::riff(1300, &kids) +} + +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn read_a_large_drawing() { + for compress in [false, true] { + let file = many_curves(50_000, compress); + let mut times = Vec::new(); + for _ in 0..5 { + let t = std::time::Instant::now(); + let d = read(&file, Limits::default()).unwrap(); + times.push(t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(d.pages.len(), 1); + } + times.sort_by(f64::total_cmp); + println!("compress={compress} bytes={} median_ms={:.1} min_ms={:.1}", file.len(), times[2], times[0]); + } +} diff --git a/crates/cdr/tests/it/cmx.rs b/crates/cdr/tests/it/cmx.rs new file mode 100644 index 0000000000..0067d981b7 --- /dev/null +++ b/crates/cdr/tests/it/cmx.rs @@ -0,0 +1,568 @@ +//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and +//! hostile ones. + +use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape}; +use craft_cdr::synth_cmx::*; +use craft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; +use proptest::prelude::*; + +fn shape(o: &Object) -> &Shape { + match o { + Object::Shape(s) => s, + other => panic!("not a shape: {other:?}"), + } +} + +/// The (x, y) bounds of a shape's path. +fn bounds(s: &Shape) -> (f64, f64, f64, f64) { + let Geometry::Path(p) = &s.geometry else { panic!("not a path") }; + let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for sp in &p.subpaths { + for pt in std::iter::once(sp.start).chain(sp.segments.iter().map(|s| match s { + craft_cdr::model::Segment::Line(p) | craft_cdr::model::Segment::Cubic(_, _, p) => *p, + })) { + b = (b.0.min(pt.x), b.1.min(pt.y), b.2.max(pt.x), b.3.max(pt.y)); + } + } + b +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// The file with `children` after a 32-bit header and the sample tables. +fn file(pages: &[Vec]) -> Vec { + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(pages.iter().cloned()); + children.extend(tables()); + riff(&children) +} + +#[test] +fn a_cmx_file_is_told_from_a_cdr_drawing() { + let f = sample(); + assert!(is_cmx(&f) && !is_cdr(&f)); + let mut rifx = f.clone(); + rifx[..4].copy_from_slice(b"RIFX"); + assert!(is_cmx(&rifx)); + assert!(!is_cmx(b"RIFF\0\0\0\0CDR9")); + assert_eq!(read_cmx(b"RIFF\0\0\0\0CDR9", Limits::default()), Err(Error::NotCmx)); +} + +#[test] +fn pages_layers_groups_and_curves() { + let d = read_cmx(&sample(), Limits::default()).unwrap(); + assert_eq!(d.version, 0); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + let page = &d.pages[0]; + // 2,100,000 units of 0.1 µm are 210 mm. + let (w, h) = page.size.unwrap(); + assert!(near(w, 210.0 / 25.4 * 72.0) && near(h, 297.0 / 25.4 * 72.0), "{w} {h}"); + // The layer drawn last is in front: the model lists layers front to back. + let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Top", "Art"]); + let art = &page.layers[1].objects; + assert_eq!(art.len(), 2); + // The group, drawn after the red square, is in front of it. + let Object::Group { objects: kids, .. } = &art[0] else { panic!("{:?}", art[0]) }; + assert_eq!(kids.len(), 2); + let red = shape(&art[1]); + assert_eq!(red.fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + // 1,000,000 units are 100 mm; the square's corner is 50 mm left of and below the center. + let mm = 72.0 / 25.4; + let b = bounds(red); + assert!(near(b.0, -50.0 * mm) && near(b.1, -50.0 * mm) && near(b.2, 50.0 * mm) && near(b.3, 50.0 * mm), "{b:?}"); + let Geometry::Path(p) = &red.geometry else { panic!() }; + assert!(p.subpaths.len() == 1 && p.subpaths[0].closed && p.subpaths[0].segments.len() == 4); + let o = red.outline.as_ref().unwrap(); + assert!(near(o.width, 0.5 * mm)); + assert_eq!((o.color.clone(), o.cap, o.join), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Round, Join::Round)); + assert!(o.dashes.is_empty() && !o.behind_fill && !o.scale_with); + // Line type 1 draws no outline. + let blue = shape(&kids[0]); + let black = shape(&kids[1]); + assert!(black.outline.is_none()); + assert_eq!(black.fill, Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0]))); + // The color record's values are blue, green and red. + assert_eq!(blue.fill, Some(Color::Rgb([0.0, 0.0, 1.0]))); + let o = blue.outline.as_ref().unwrap(); + assert!(near(o.width, 1.0 * mm)); + assert_eq!((o.dashes.clone(), o.behind_fill, o.cap, o.join), (vec![3.0, 1.0], true, Cap::Square, Join::Miter)); + assert_eq!(page.layers[0].name, "Top"); +} + +#[test] +fn layer_names_and_layers_without_objects() { + let p = page(&[ + begin_page(None), + begin_layer("Ebene 1", Some("Слой 1")), + square(&attrs(Some(1), None, false), 0, 0, 1000), + end_layer(), + begin_layer("Gitter", None), + end_layer(), + begin_layer("Caf\u{e9}", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + end_layer(), + end_page(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let page = &d.pages[0]; + assert_eq!(page.size, None); + // The empty layer is left out, and the UTF-16 name wins over the 8-bit one. + let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Caf\u{c3}\u{a9}", "Слой 1"]); +} + +#[test] +fn objects_before_any_layer_get_one() { + let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.pages[0].layers.len(), 1); + // The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place. + assert_eq!(d.pages[0].layers[0].name, ""); +} + +#[test] +fn a_page_without_a_size_takes_the_drawings_bounds() { + // A square of 100 mm whose bounds lie off the file's origin, above and to the right. + let p = page(&[ + begin_page_in_bounds(1_000_000, 3_000_000, 2_000_000, 2_000_000), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 1_000_000, 2_000_000, 1_000_000), + end_layer(), + end_page(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let page = &d.pages[0]; + let side = 100.0 / 25.4 * 72.0; + let (w, h) = page.size.unwrap(); + assert!(near(w, side) && near(h, side), "{w} x {h}"); + // The page is centered on the bounds, so the square fills it. + let (x0, y0, x1, y1) = bounds(shape(&page.layers[0].objects[0])); + assert!(near(x0, -side / 2.0) && near(x1, side / 2.0) && near(y0, -side / 2.0) && near(y1, side / 2.0), "{x0} {y0} {x1} {y1}"); +} + +#[test] +fn curves_and_open_groups() { + let c = + curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]); + // A group the layer leaves open closes with it. + let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let objects = &d.pages[0].layers[0].objects; + let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") }; + let s = shape(&kids[0]); + assert!(s.fill.is_none()); + let Geometry::Path(p) = &s.geometry else { panic!() }; + assert_eq!(p.subpaths.len(), 2); + assert!(matches!(p.subpaths[0].segments[..], [craft_cdr::model::Segment::Cubic(..)])); + assert!(!p.subpaths[1].closed); +} + +#[test] +fn a_curve_without_its_points_is_reported() { + let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() { + let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]; + d.extend(b"Art"); + let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])])); + let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.pages[0].layers[0].name, "Art"); +} + +#[test] +fn what_is_not_read_is_reported() { + let other = |code: i16| instr(code, &fields(&[field(1, &[0; 8])])); + let p = page(&[ + begin_page(None), + begin_layer("L", None), + other(66), + other(68), + other(20), + other(88), + square(&attrs_fill_type(2), 0, 0, 1000), + square(&attrs(Some(1), None, true), 0, 0, 1000), + end_layer(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] { + assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings); + } + // A fill of another type leaves the curve unfilled; the curve is still read. + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 2); + assert!(shape(&objects[1]).fill.is_none()); +} + +#[test] +fn colors_of_other_models_and_missing_entries() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + square(&attrs(Some(9), None, false), 0, 0, 1000), + square(&attrs(Some(2), None, false), 0, 0, 1000), + ])); + children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0]))); + assert_eq!(shape(&objects[1]).fill, Some(Color::Rgb([0.0; 3]))); +} + +#[test] +fn gray_cmy_and_rgb_colors_of_the_older_fields() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + square(&attrs(Some(2), None, false), 0, 0, 1000), + square(&attrs(Some(3), None, false), 0, 0, 1000), + ])); + children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + // The model holds objects front to back: the RGB square, the CMY one, then the gray one. + assert_eq!(shape(&objects[0]).fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + match (shape(&objects[1]).fill.clone(), shape(&objects[2]).fill.clone()) { + (Some(Color::Cmyk([c, m, y, k])), Some(Color::Gray(g))) => { + assert!((c - 1.0).abs() < 1e-6 && m == 0.0 && (y - 0.2).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}"); + assert!((g - 0.8).abs() < 1e-6, "{g}"); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn outline_arrowheads_are_reported() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); + children.push(arrowheads(&[(0, 2)])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::Arrowheads]); +} + +#[test] +fn a_long_instruction_and_a_jump_over_image_bytes() { + // The jump's target counts from the start of the file: header, `cont`, then the page body. + let before = riff(&[cont(b'4', 1e-7), page(&[])]).len() - 8; + let head = [begin_page(None), begin_layer("L", None)].concat(); + let jump_len = 4 + 1 + 3 + 4; + let image = vec![0xEEu8; 37]; + let target = (before + 8 + head.len() + jump_len + image.len()) as u32; + let jump = instr(111, &fields(&[field(1, &target.to_le_bytes())])); + assert_eq!(jump.len(), jump_len); + let body = [ + head, + jump, + image, + long_instr(67, &curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48])[4..]), + end_layer(), + ] + .concat(); + let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + // The images jumped over are not read, and the warning says so. + assert_eq!(d.warnings, [Warning::UnsupportedObjects]); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn bytes_after_a_chunk_that_runs_short_are_passed_over() { + let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff]; + let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn other_byte_orders_and_coordinate_sizes_are_refused() { + let mut f = sample(); + f[..4].copy_from_slice(b"RIFX"); + assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); + let mut children = vec![cont(b'2', 1e-3)]; + children.extend(tables()); + assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); + assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); +} + +#[test] +fn a_header_without_a_usable_unit_reads_0_1_micrometers() { + for meters in [0.0, -1.0, f64::NAN, 2.0] { + let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let (w, _) = d.pages[0].size.unwrap(); + assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}"); + } +} + +#[test] +fn groups_past_the_depth_limit_are_left_out() { + let mut ins = vec![begin_page(None), begin_layer("L", None)]; + for _ in 0..6 { + ins.push(begin_group()); + } + ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); + for _ in 0..6 { + ins.push(end_group()); + } + ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); + let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep)); + // The square after the groups is still read, beside the three groups kept. + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 2); + let mut depth = 0; + let mut o = &objects[1]; + while let Object::Group { objects: kids, .. } = o { + depth += 1; + match kids.first() { + Some(k) => o = k, + None => break, + } + } + assert_eq!(depth, 3); +} + +#[test] +fn counts_past_the_limits_are_bounded() { + let ins: Vec> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect(); + let f = file(&[page(&ins)]); + let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 10); + assert!(d.warnings.contains(&Warning::TooDeep)); + let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 2); + assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); + let dashed = |n: u16| { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)])); + children.extend(tables()); + read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() + }; + let d = dashed(3); + let o: Vec = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect(); + assert_eq!(o, [0, 2]); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn a_curve_cut_short_keeps_the_points_it_holds() { + let mut c = curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48]); + // Claim 9 points where 3 are stored: the field's own length still covers only 3. + let at = c.windows(2).position(|w| w == [3, 0]).unwrap(); + c[at] = 9; + let p = page(&[begin_page(None), c]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_curve_that_lost_type_bytes_keeps_its_first_points() { + // Three whole points and only two of their type bytes. + let mut g = 3u16.to_le_bytes().to_vec(); + for (x, y) in [(0i32, 0i32), (1_000_000, 0), (1_000_000, 1_000_000)] { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend([0x0c, 0x44]); + let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)])); + let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() }; + let side = 100.0 / 25.4 * 72.0; + assert!(near(p.subpaths[0].start.x, 0.0) && near(p.subpaths[0].start.y, 0.0)); + match p.subpaths[0].segments[..] { + [craft_cdr::model::Segment::Line(e)] => assert!(near(e.x, side) && near(e.y, 0.0), "{e:?}"), + ref other => panic!("{other:?}"), + } +} + +#[test] +fn a_file_cut_short_of_its_declared_size_is_reported() { + let mut f = file(&[]); + let declared = (f.len() as u32 - 8 + 100).to_le_bytes(); + f[4..8].copy_from_slice(&declared); + let d = read_cmx(&f, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn a_page_that_ends_inside_an_instruction_is_reported() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_chunk_64_bytes_past_stray_bytes_is_found() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn stray_letters_with_a_length_past_the_file_are_passed_over() { + let mut stray = b"abcd".to_vec(); + stray.extend(0xFFFF_FF00u32.to_le_bytes()); + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl"))); + children.push(table(b"rdot", &[dashes(&[0, 0])])); + children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap(); + assert!(o.dashes.is_empty(), "{:?}", o.dashes); +} + +#[test] +fn a_curve_field_that_lost_points_is_left_out() { + // Three points claimed, two whole points stored and the third cut inside its y: the type + // bytes can't be found, so no node types are read from coordinates. + let mut g = 3u16.to_le_bytes().to_vec(); + for (x, y) in [(0i32, 0i32), (1_000_000, 0)] { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend(1_000_000i32.to_le_bytes()); + g.extend([0x40, 0x42]); + let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)])); + let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); +} + +#[test] +fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() { + // Stray bytes, a chunk the reader passes over whose id ends in a digit, then the page. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 6]; + b.extend(chunk(b"inf1", &[0; 70])); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() { + // After stray bytes, four spaces with a small length, or letters with a length past the list, + // come before the page: neither is taken for a chunk, so the page is found. + for filler in [b" \x08\x00\x00\x00".to_vec(), b"junk\x40\x42\x0f\x00".to_vec()] { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(filler); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + } +} + +#[test] +fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() { + // Stray bytes, then a chunk the reader passes over whose body starts with the letters of a + // page chunk, then the page: only the page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut inner = b"page".to_vec(); + inner.extend(4u32.to_le_bytes()); + inner.extend([0; 10]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_canvas_or_a_container_is_reported() { + for bit in [8u8, 16] { + let mut a = attrs(Some(1), None, false); + a[0] |= bit; + let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}"); + assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some()); + } +} + +#[test] +fn a_library_color_with_its_name_reads_as_a_spot_color() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); + children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + match shape(&d.pages[0].layers[0].objects[0]).fill.clone() { + Some(Color::Spot { name, tint, look }) => { + assert_eq!((name.as_str(), tint), ("Brick 12", 1.0)); + assert!(look.is_some()); + } + other => panic!("{other:?}"), + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { + let mut b = b"RIFF\0\0\0\0CMX1".to_vec(); + b.extend(bytes); + let _ = read_cmx(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_samples(edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = sample(); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read_cmx(&b, Limits::default()); + } +} diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs new file mode 100644 index 0000000000..4fc7dcbdc9 --- /dev/null +++ b/crates/cdr/tests/it/main.rs @@ -0,0 +1,8 @@ +//! Integration tests: one test binary for the crate, one module per area. +// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod bench; +mod cmx; +mod provenance; +mod read; diff --git a/crates/cdr/tests/it/provenance.rs b/crates/cdr/tests/it/provenance.rs new file mode 100644 index 0000000000..fffc006cb4 --- /dev/null +++ b/crates/cdr/tests/it/provenance.rs @@ -0,0 +1,43 @@ +//! Every layout id the code cites (`R1` ...) has a row in `PROVENANCE.md`. + +use std::collections::BTreeSet; + +/// The ids `R` in `text`. +fn ids(text: &str) -> BTreeSet { + let b = text.as_bytes(); + let mut out = BTreeSet::new(); + for (i, c) in b.iter().enumerate() { + let starts = *c == b'R' && (i == 0 || !b[i - 1].is_ascii_alphanumeric()); + if !starts { + continue; + } + let digits: String = b[i + 1..].iter().take_while(|d| d.is_ascii_digit()).map(|d| *d as char).collect(); + let ends = b.get(i + 1 + digits.len()).is_none_or(|d| !d.is_ascii_alphanumeric()); + if !digits.is_empty() && ends { + out.insert(digits.parse().unwrap()); + } + } + out +} + +#[test] +fn every_cited_layout_has_a_row() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let table = std::fs::read_to_string(dir.join("PROVENANCE.md")).unwrap(); + let rows: BTreeSet = table.lines().filter_map(|l| l.strip_prefix("| R")).filter_map(|l| l.split(' ').next()?.parse().ok()).collect(); + let mut cited = BTreeSet::new(); + for entry in std::fs::read_dir(dir.join("src")).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|e| e == "rs") { + cited.extend(ids(&std::fs::read_to_string(&path).unwrap())); + } + } + assert!(!cited.is_empty()); + let missing: Vec<_> = cited.difference(&rows).collect(); + assert!(missing.is_empty(), "cited without a PROVENANCE.md row: {missing:?}"); +} + +#[test] +fn ids_are_found_only_as_whole_words() { + assert_eq!(ids("(R1, R12) RIFF R3x xR4 R"), BTreeSet::from([1, 12])); +} diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs new file mode 100644 index 0000000000..6ea8672635 --- /dev/null +++ b/crates/cdr/tests/it/read.rs @@ -0,0 +1,2288 @@ +//! Reading synthetic drawings of every version the reader takes, plain and compressed, and +//! hostile files. + +use craft_cdr::model::{Blend, Cap, Color, Flags, Geometry, Join, LayerKind, Matrix, Object, Segment}; +use craft_cdr::synth::{self, V, chunk, list}; +use craft_cdr::{Error, Limits, Warning, preview, read}; +use proptest::prelude::*; + +fn shapes(objects: &[Object]) -> Vec<&craft_cdr::model::Shape> { + let mut out = Vec::new(); + let mut stack: Vec<&Object> = objects.iter().rev().collect(); + while let Some(o) = stack.pop() { + match o { + Object::Shape(s) => out.push(&**s), + Object::Group { objects: kids, .. } => stack.extend(kids.iter().rev()), + Object::Clip { container, objects } => { + out.push(&**container); + stack.extend(objects.iter().rev()); + } + } + } + out +} + +/// The page and layers of the sample of `version`. +fn check_pages(d: &craft_cdr::Drawing, version: u16) { + assert_eq!(d.version, version); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{version}: {w} {h}"); + assert_eq!(d.pages.len(), 1, "{version}"); + let art = &d.pages[0].layers[0]; + assert_eq!((art.name.as_str(), art.kind), ("Art", LayerKind::Drawing)); + assert!(matches!(art.objects[3], Object::Group { objects: ref g, .. } if g.len() == 2)); + assert!(d.warnings.contains(&Warning::UnsupportedObjects)); + // The master page: its guideline every page shows, and its desktop object. + if version >= 600 { + assert_eq!(d.guides.len(), 1); + assert!((d.guides[0].angle - 90.0).abs() < 1e-9 && (d.guides[0].at.x - 36.0).abs() < 0.01); + } + assert_eq!(d.master.len(), 1); + assert_eq!(d.master[0].kind, LayerKind::Desktop); +} + +/// The shapes of the sample of `version`: rectangle, ellipse, curve, and the group's polygon and +/// arc; the text is left out. +fn check_shapes(d: &craft_cdr::Drawing, version: u16) { + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 5, "{version}"); + assert!(matches!(s[0].geometry, Geometry::Rect { radii, .. } if radii.iter().all(|r| (r - 5.0).abs() < 0.1))); + // The samples of versions 3 and 4 store their red as CMYK in percent. + let red = if version < 500 { Color::Cmyk([0.0, 1.0, 1.0, 0.0]) } else { Color::Rgb([1.0, 0.0, 0.0]) }; + assert_eq!(s[0].fill, Some(red), "{version}"); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 2.0).abs() < 0.05 && o.cap == Cap::Round, "{version}: {o:?}"); + assert!((s[0].matrix.0[4] + 100.0).abs() < 0.1 && (s[0].matrix.0[5] - 100.0).abs() < 0.1); + assert!(matches!(s[1].geometry, Geometry::Ellipse { .. }) && s[1].outline.is_none()); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths[0].closed && matches!(p.subpaths[0].segments[1], Segment::Cubic(..)))); + assert!(s[2].fill.is_none()); + if version >= 600 { + let Geometry::Path(p) = &s[3].geometry else { panic!("polygon") }; + assert_eq!(p.subpaths[0].segments.len(), 10, "five sides of two segments"); + // 5 % of 1000 mm. + let r = p.subpaths[0].start.y; + assert!((r - 0.05 * synth::POLYGON_SIDE).abs() < 0.5, "{r}"); + } + assert!(matches!(&s[4].geometry, Geometry::Path(p) if p.subpaths[0].closed)); +} + +#[test] +fn every_version_from_5_to_13_reads_its_sample() { + for version in [500, 600, 700, 800, 900, 1000, 1100, 1200, 1300] { + for compress in [false, version >= 700] { + let d = read(&synth::sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version} {compress}: {e}")); + check_pages(&d, version); + check_shapes(&d, version); + } + } +} + +#[test] +fn versions_3_and_4_read_their_sample() { + for version in [300, 400] { + let file = synth::sample(version, false); + assert_eq!(&file[8..12], if version == 300 { b"CDR " } else { b"CDR4" }); + assert!(craft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(!d.warnings.contains(&Warning::Damaged), "{version}: {:?}", d.warnings); + check_pages(&d, version); + check_shapes(&d, version); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!((o.join, &o.color), (Join::Round, &Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{version}"); + // The ellipse 50 pt right of and below the page centre, and the curve where it was drawn. + assert!((s[1].matrix.0[4] - 50.0).abs() < 0.1 && (s[1].matrix.0[5] + 50.0).abs() < 0.1, "{version}: {:?}", s[1].matrix); + assert_eq!(s[2].matrix, Matrix::IDENTITY, "{version}"); + } + // The form type alone names version 3, and a `vrsn` chunk names it under another form type. + let mut plain = vec![]; + plain.extend(synth::sample_content(300)); + check_shapes(&read(&synth::riff(300, &plain), Limits::default()).unwrap(), 300); + let mut relabeled = synth::sample(300, false); + relabeled[11] = b'5'; + assert_eq!(read(&relabeled, Limits::default()).unwrap().version, 300); +} + +/// A version 3 drawing of one layer holding `objects`. +fn drawing3(objects: Vec) -> Vec { + let page = synth::page(false, vec![synth::layer(V(300), [0, 0, 0, 0x98], "L", objects)]); + synth::riff(300, &[chunk(b"vrsn", 300u16.to_le_bytes().to_vec()), page]) +} + +/// A version 3 rectangle of 10 × 10 pt with the transforms `matrices`. +fn rect3(matrices: &[[f64; 6]]) -> synth::Node { + let v = V(300); + let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))]; + if !matrices.is_empty() { + args.push((100, synth::transforms3(matrices))); + } + synth::object(v, 1, &args, None) +} + +#[test] +fn version_3_groups_place_their_objects() { + let shift = |x: f64, y: f64| [1.0, 0.0, 0.0, 1.0, x, y]; + let double = [2.0, 0.0, 0.0, 2.0, 0.0, 0.0]; + // A rectangle moved 72 pt right, in a group that doubles sizes, in a group that moves 36 pt + // up; beside the inner group, a rectangle of the outer group alone; then one outside both. + let inner = synth::group3(&[double], vec![rect3(&[shift(72.0, 0.0)])]); + let outer = synth::group3(&[shift(0.0, 36.0)], vec![inner, rect3(&[])]); + let d = read(&drawing3(vec![outer, rect3(&[shift(7.2, 0.0)])]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + assert!( + matches!(&objects[0], Object::Group { objects: g, .. } if matches!(&g[0], Object::Group { objects: i, .. } if i.len() == 1) && g.len() == 2) + ); + let s = shapes(objects); + let close = |m: &Matrix, want: [f64; 6]| m.0.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01); + // Its own shift, then the inner group's scale, then the outer group's shift. + assert!(close(&s[0].matrix, [2.0, 0.0, 0.0, 2.0, 144.0, 36.0]), "{:?}", s[0].matrix); + assert!(close(&s[1].matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 36.0]), "{:?}", s[1].matrix); + assert!(close(&s[2].matrix, [1.0, 0.0, 0.0, 1.0, 7.2, 0.0]), "{:?}", s[2].matrix); + // Two matrices of one object apply in file order. + let d = read(&drawing3(vec![rect3(&[shift(72.0, 0.0), double])]), Limits::default()).unwrap(); + assert!(close(&shapes(&d.pages[0].layers[0].objects)[0].matrix, [2.0, 0.0, 0.0, 2.0, 144.0, 0.0])); +} + +#[test] +fn version_3_objects_and_groups_under_an_envelope_keep_their_outlines_and_matrices() { + // A transforms argument of one envelope entry (type 0x14). + let mut envelope = vec![0, 0, 1, 0, 0x14, 0]; + envelope.resize(14 + 24, 0); + // A matrix that moves 72 pt right, then an envelope entry whose data follows the matrix's. + let matrix = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0]]).split_off(14); + let mut shifted = vec![0, 0, 2, 0, 0x8c, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0x14, 0, 0, 0, 0, 0, 48, 0, 0, 0]; + shifted.extend(matrix); + shifted.resize(48 + 24, 0); + let v = V(300); + let bent = synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, envelope.clone())], None); + let moved = synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, shifted)], None); + let group = list(b"grp ", vec![chunk(b"lobj", v.loda(0, &[(100, envelope)])), rect3(&[])]); + let d = read(&drawing3(vec![bent, moved, group, rect3(&[])]), Limits::default()).unwrap(); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 4); + assert!(matches!(&objects[2], Object::Group { objects: g, .. } if g.len() == 1)); + let s = shapes(objects); + assert_eq!(s.len(), 4); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && s[0].matrix == Matrix::IDENTITY); + assert!((s[1].matrix.0[4] - 72.0).abs() < 0.01 && s[1].matrix.0[5].abs() < 0.01, "{:?}", s[1].matrix); + assert_eq!(s[2].matrix, Matrix::IDENTITY); + assert_eq!(d.warnings, vec![Warning::Envelopes]); +} + +#[test] +fn version_3_object_types_count_from_0() { + let v = V(300); + // `lobj` records written with their stored types: 0 rectangle, 2 curve, 3 text, 4 bitmap. + let raw = |kind: u32, coords: Vec| list(b"obj ", vec![chunk(b"lobj", v.loda(kind, &[(30, coords)]))]); + let curve = v.points(&[(0.0, 0.0, 0x00), (10.0, 0.0, 0x40)]); + let ellipse = [v.coord(40.0), v.coord(20.0), v.angle(0.0), v.angle(0.0), v.word(0)].concat(); + let d = read( + &drawing3(vec![raw(0, v.rect(10.0, 10.0, 0.0)), raw(1, ellipse), raw(2, curve), raw(3, vec![0; 8]), raw(4, vec![0; 8])]), + Limits::default(), + ) + .unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && matches!(s[1].geometry, Geometry::Ellipse { .. })); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths.len() == 1)); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); +} + +#[test] +fn version_3_fills_and_outlines_read_from_the_object() { + let v = V(300); + let styled = |fill: Vec, outline: Vec| synth::object(v, 1, &[(20, fill), (10, outline), (30, v.rect(10.0, 10.0, 0.0))], None); + let pen = |line_type: u16| synth::Pen { line_type, width: 3.0, cap: 2, join: 2 }; + let black = synth::color3(1, [0, 0, 0, 100]); + let d = read( + &drawing3(vec![ + styled(synth::fill3(1, &synth::color3(0, [0, 0, 40, 0])), synth::outline3(pen(0), black, &[3, 1])), + styled(synth::fill3(1, &synth::color3(0, [1, 0, 100, 0])), synth::outline3(pen(1), black, &[])), + styled(synth::fill3(0, &[]), synth::outline3(pen(0), synth::color3(0, [200, 0, 80, 0]), &[])), + ]), + Limits::default(), + ) + .unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + // Ink 0 is black at its tint, ink 1 white, and another number a library ink. + assert_eq!((s[0].fill.clone(), s[1].fill.clone(), s[2].fill.clone()), (Some(Color::Gray(0.4)), Some(Color::Gray(0.0)), None)); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 3.0).abs() < 0.05, "{}", o.width); + assert_eq!((o.cap, o.join, &o.dashes), (Cap::Square, Join::Bevel, &vec![3.0, 1.0])); + assert!(s[1].outline.is_none()); + assert_eq!(s[2].outline.as_ref().unwrap().color, Color::Spot { name: "Spot 0:200".into(), tint: 0.8, look: None }); + assert_eq!(d.warnings, vec![Warning::SpotLooks]); + // Fountain, texture and pattern fills are named and leave the shape unfilled; a fill or an + // outline cut short is damage. + for kind in [2, 4, 6, 7, 10] { + let d = read(&drawing3(vec![styled(synth::fill3(kind, &[0; 12]), synth::outline3(pen(1), black, &[]))]), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedFills], "{kind}"); + assert!(shapes(&d.pages[0].layers[0].objects)[0].fill.is_none()); + } + let d = read(&drawing3(vec![styled(vec![1, 1], vec![1, 0])]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +#[test] +fn version_3_dashes_count_toward_the_dash_limit() { + let v = V(300); + let pen = synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }; + let dashed = + || synth::object(v, 1, &[(10, synth::outline3(pen, synth::color3(1, [0, 0, 0, 100]), &[2, 2, 2])), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = read(&drawing3(vec![dashed(), dashed()]), Limits { dashes: 4, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!((s[0].outline.as_ref().unwrap().dashes.len(), s[1].outline.as_ref().unwrap().dashes.len()), (3, 0)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +#[test] +fn hostile_version_3_transforms_are_damage() { + let v = V(300); + let with = |arg: Vec| synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, arg)], None); + // A matrix whose data offset lies past the argument, and an argument cut inside its header. + let mut past = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 5.0, 5.0]]); + past[10..12].copy_from_slice(&60000u16.to_le_bytes()); + for arg in [past, vec![0, 0, 9]] { + let d = read(&drawing3(vec![with(arg)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].matrix, Matrix::IDENTITY); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + // A count of 65,535 over one entry reads that entry. + let mut many = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0]]); + many[2..4].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&drawing3(vec![with(many)]), Limits::default()).unwrap(); + assert!((shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4] - 72.0).abs() < 0.01); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +#[test] +fn version_4_transforms_are_fixed_point_and_compose_in_file_order() { + let v = V(400); + let own = vec![ + chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), + list(b"trfl", vec![chunk(b"trfd", v.trfd(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0], [0.0, 2.0, -2.0, 0.0, 0.0, 0.0]]))]), + ]; + let object = list(b"obj ", vec![list(b"lgob", own)]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])]); + let d = read(&synth::riff(400, &[chunk(b"vrsn", 400u16.to_le_bytes().to_vec()), page]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Moved 72 pt right, then turned a quarter and doubled: (0, 0) lands at (0, 144). + let m = shapes(&d.pages[0].layers[0].objects)[0].matrix; + assert!(m.0.iter().zip([0.0, 2.0, -2.0, 0.0, 0.0, 144.0]).all(|(a, b)| (a - b).abs() < 0.01), "{m:?}"); +} + +#[test] +fn version_4_colors_are_words() { + let v = V(400); + let file = |fill: [u8; 12]| { + let doc = list(b"doc ", vec![list(b"filt", vec![chunk(b"fill", v.fill(1, &fill))])]); + let rect = synth::object(v, 1, &[(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect])]); + synth::riff(400, &[chunk(b"vrsn", 400u16.to_le_bytes().to_vec()), doc, page]) + }; + let fill_of = |fill: [u8; 12]| { + let d = read(&file(fill), Limits::default()).unwrap(); + (shapes(&d.pages[0].layers[0].objects)[0].fill.clone(), d.warnings) + }; + assert_eq!(fill_of(synth::color4(1, [20, 40, 60, 80])), (Some(Color::Cmyk([0.2, 0.4, 0.6, 0.8])), vec![])); + assert_eq!(fill_of(synth::color4(0, [0, 30, 0, 0])), (Some(Color::Gray(0.3)), vec![])); + assert_eq!(fill_of(synth::color4(0, [1, 30, 0, 0])), (Some(Color::Gray(0.0)), vec![])); + assert_eq!( + fill_of(synth::color4(0, [513, 30, 0, 0])), + (Some(Color::Spot { name: "Spot 0:513".into(), tint: 0.3, look: None }), vec![Warning::SpotLooks]) + ); + // The version 5 record read in the version 4 layout would take these values from other bytes. + assert_ne!(fill_of(synth::color(2, [20, 40, 60, 80])).0, Some(Color::Cmyk([0.2, 0.4, 0.6, 0.8]))); +} + +#[test] +fn the_version_3_page_size_is_the_distance_between_its_corners() { + let v = V(300); + for corners in [[-306.0, 396.0, 306.0, -396.0], [306.0, -396.0, -306.0, 396.0]] { + let mut b = vec![0xff; 2]; + b.extend(corners.iter().flat_map(|c| v.coord(*c))); + let d = read(&synth::riff(300, &[list(b"doc ", vec![chunk(b"mcfg", b)])]), Limits::default()).unwrap(); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{w} {h}"); + } + // Corners that give no width, and a chunk cut inside them, give no page size. + let mut flat = vec![0; 2]; + flat.extend([v.coord(10.0), v.coord(5.0), v.coord(10.0), v.coord(-5.0)].concat()); + for b in [flat.clone(), flat[..9].to_vec()] { + assert_eq!(read(&synth::riff(300, &[list(b"doc ", vec![chunk(b"mcfg", b)])]), Limits::default()).unwrap().page_size, None); + } +} + +#[test] +fn a_point_list_before_version_6_counts_its_points_with_a_u16() { + for version in [300, 400, 500] { + let v = V(version); + let mut points = v.points(&[(0.0, 0.0, 0x00), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]); + // The u16 after the count is 1 in some curves; as part of a u32 count it would run the + // count past the points. + points[2] = 1; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &[(30, points)], None)])]); + let d = read(&synth::riff(version, &[chunk(b"vrsn", version.to_le_bytes().to_vec()), page]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(matches!(&s[0].geometry, Geometry::Path(p) if p.subpaths[0].segments.len() == 2), "{version}"); + } +} + +/// The objects of the one layer of a version 1 or 2 drawing. +fn wl_objects(d: &craft_cdr::Drawing) -> &[Object] { + assert_eq!((d.pages.len(), d.pages[0].layers.len(), d.master.len(), d.guides.len()), (1, 1, 0, 0)); + &d.pages[0].layers[0].objects +} + +#[test] +fn versions_1_and_2_read_their_sample() { + for (marker, version) in [(b'e', 100), (b'l', 200), (b'm', 200)] { + let file = synth::wl_sample(marker); + assert!(file.starts_with(b"WL") && craft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.version, version); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{w} {h}"); + // The text is left out, and the group record holds nothing. + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); + let s = shapes(wl_objects(&d)); + assert_eq!(s.len(), 3); + // Front to back: the rounded rectangle, the ellipse, the curve. + assert!( + matches!(s[0].geometry, Geometry::Rect { w, h, radii } if (w - 100.0).abs() < 0.1 && (h - 50.0).abs() < 0.1 && radii.iter().all(|r| (r - 5.0).abs() < 0.1)) + ); + assert_eq!(s[0].fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0]))); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 2.0).abs() < 0.05, "{}", o.width); + assert_eq!((&o.color, o.cap, o.join, o.dashes.len()), (&Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Butt, Join::Miter, 0)); + assert!((s[0].matrix.0[4] + 100.0).abs() < 0.1 && (s[0].matrix.0[5] - 100.0).abs() < 0.1, "{:?}", s[0].matrix); + assert!(matches!(s[1].geometry, Geometry::Ellipse { w, h } if (w - 40.0).abs() < 0.1 && (h + 40.0).abs() < 0.1)); + assert!(s[1].outline.is_none() && (s[1].matrix.0[4] - 50.0).abs() < 0.1 && (s[1].matrix.0[5] + 50.0).abs() < 0.1); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths[0].closed && matches!(p.subpaths[0].segments[1], Segment::Cubic(..)))); + assert!(s[2].fill.is_none() && s[2].outline.is_some()); + assert_eq!(&s[2].matrix.0[..4], &[2.0, 0.0, 0.0, 2.0]); + } +} + +#[test] +fn a_version_1_matrix_and_point_place_the_shape() { + use synth::WlShape; + // x' = 0 x - 1 y + 72 and y' = 1 x + 0 y + 36: a quarter turn, then a shift. + let turned = synth::wl_object(WlShape::Rect { w: 10.0, h: 10.0, radius: 0.0 }, [0.0, 1.0, -1.0, 0.0, 72.0, 36.0], None, None); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[turned]), Limits::default()).unwrap(); + let m = shapes(wl_objects(&d))[0].matrix; + assert!(m.0.iter().zip([0.0, 1.0, -1.0, 0.0, 72.0, 36.0]).all(|(a, b)| (a - b).abs() < 0.01), "{m:?}"); + let at = m.apply(craft_cdr::model::Pt { x: 10.0, y: 0.0 }); + assert!((at.x - 72.0).abs() < 0.01 && (at.y - 46.0).abs() < 0.01, "{at:?}"); +} + +#[test] +fn version_1_arcs_and_text_are_left_out_with_a_warning() { + use synth::WlShape; + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let arc = synth::wl_object(WlShape::Ellipse { w: 40.0, h: 40.0, angles: (0, 900) }, unit, None, None); + let whole = synth::wl_object(WlShape::Ellipse { w: 40.0, h: 40.0, angles: (900, 900) }, unit, None, None); + let mut other = synth::wl_object(WlShape::Text, unit, None, None); + other[60] = 9; + for (records, kept) in [(vec![arc], 0), (vec![whole], 1), (vec![synth::wl_object(WlShape::Text, unit, None, None)], 0), (vec![other], 0)] { + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &records), Limits::default()).unwrap(); + assert_eq!(wl_objects(&d).len(), kept); + assert_eq!(d.warnings.contains(&Warning::UnsupportedObjects), kept == 0); + assert!(!d.warnings.contains(&Warning::Damaged)); + } +} + +#[test] +fn hostile_version_1_files_stop_within_their_bytes_and_limits() { + use synth::WlShape; + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let rect = || synth::wl_object(WlShape::Rect { w: 10.0, h: 10.0, radius: 0.0 }, unit, None, None); + let file = synth::wl_sample(b'e'); + // Cut at every length: an error, or what the bytes still hold. + for len in 0..file.len() { + let _ = read(&file[..len], Limits::default()); + } + // A body size that runs past the records' end. + let mut long = rect(); + long[28..30].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), long]), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); + // A point count larger than the record holds reads the points that fit. + let mut curve = synth::wl_object(WlShape::Curve(vec![(0.0, 0.0, 0x00), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]), unit, None, None); + curve[114..116].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve.clone()]), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); + // Points past the coordinate limit leave the curve out. + curve[114..116].copy_from_slice(&3u16.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve]), Limits { coordinates: 2, ..Limits::default() }).unwrap(); + assert_eq!(wl_objects(&d).len(), 0); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // Objects past the object limit are left out, and records past the chunk limit stop the read. + let many: Vec> = (0..10).map(|_| rect()).collect(); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &many), Limits { objects: 4, ..Limits::default() }).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (4, vec![Warning::TooDeep])); + let groups: Vec> = (0..10).map(|_| synth::wl_group()).collect(); + assert_eq!(read(&synth::wl_file(b'e', (612.0, 792.0), &groups), Limits { chunks: 4, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read(&file, Limits { input: file.len() - 1, ..Limits::default() }), Err(Error::Limit("input size"))); + // Bytes left after the last whole record are damage. + let mut ragged = vec![rect()]; + ragged.push(vec![0; 5]); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &ragged), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); +} + +#[test] +fn a_wl_prefix_alone_is_not_a_drawing() { + for bytes in [ + &b"WL"[..], + b"WLe\0", + b"WLAN settings, exported as plain text for the help desk", + // Records that start inside the header, and a marker and a fourth byte no source gives. + b"WLe\0\x1c\0\0\0\x10\0\0\0\x1c\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", + b"WLAN\x1c\0\0\0\x1c\0\0\0\x1c\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", + ] { + assert!(!craft_cdr::is_cdr(bytes)); + assert_eq!(read(bytes, Limits::default()), Err(Error::NotCdr)); + } +} + +#[test] +fn versions_outside_1_to_27_and_other_files_are_refused() { + // No source shows a RIFF file of version 1 or 2: those versions are `WL` files. + for version in [100, 200] { + let refused = read(&synth::riff(version, &[]), Limits::default()).unwrap_err(); + assert_eq!(refused, Error::Unsupported("RIFF files of versions before 3"), "{version}"); + assert_eq!(refused.to_string(), "RIFF files of versions before 3 are not read"); + } + assert_eq!(read(&synth::riff(2800, &[]), Limits::default()), Err(Error::Version(2800))); + assert_eq!(read(b"RIFF\x04\0\0\0WAVE", Limits::default()), Err(Error::NotCdr)); + assert_eq!(read(b"RIFF\x04\0\0\0CDRX", Limits::default()), Err(Error::NotCdr)); + assert!(!craft_cdr::is_cdr(b"PK\x03\x04")); + assert!(craft_cdr::is_cdr(&synth::sample(1100, true))); +} + +#[test] +fn letters_that_count_differently_take_the_vrsn_version() { + // Version 27 saves the letter `U`, which counts as 29 the older way; the next letter with a + // `vrsn` of 2800 is refused as version 28. + let mut file = synth::sample(2700, false); + file[11] = b'U'; + let d = read(&file, Limits::default()).unwrap(); + check_pages(&d, 2700); + check_shapes(&d, 2700); + let mut file = synth::riff(2800, &[chunk(b"vrsn", 2800u16.to_le_bytes().to_vec())]); + file[11] = b'V'; + assert_eq!(read(&file, Limits::default()), Err(Error::Version(2800))); +} + +#[test] +fn every_version_from_14_to_27_reads_its_package() { + for version in [1400, 1500, 1600, 1700, 1800, 2000, 2200, 2400, 2430, 2600, 2700] { + for compress in [false, true] { + let file = synth::sample_file(version, compress); + assert!(file.starts_with(b"PK\x03\x04") && craft_cdr::is_cdr(&file), "{version}"); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version} {compress}: {e}")); + assert!(!d.warnings.contains(&Warning::Damaged), "{version} {compress}: {:?}", d.warnings); + check_pages(&d, version); + check_shapes(&d, version); + } + } +} + +/// The version 17 sample's content with `extra` added after it, as a package. +fn package17(extra: Vec, members: &[synth::Member]) -> Vec { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + body.extend(extra); + synth::package16(1700, &body, true, members) +} + +#[test] +fn lists_whose_bodies_move_to_a_data_stream_read_the_same() { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + for moved in [*b"layr", *b"obj ", *b"page"] { + let file = synth::package16_with(1700, &body, true, &[], &[moved]); + let d = read(&file, Limits::default()).unwrap(); + assert!(!d.warnings.contains(&Warning::Damaged), "{moved:?}: {:?}", d.warnings); + check_pages(&d, 1700); + check_shapes(&d, 1700); + } +} + +#[test] +fn a_data_stream_no_chunk_reads_is_not_inflated() { + // 32 MiB of picture data that the reader doesn't use, in a stream of its own. + let bitmaps = list(b"bmpt", vec![chunk(b"bmp ", vec![0; 32 << 20])]); + let file = package17(vec![bitmaps], &[]); + assert!(file.len() < 1 << 20); + let d = read(&file, Limits { inflated: 4 << 20, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); + check_shapes(&d, 1700); +} + +#[test] +fn a_redirected_list_is_inflated_and_counts_toward_the_limit() { + // A list whose body is in a stream must be inflated to be split; past the limit it is left + // out with a warning, and the rest of the drawing reads. + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + body.push(list(b"bmpt", vec![chunk(b"bmp ", vec![0; 32 << 20])])); + let file = synth::package16_with(1700, &body, true, &[], &[*b"bmpt"]); + let d = read(&file, Limits { inflated: 4 << 20, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep) && !d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + check_shapes(&d, 1700); + let d = read(&file, Limits::default()).unwrap(); + assert!(!d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn chunks_in_a_data_stream_past_a_limit_are_not_damage() { + // A record and a list in a 2 MiB stream, read with a 1 MiB member limit, stored and deflated + // with a 1 MiB inflate limit: only the limit warning. + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.resize(2 << 20, 0); + stream[(1 << 20)..(1 << 20) + 4].copy_from_slice(b"fntt"); + let mut root = b"RIFF".to_vec(); + let body = doc_of(&[redirect(b"mcfg", 0, n, 0), redirect(b"LIST", 0, 4, 1 << 20)]); + root.extend(((body.len() + 4) as u32).to_le_bytes()); + root.extend(b"CDRH"); + root.extend(body); + let m = |name: &str, data: Vec, deflate: bool| synth::Member { name: name.into(), data, deflate }; + for (deflate, limits) in [(false, Limits { member: 1 << 20, ..Limits::default() }), (true, Limits { inflated: 1 << 20, ..Limits::default() })] { + let file = synth::zip( + &[ + m("content/root.dat", root.clone(), false), + m("content/dataFileList.dat", b"data1.dat".to_vec(), false), + m("content/data/data1.dat", stream.clone(), deflate), + ], + b"", + ); + let d = read(&file, limits).unwrap(); + assert_eq!(d.warnings, vec![Warning::TooDeep], "{deflate}"); + assert!(d.page_size.is_none()); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{deflate}: {:?}", d.warnings); + } +} + +#[test] +fn encrypted_data_streams_and_other_methods_are_refused() { + let good = synth::sample_file(1700, false); + assert!(read(&good, Limits::default()).is_ok()); + // The directory entry of a data stream: its name's last place, 46 bytes after the entry start. + let name = b"content/data/data1.dat"; + let entry = good.windows(name.len()).rposition(|w| w == name).unwrap() - 46; + assert_eq!(&good[entry..entry + 4], b"PK\x01\x02"); + let mut encrypted = good.clone(); + encrypted[entry + 8] |= 1; + assert_eq!(read(&encrypted, Limits::default()), Err(Error::Unsupported("encrypted packages"))); + let mut other = good.clone(); + other[entry + 10] = 12; + assert_eq!(read(&other, Limits::default()), Err(Error::Unsupported("package compression methods other than storing and deflate"))); +} + +/// A version 17 package whose `root.dat` is `root` (the RIFF body after the form type) and whose +/// one data stream is `stream`. +fn raw_package(root: &[u8], stream: &[u8], list: &[u8]) -> Vec { + let mut riff = b"RIFF".to_vec(); + riff.extend(((root.len() + 4) as u32).to_le_bytes()); + riff.extend(b"CDRH"); + riff.extend(root); + let m = |name: &str, data: &[u8]| synth::Member { name: name.into(), data: data.to_vec(), deflate: false }; + synth::zip(&[m("content/root.dat", &riff), m("content/dataFileList.dat", list), m("content/data/data1.dat", stream)], b"") +} + +/// A chunk header for a redirect record of `stream`, `len` and `offset`. +fn redirect(id: &[u8; 4], stream: u32, len: u32, offset: u32) -> Vec { + let mut out = id.to_vec(); + out.extend(16u32.to_le_bytes()); + for v in [stream, len, offset, 0] { + out.extend(v.to_le_bytes()); + } + out +} + +#[test] +fn a_list_redirected_into_its_own_bytes_is_read_once() { + // The stream holds a `grp ` body whose children are lists redirected to that body again: + // the bytes are taken, so each child is damage and the list is read once. + for children in [1, 2] { + let len = 4 + 24 * children; + let mut stream = b"grp ".to_vec(); + for _ in 0..children { + stream.extend(redirect(b"LIST", 0, len, 0)); + } + let file = raw_package(&redirect(b"LIST", 0, len, 0), &stream, b"data1.dat"); + let d = read(&file, Limits { chunks: 100, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::Damaged], "{children}"); + } +} + +/// A `doc ` list holding `records`, as `root.dat`'s body. +fn doc_of(records: &[Vec]) -> Vec { + let records = records.concat(); + let mut body = b"LIST".to_vec(); + body.extend(((records.len() + 4) as u32).to_le_bytes()); + body.extend(b"doc "); + body.extend(records); + body +} + +#[test] +fn records_share_bytes_within_the_member_limit() { + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.extend(&mcfg); + // The same bytes, bytes that overlap them, bytes that only touch them, and the same bytes + // through a second line naming the same member: both redirects read. + for (second, list) in [ + (redirect(b"mcfg", 0, n, 0), &b"data1.dat"[..]), + (redirect(b"mcfg", 0, n, n - 1), b"data1.dat"), + (redirect(b"mcfg", 0, n, n), b"data1.dat"), + (redirect(b"mcfg", 1, n, 0), b"data1.dat\ndata1.dat"), + ] { + let file = raw_package(&doc_of(&[redirect(b"mcfg", 0, n, 0), second.clone()]), &stream, list); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{:?}: {:?}", &second[8..], d.warnings); + } + // Bytes read again take from the member limit: with a limit of the stream's 1,024 bytes, a + // record of all of them reads twice, and a third read is left out with the limit warning. + let mut stream = mcfg.clone(); + stream.resize(1024, 0); + let limits = Limits { member: 1024, ..Limits::default() }; + for (reads, warnings) in [(2, vec![]), (3, vec![Warning::TooDeep])] { + let records = vec![redirect(b"mcfg", 0, 1024, 0); reads]; + let d = read(&raw_package(&doc_of(&records), &stream, b"data1.dat"), limits).unwrap(); + assert!(d.page_size.is_some(), "{reads}"); + assert_eq!(d.warnings, warnings, "{reads}"); + } +} + +#[test] +fn a_member_two_streams_name_is_inflated_once() { + // One deflated member of 2 MiB named on two lines, a list read from one and the page size + // from the other: within a 3 MiB inflate limit it is inflated once. + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.resize(2 << 20, 0); + stream[(1 << 20)..(1 << 20) + 4].copy_from_slice(b"fntt"); + let mut root = b"RIFF".to_vec(); + let body = doc_of(&[redirect(b"LIST", 1, 4, 1 << 20), redirect(b"mcfg", 0, n, 0)]); + root.extend(((body.len() + 4) as u32).to_le_bytes()); + root.extend(b"CDRH"); + root.extend(body); + let m = |name: &str, data: Vec, deflate: bool| synth::Member { name: name.into(), data, deflate }; + let file = synth::zip( + &[ + m("content/root.dat", root, false), + m("content/dataFileList.dat", b"data1.dat\ndata1.dat".to_vec(), false), + m("content/data/data1.dat", stream, true), + ], + b"", + ); + let d = read(&file, Limits { inflated: 3 << 20, ..Limits::default() }).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{:?}", d.warnings); +} + +#[test] +fn redirects_past_their_stream_or_to_a_missing_one_are_damage() { + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + for (root, list, damaged) in [ + (redirect(b"mcfg", 0, n, 0), &b"data1.dat"[..], false), + (redirect(b"mcfg", 0, n, 0), b"data1.dat\r\n", false), + (redirect(b"mcfg", 0, n + 1, 0), b"data1.dat", true), + (redirect(b"mcfg", 0, n, u32::MAX), b"data1.dat", true), + (redirect(b"mcfg", 1, n, 0), b"data1.dat", true), + (redirect(b"mcfg", 0, n, 0), b"gone.dat", true), + (redirect(b"mcfg", 0, n, 0), b"", true), + ] { + let mut body = b"LIST".to_vec(); + body.extend(((root.len() + 4) as u32).to_le_bytes()); + body.extend(b"doc "); + body.extend(&root); + let d = read(&raw_package(&body, &mcfg, list), Limits::default()).unwrap(); + assert_eq!(d.warnings.contains(&Warning::Damaged), damaged, "{list:?} {:?}", &root[8..]); + assert_eq!(d.page_size.is_some(), !damaged); + } +} + +#[test] +fn a_redirect_record_holds_up_to_8_bytes_itself() { + let mut inline = b"vrsn".to_vec(); + inline.extend(16u32.to_le_bytes()); + inline.extend(u32::MAX.to_le_bytes()); + inline.extend(2u32.to_le_bytes()); + inline.extend(1800u16.to_le_bytes()); + inline.extend([0; 6]); + let d = read(&raw_package(&inline, b"", b""), Limits::default()).unwrap(); + assert_eq!(d.version, 1800); + // A length past the record's 8 bytes is damage, and the form type's version stands. + inline[12] = 9; + let d = read(&raw_package(&inline, b"", b""), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + assert_eq!(d.version, 1700); +} + +fn zip_of(members: &[(&str, Vec)]) -> Vec { + let m: Vec<_> = members.iter().map(|(n, d)| synth::Member { name: (*n).into(), data: d.clone(), deflate: false }).collect(); + synth::zip(&m, b"") +} + +/// Where the first central directory entry starts. +fn directory(bytes: &[u8]) -> usize { + bytes.windows(4).position(|w| w == b"PK\x01\x02").unwrap() +} + +#[test] +fn hostile_packages_are_refused() { + let riff = synth::sample(1400, false); + let good = zip_of(&[("content/riffData.cdr", riff.clone())]); + assert!(read(&good, Limits::default()).is_ok()); + // More members than a read takes. + let many: Vec<(String, Vec)> = (0..4097).map(|i| (format!("m{i}"), vec![])).collect(); + let many: Vec<(&str, Vec)> = many.iter().map(|(n, d)| (n.as_str(), d.clone())).collect(); + assert_eq!(read(&zip_of(&many), Limits::default()), Err(Error::Limit("package member count"))); + assert_eq!(read(&zip_of(&many[..4096]), Limits::default()), Err(Error::NotCdr)); + // A member named twice. + let twice = zip_of(&[("content/riffData.cdr", riff.clone()), ("content/riffData.cdr", riff.clone())]); + assert_eq!(read(&twice, Limits::default()), Err(Error::Damaged("package member named twice"))); + // A member whose bytes run into the next member's header. + let two = zip_of(&[("a", vec![1; 10]), ("content/riffData.cdr", riff.clone())]); + let mut overlap = two.clone(); + let at = directory(&two) + 20; + overlap[at..at + 4].copy_from_slice(&20u32.to_le_bytes()); + assert_eq!(read(&overlap, Limits::default()), Err(Error::Damaged("package members overlap"))); + // A central directory cut short, and an archive without its end record. + let mut short = good.clone(); + let n = short.len(); + let len_at = n - 22 + 12; + let len = u32::from_le_bytes(short[len_at..len_at + 4].try_into().unwrap()); + short[len_at..len_at + 4].copy_from_slice(&(len - 10).to_le_bytes()); + assert_eq!(read(&short, Limits::default()), Err(Error::Damaged("package directory"))); + assert_eq!(read(&good[..directory(&good) + 30], Limits::default()), Err(Error::Damaged("package directory"))); + // Encrypted members, ZIP64 fields and archives split across files. + let mut encrypted = good.clone(); + encrypted[directory(&good) + 8] |= 1; + assert_eq!(read(&encrypted, Limits::default()), Err(Error::Unsupported("encrypted packages"))); + let mut zip64 = good.clone(); + zip64[n - 22 + 10..n - 22 + 12].copy_from_slice(&[0xff, 0xff]); + assert_eq!(read(&zip64, Limits::default()), Err(Error::Unsupported("ZIP64 packages"))); + let mut split = good.clone(); + split[n - 22 + 4] = 1; + assert_eq!(read(&split, Limits::default()), Err(Error::Unsupported("packages split across files"))); +} + +#[test] +fn a_package_member_bomb_stops_at_its_stated_size_or_the_limit() { + let riff = synth::sample(1400, false); + let m = synth::Member { name: "content/riffData.cdr".into(), data: riff.clone(), deflate: true }; + let good = synth::zip(std::slice::from_ref(&m), b""); + assert!(read(&good, Limits::default()).is_ok()); + // A member that inflates past the size its entry states stops one byte past it. + let bomb = synth::zip(&[synth::Member { data: [riff.clone(), vec![0; 64 << 20]].concat(), ..m.clone() }], b""); + assert!(bomb.len() < 1 << 20); + let mut lying = bomb.clone(); + let at = directory(&bomb) + 24; + lying[at..at + 4].copy_from_slice(&(riff.len() as u32).to_le_bytes()); + assert_eq!(read(&lying, Limits::default()), Err(Error::Damaged("package member"))); + // One that states more than a member may hold, or than is left to inflate, is not inflated. + assert_eq!(read(&bomb, Limits { member: 1 << 20, ..Limits::default() }), Err(Error::Limit("package member size"))); + assert_eq!(read(&bomb, Limits { inflated: 1 << 20, ..Limits::default() }), Err(Error::Limit("inflated size"))); +} + +#[test] +fn stored_package_members_take_nothing_from_the_inflate_limit() { + // Nothing may be inflated, and the stored members of either package layout still read, as + // the same drawing does as a plain RIFF file. + let none = Limits { inflated: 0, ..Limits::default() }; + assert!(read(&synth::sample(1400, false), none).is_ok()); + for version in [1400, 1700] { + let d = read(&synth::sample_file(version, false), none).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(d.warnings.iter().all(|w| *w == Warning::UnsupportedObjects), "{version}: {:?}", d.warnings); + check_shapes(&d, version); + } + // Deflated members do take from it. + assert_eq!(read(&synth::sample_file(1400, true), none), Err(Error::Limit("inflated size"))); +} + +#[test] +fn redirect_records_that_lead_nowhere_count_toward_the_chunk_limit() { + // 3,000 redirects to a stream the package lacks: each lost record is counted. + let root: Vec = (0..3000).flat_map(|_| redirect(b"mcfg", 7, 4, 0)).collect(); + let file = raw_package(&root, b"", b"data1.dat"); + assert_eq!(read(&file, Limits { chunks: 2_000, ..Limits::default() }), Err(Error::Limit("chunk count"))); + let d = read(&file, Limits { chunks: 4_000, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() { + let v = V(1500); + let mut c = synth::V(1500).rect(100.0, 50.0, 0.0); + // The four shares: 0.2, 0.4, 0, and 3, which half the shorter side holds to 25 pt. + for (k, share) in [0.2f64, 0.4, 0.0, 3.0].iter().enumerate() { + let at = 40 + 24 * k; + c[at..at + 8].copy_from_slice(&share.to_le_bytes()); + } + let file = + synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c.clone())], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { w, h, radii } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + assert!((w - 100.0).abs() < 1e-6 && (h - 50.0).abs() < 1e-6); + for (got, want) in radii.iter().zip([5.0, 10.0, 0.0, 25.0]) { + assert!((got - want).abs() < 1e-6, "{radii:?}"); + } + // With the scale-with flag set the radii are inches, held to half the shorter side as well. + c[32] = 1; + let file = synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + for (got, want) in radii.iter().zip([14.4, 25.0, 0.0, 25.0]) { + assert!((got - want).abs() < 1e-6, "{radii:?}"); + } +} + +#[test] +fn paths_from_version_10_read_their_points() { + let v = V(1700); + let mut c = vec![0; 4]; + c.extend(2u16.to_le_bytes()); + c.extend(1u16.to_le_bytes()); + c.extend([0; 16]); + c.extend(&v.points(&[(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0x48)])[4..]); + let objects = |version: u16| { + let v = V(version); + synth::riff( + version, + &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 0x25, &[(30, c.clone())], None)])])], + ) + }; + for version in [1000, 1300, 1500, 1700] { + let d = read(&objects(version), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Path(p) = &s[0].geometry else { panic!("{version}: {:?}", s[0].geometry) }; + assert_eq!(p.subpaths[0].segments.len(), 2); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } + // No sample before version 10 holds the type, so it is not read as a path there. + let d = read(&objects(900), Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty() && d.warnings.contains(&Warning::UnsupportedObjects)); +} + +#[test] +fn a_template_takes_its_version_from_the_vrsn_chunk() { + let mut file = synth::sample(2100, false); + file[8..12].copy_from_slice(b"CDTQ"); + assert!(craft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.version, 2100); + check_shapes(&d, 2100); + let mut bare = synth::riff(2100, &[]); + bare[8..12].copy_from_slice(b"CDTQ"); + assert_eq!(read(&bare, Limits::default()), Err(Error::NotCdr)); + // A template of a version after 27 is refused by its version, and one before 3 as a RIFF + // file of those versions. + for (version, refused) in [(2800u16, Error::Version(2800)), (200, Error::Unsupported("RIFF files of versions before 3"))] { + let mut t = synth::riff(2100, &[chunk(b"vrsn", version.to_le_bytes().to_vec())]); + t[8..12].copy_from_slice(b"CDTQ"); + assert_eq!(read(&t, Limits::default()), Err(refused)); + } +} + +#[test] +fn layers_take_their_kind_from_their_object_type() { + for version in [300, 800, 1300, 1700] { + let v = V(version); + let rect = || synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None); + // Version 3 counts its types from 0 (R32). + let ty = |t: u32| if version < 400 { t - 1 } else { t }; + // Master page layers flagged in the older way, with the types of guides and desktop layers, + // and a drawing layer whose flags would make it a desktop layer. + let master = synth::page( + true, + vec![ + synth::layer_of_type(v, [2, 1, 1, 0x98], ty(12), "G", vec![rect()]), + synth::layer_of_type(v, [0, 1, 1, 0x98], ty(17), "D", vec![rect()]), + synth::layer_of_type(v, [8, 1, 0, 0x98], 0, "M", vec![rect()]), + ], + ); + // A drawing layer with flag bit 0x10 set, and a grid layer. + let own = synth::page( + false, + vec![ + synth::layer_of_type(v, [0x10, 0, 0, 0x98], 0, "L", vec![rect()]), + synth::layer_of_type(v, [0x1a, 0, 1, 0x98], ty(11), "Grid", vec![rect()]), + ], + ); + let body = [chunk(b"vrsn", version.to_le_bytes().to_vec()), master, own]; + let file = if version < 1400 { synth::riff(version, &body) } else { synth::package16(version, &body, true, &[]) }; + let d = read(&file, Limits::default()).unwrap(); + let kinds: Vec<_> = d.master.iter().map(|l| l.kind).collect(); + assert_eq!(kinds, [LayerKind::Guides, LayerKind::Desktop, LayerKind::Drawing], "{version}"); + let kinds: Vec<_> = d.pages[0].layers.iter().map(|l| (l.kind, l.objects.len())).collect(); + assert_eq!(kinds, [(LayerKind::Drawing, 1), (LayerKind::Grid, 1)], "{version}"); + } +} + +#[test] +fn a_lower_case_form_type_names_the_same_versions() { + let mut file = synth::sample(600, false); + file[8..12].copy_from_slice(b"cdr6"); + // The `vrsn` chunk agrees; without it the form type alone decides. + assert_eq!(read(&file, Limits::default()).unwrap().version, 600); + assert!(craft_cdr::is_cdr(&file)); + file[8..12].copy_from_slice(b"cdrX"); + assert_eq!(read(&file, Limits::default()), Err(Error::NotCdr)); +} + +#[test] +fn rectangles_keep_four_corner_radii_from_version_9() { + let v = V(900); + let c = [v.coord(100.0), v.coord(50.0), v.coord(1.0), v.coord(2.0), v.coord(3.0), v.coord(4.0)].concat(); + let file = synth::riff(900, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + for (got, want) in radii.iter().zip([1.0, 2.0, 3.0, 4.0]) { + assert!((got - want).abs() < 0.01, "{radii:?}"); + } + // Before version 9 one radius rounds every corner. + let v = V(800); + let c = [v.coord(100.0), v.coord(50.0), v.coord(6.0)].concat(); + let file = synth::riff(800, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let s = read(&file, Limits::default()).unwrap(); + let s = shapes(&s.pages[0].layers[0].objects); + assert!(matches!(s[0].geometry, Geometry::Rect { radii, .. } if radii.iter().all(|r| (r - 6.0).abs() < 0.01))); +} + +#[test] +fn version_7_guidelines_count_toward_the_object_limit() { + let v = V(700); + let mut guid = 1000u32.to_le_bytes().to_vec(); + guid.extend(1000u32.to_le_bytes()); + for i in 0..1000 { + guid.extend([0; 12]); + guid.extend(90_000_000i32.to_le_bytes()); + guid.extend([v.coord(f64::from(i)), v.coord(0.0), v.coord(f64::from(i)), v.coord(1.0), v.coord(f64::from(i)), v.coord(0.0)].concat()); + } + let file = synth::riff(700, &[chunk(b"vrsn", 700u16.to_le_bytes().to_vec()), list(b"doc ", vec![chunk(b"guid", guid)])]); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.guides.len(), 1000); + let d = read(&file, Limits { objects: 10, ..Limits::default() }).unwrap(); + assert_eq!(d.guides.len(), 10); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +/// Guidelines on any layer of the master page show on every page, not only those of its guides +/// layer: one on a drawing layer that also holds art, and one alone on the desktop layer. +#[test] +fn master_guidelines_on_any_layer_show_on_every_page() { + let v = V(1100); + let guide = |x: f64| { + let mut g = vec![0; 12]; + g.extend(90_000_000i32.to_le_bytes()); + g.extend([v.coord(x), v.coord(0.0)].concat()); + synth::object(v, 0x16, &[(16000, g)], None) + }; + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let master = synth::page( + true, + vec![synth::layer(v, [0, 0, 1, 0x98], "Art", vec![guide(10.0), rect]), synth::layer(v, [0x08, 0, 1, 0x98], "Desktop", vec![guide(20.0)])], + ); + let file = synth::riff(1100, &[master, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", vec![])])]); + let d = read(&file, Limits::default()).unwrap(); + let mut xs: Vec = d.guides.iter().map(|g| g.at.x).collect(); + xs.sort_by(f64::total_cmp); + assert_eq!(xs.len(), 2, "{:?}", d.guides); + assert!((xs[0] - 10.0).abs() < 0.01 && (xs[1] - 20.0).abs() < 0.01, "{xs:?}"); + assert_eq!(d.master.len(), 1); + assert_eq!(d.master[0].objects.len(), 1); +} + +/// An object with more arguments than the limit keeps the ones read paired with their own types: +/// the types table runs from the stored count, not from the limit. +#[test] +fn arguments_past_the_limit_leave_the_first_ones_paired_with_their_types() { + let v = V(1100); + let mut args = vec![(30, [v.coord(40.0), v.coord(20.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())]; + args.extend((0..69).map(|i| (500 + i, vec![0; 4]))); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!( + matches!(s.first().map(|s| &s.geometry), Some(Geometry::Rect { w, h, .. }) if (w - 40.0).abs() < 0.01 && (h - 20.0).abs() < 0.01), + "{s:?}" + ); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +/// Groups count toward the object limit; a group past it leaves its objects ungrouped. +#[test] +fn groups_count_toward_the_object_limit() { + fn count(objects: &[Object]) -> usize { + objects.iter().map(|o| 1 + if let Object::Group { objects: kids, .. } = o { count(kids) } else { 0 }).sum() + } + let v = V(1100); + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let nested = list(b"grp ", vec![list(b"grp ", vec![rect])]); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![nested])])]); + let d = read(&file, Limits { objects: 2, ..Limits::default() }).unwrap(); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(count(objects), 2, "{objects:?}"); + assert!(matches!(objects.as_slice(), [Object::Group { objects: kids, .. }] if matches!(kids.as_slice(), [Object::Shape(_)])), "{objects:?}"); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +/// A rectangle, ellipse, curve or polygon stored without its coordinates is left out as damage. +#[test] +fn shapes_without_their_coordinates_are_damage() { + let v = V(1100); + for kind in [1, 2, 3, 0x14] { + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, kind, &[], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty(), "{kind}"); + assert!(d.warnings.contains(&Warning::Damaged), "{kind}: {:?}", d.warnings); + } +} + +/// An object list without its `loda`, a fill or outline record that can't be read, and a `guid` +/// chunk that counts more guidelines than it holds are each damage. +#[test] +fn unreadable_records_and_lists_are_damage() { + let v = V(1300); + let rect = |args: Vec<(u32, Vec)>| { + let mut args = args; + args.push((30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())); + synth::object(v, 1, &args, None) + }; + let on_page = |objects: Vec, styles: Vec| { + let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())]; + kids.extend(styles); + kids.push(synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)])); + read(&synth::riff(1300, &kids), Limits::default()).unwrap() + }; + let d = on_page(vec![list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08])])], vec![]); + assert!(d.warnings.contains(&Warning::Damaged), "no loda: {:?}", d.warnings); + // A fill record of only its id. + let d = on_page(vec![rect(vec![(20, 4u32.to_le_bytes().to_vec())])], vec![list(b"filt", vec![chunk(b"fild", 4u32.to_le_bytes().to_vec())])]); + assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].fill, None); + assert!(d.warnings.contains(&Warning::Damaged), "fill: {:?}", d.warnings); + // A tagged outline whose first records are none of record 1. + let mut outl = 9u32.to_le_bytes().to_vec(); + for _ in 0..16 { + outl.extend(5u32.to_le_bytes()); + outl.extend(0u32.to_le_bytes()); + } + let d = on_page(vec![rect(vec![(10, 9u32.to_le_bytes().to_vec())])], vec![list(b"otlt", vec![chunk(b"outl", outl)])]); + assert!(shapes(&d.pages[0].layers[0].objects)[0].outline.is_none()); + assert!(d.warnings.contains(&Warning::Damaged), "outline: {:?}", d.warnings); + // Version 7: a `guid` chunk counting three guidelines and holding one. + let mut guid = 3u32.to_le_bytes().to_vec(); + guid.extend(3u32.to_le_bytes()); + guid.extend([0; 40]); + let d = read(&synth::riff(700, &[chunk(b"vrsn", 700u16.to_le_bytes().to_vec()), list(b"doc ", vec![chunk(b"guid", guid)])]), Limits::default()) + .unwrap(); + assert_eq!(d.guides.len(), 1); + assert!(d.warnings.contains(&Warning::Damaged), "guid: {:?}", d.warnings); +} + +/// Pages keep their layers in a `gobj` list, and layers and objects their `loda` (and objects +/// their transform) in a `lgob` list. The layout with those chunks directly in the page, layer and +/// object lists reads the same. +#[test] +fn layers_and_objects_read_from_their_gobj_and_lgob_lists() { + let v = V(1000); + let c = [v.coord(10.0), v.coord(20.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat(); + let m = [1.0, 0.0, 0.0, 1.0, 5.0, 6.0]; + let nested = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c.clone())], Some(m))])]); + let plain_object = list(b"obj ", vec![chunk(b"loda", v.loda(1, &[(30, c)])), list(b"trfl", vec![chunk(b"trfd", v.trfd(&[m]))])]); + let plain_layer = list(b"layr", vec![chunk(b"flgs", vec![0, 0, 0, 0x98]), chunk(b"loda", v.loda(0, &[(1000, b"L\0".to_vec())])), plain_object]); + let plain = list(b"page", vec![chunk(b"flgs", vec![0, 0, 0, 0x90]), plain_layer]); + for page in [nested, plain] { + let d = read(&synth::riff(1000, &[page]), Limits::default()).unwrap(); + let layer = &d.pages[0].layers[0]; + assert_eq!(layer.name, "L"); + let s = shapes(&layer.objects); + assert_eq!(s.len(), 1, "{:?}", layer.objects); + assert!(matches!(s[0].geometry, Geometry::Rect { w, .. } if (w - 10.0).abs() < 0.01)); + assert!((s[0].matrix.0[4] - 5.0).abs() < 0.01 && (s[0].matrix.0[5] - 6.0).abs() < 0.01, "{:?}", s[0].matrix); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + } +} + +/// From version 7 a `LIST stlt` holds the style tables, which don't parse as chunks: it is not +/// damage. +#[test] +fn a_style_table_list_is_not_read_as_chunks() { + let v = V(1000); + let stlt = chunk(b"LIST", [b"stlt".to_vec(), 3u32.to_le_bytes().to_vec(), vec![0xff; 30]].concat()); + let d = read(&synth::riff(1000, &[list(b"doc ", vec![stlt, synth::mcfg(v, 100.0, 50.0)])]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert!(d.page_size.is_some_and(|(w, h)| (w - 100.0).abs() < 0.01 && (h - 50.0).abs() < 0.01)); +} + +/// Before version 7 a `LIST stlt` holds chunks (R4), which are read like the document's others. +#[test] +fn a_style_list_before_version_7_is_read_as_chunks() { + for version in [400, 500, 600] { + let v = V(version); + let red = if version < 500 { synth::color4(1, [0, 100, 100, 0]) } else { synth::color(5, [0, 0, 255, 0]) }; + let styles = list(b"stlt", vec![list(b"filt", vec![chunk(b"fill", v.fill(1, &red))])]); + let rect = synth::object(v, 1, &[(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect])]); + let content = vec![list(b"doc ", vec![styles]), page]; + let d = read(&synth::file_of(version, content.clone()), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].fill.is_some(), "{version}"); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + // A template, whose form type names no version, by its `vrsn` chunk. + let mut template = synth::file_of(version, content); + template[8..12].copy_from_slice(b"CDTA"); + let d = read(&template, Limits::default()).unwrap(); + assert!(shapes(&d.pages[0].layers[0].objects)[0].fill.is_some(), "{version}"); + } +} + +/// The objects of a styled drawing: a rectangle with only its style (argument 200), one whose +/// style leaves the fill and outline to its parent, and one with an outline argument of its own. +fn graphic_style_drawing(version: u16, table: synth::Node) -> Vec { + let v = V(version); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }, &black, &[])), + ], + ), + table, + ], + ); + let rect = (30, v.rect(20.0, 10.0, 0.0)); + let styled = |style: u32, own: &[(u32, Vec)]| { + let mut args = vec![(200, style.to_le_bytes().to_vec())]; + args.extend(own.iter().cloned()); + args.push(rect.clone()); + synth::object(v, 1, &args, None) + }; + let objects = vec![styled(0x10, &[]), styled(0x11, &[]), styled(0x10, &[(10, 3u32.to_le_bytes().to_vec())])]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +/// From version 7 an object without a fill or outline argument of its own takes its style's +/// (argument 200, `LIST stlt`), through the style's parent where the style names none; its own +/// argument wins over the style's. +#[test] +fn objects_without_their_own_fill_or_outline_take_their_styles() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for version in [700, 800, 801, 900, 1000, 1100, 1200, 1300, 1400, 1500] { + for text in [false, true] { + let table = synth::stlt(V(version), &[(0x100, 1)], &[(0x200, 2)], &styles, text); + let d = read(&graphic_style_drawing(version, table), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3, "{version}"); + for shape in &s[..2] { + assert_eq!(shape.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(shape.outline.as_ref().is_some_and(|o| (o.width - 2.0).abs() < 0.05), "{version} {text}: {:?}", shape.outline); + } + assert_eq!(s[2].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(s[2].outline.is_none(), "{version} {text}"); + assert!(d.warnings.is_empty(), "{version} {text}: {:?}", d.warnings); + } + } +} + +/// A template whose style table comes before its `vrsn` chunk still reads the table by the +/// version that chunk names. +#[test] +fn a_style_table_before_the_version_chunk_reads_by_that_version() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let table = synth::stlt(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + let mut file = graphic_style_drawing(1000, chunk(b"junk", vec![])); + // The drawing's chunks, the table put first, ahead of `vrsn`. + let body = file.split_off(12); + file.extend(synth::plain(&table)); + file.extend(body); + file[8..12].copy_from_slice(b"CDTA"); + let len = (file.len() - 8) as u32; + file[4..8].copy_from_slice(&len.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); +} + +/// A style table that doesn't parse to its end is damage when an object needs a style from it; +/// the object is drawn with what it holds itself. +#[test] +fn a_style_table_that_does_not_parse_is_damage_when_an_object_needs_it() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let mut body = synth::stlt_body(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + body.push(0); + let table = chunk(b"LIST", [b"stlt".to_vec(), body].concat()); + let d = read(&graphic_style_drawing(1000, table), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +/// A drawing with fill 1 (red), whose `LIST clpt` holds `groups` and whose page holds `objects`. +fn clip_drawing(version: u16, groups: Vec<(u32, Vec)>, objects: Vec) -> Vec { + let v = V(version); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + synth::clpt(groups), + ], + ); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +fn clip_rect(v: V, w: f64, extra: &[(u32, Vec)], at: [f64; 2]) -> synth::Node { + let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))]; + args.extend(extra.iter().cloned()); + synth::object(v, 1, &args, Some([1.0, 0.0, 0.0, 1.0, at[0], at[1]])) +} + +/// A container (argument 8005) clips the group of `LIST clpt` whose `spnd` id it names; the +/// group's objects keep their own transforms, front to back. +#[test] +fn a_container_clips_the_group_it_names() { + for version in [700, 900, 1200, 1300, 1500, 1600, 2000] { + let v = V(version); + let contents = vec![clip_rect(v, 10.0, &[], [5.0, 6.0]), clip_rect(v, 20.0, &[], [-50.0, 0.0])]; + let container = clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![(0x77, contents)], vec![container]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + let [Object::Clip { container, objects: clipped }] = objects.as_slice() else { panic!("{version}: {objects:?}") }; + assert!(matches!(container.geometry, Geometry::Rect { w, .. } if (w - 40.0).abs() < 0.01), "{version}"); + let s = shapes(clipped); + assert_eq!(s.len(), 2, "{version}"); + assert!((s[0].matrix.0[4] - 5.0).abs() < 0.01 && (s[1].matrix.0[4] + 50.0).abs() < 0.01, "{version}: {:?}", s[0].matrix); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } +} + +/// The feature sample, the seed of the importer's fuzz tests, reads its style table, clipping +/// container, lens, flags, winding flag, transparency and named outline color in every version +/// from 7 to 13, plain and compressed. +#[test] +fn the_feature_sample_reads_its_styles_container_and_lens() { + for version in [700, 800, 900, 1000, 1100, 1200, 1300] { + for compress in [false, true] { + let d = read(&synth::feature_sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + let [ + Object::Shape(styled), + Object::Clip { objects: clipped, .. }, + Object::Shape(_), + Object::Shape(flagged), + Object::Group { objects: grouped, flags }, + ] = objects.as_slice() + else { + panic!("{version}: {objects:?}") + }; + assert_eq!(styled.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version}"); + assert!(styled.outline.as_ref().is_some_and(|o| o.dashes == [3.0, 1.0]), "{version}"); + let s = shapes(clipped); + assert_eq!(s.len(), 2, "{version}"); + assert!(s[1].outline.as_ref().is_some_and(|o| o.behind_fill), "{version}"); + assert_eq!(flagged.flags, Flags { hidden: true, locked: true }, "{version}"); + assert!(flagged.nonzero, "{version}"); + assert_eq!(*flags, Flags { hidden: true, locked: false }, "{version}"); + let named = shapes(grouped)[0].outline.as_ref().map(|o| o.color.clone()); + // A transparency and a named outline color are read from version 13. + if version >= 1300 { + assert_eq!((flagged.opacity, flagged.blend), (0.75, Blend::Multiply), "{version}"); + assert_eq!(named, Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version} {compress}"); + } else { + assert_eq!((flagged.opacity, flagged.blend), (1.0, Blend::Normal), "{version}"); + assert_eq!(named, Some(Color::Spot { name: "Spot 0:7".into(), tint: 1.0, look: None }), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses, Warning::SpotLooks], "{version} {compress}"); + } + } + } +} + +/// A container whose group isn't there is damage, and one whose group holds a container naming +/// it again is read once, with the limit warning; the containers stay as plain shapes. +#[test] +fn a_missing_or_repeating_clipped_group_keeps_the_container() { + let v = V(1100); + let missing = clip_rect(v, 40.0, &[synth::container(0x78)], [0.0, 0.0]); + let d = read(&clip_drawing(1100, vec![(0x77, vec![clip_rect(v, 10.0, &[], [0.0, 0.0])])], vec![missing]), Limits::default()).unwrap(); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)])); + assert_eq!(d.warnings, vec![Warning::Damaged]); + let inner = clip_rect(v, 10.0, &[synth::container(0x77)], [0.0, 0.0]); + let outer = clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0]); + let d = read(&clip_drawing(1100, vec![(0x77, vec![inner])], vec![outer]), Limits::default()).unwrap(); + let [Object::Clip { objects: clipped, .. }] = d.pages[0].layers[0].objects.as_slice() else { panic!("{:?}", d.pages[0].layers[0].objects) }; + assert!(matches!(clipped.as_slice(), [Object::Shape(_)]), "{clipped:?}"); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +/// Each chunk of a clipped group counts toward the clipped chunk limit every time a container +/// names the group, empty groups included; past it the containers stay as plain shapes, and a +/// group cut off at the limit leaves out its guidelines too. +#[test] +fn containers_naming_one_group_stop_at_the_clipped_chunk_limit() { + let v = V(1100); + // The group walks 53 chunks: its `spnd`, a guideline, 50 empty groups and a rectangle. + let mut guide = vec![0; 12]; + guide.extend(90_000_000i32.to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0)].concat()); + let mut contents = vec![synth::object(v, 0x16, &[(16000, guide)], None)]; + contents.extend((0..50).map(|_| list(b"grp ", vec![]))); + contents.push(clip_rect(v, 10.0, &[], [0.0, 0.0])); + let containers: Vec = (0..20).map(|_| clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])).collect(); + let file = clip_drawing(1100, vec![(0x77, contents)], containers); + let count = |objects: &[Object]| objects.iter().filter(|o| matches!(o, Object::Clip { .. })).count(); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!((count(&d.pages[0].layers[0].objects), d.pages[0].layers[0].guides.len()), (20, 20)); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Looking through the guideline's and the rectangle's lists for what they keep for themselves + // takes 13 chunks, counted once. The sixth container's walk stops after its guideline and 8 + // empty groups. + let d = read(&file, Limits { clipped_chunks: 53 * 5 + 13 + 10, ..Limits::default() }).unwrap(); + let layer = &d.pages[0].layers[0]; + assert_eq!((layer.objects.len(), count(&layer.objects), layer.guides.len()), (20, 5, 5)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +/// The chunks an object of a clipped group keeps for itself count toward the clipped chunk limit +/// the first time a container names the group, and are not looked through again for the next +/// containers. +#[test] +fn a_clipped_objects_own_chunks_count_once() { + let v = V(1100); + // A rectangle whose list holds 1,000 chunks before its own 5. + let synth::Node::List(form, own) = clip_rect(v, 10.0, &[], [0.0, 0.0]) else { panic!("an object is a list") }; + let rect = synth::Node::List(form, (0..1000).map(|_| chunk(b"pad ", vec![])).chain(own).collect()); + let containers: Vec = (0..20).map(|_| clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])).collect(); + let file = clip_drawing(1100, vec![(0x77, vec![rect.clone()])], containers); + let count = |d: &craft_cdr::Drawing| d.pages[0].layers[0].objects.iter().filter(|o| matches!(o, Object::Clip { .. })).count(); + // Each container walks the group's `spnd` and the rectangle's list, and the first also looks + // through the rectangle's chunks for its `loda` (1,003 chunks), `flgs` (1,001) and `trfd` + // (1,005). + let first = 1003 + 1001 + 1005; + let d = read(&file, Limits { clipped_chunks: first + 20 * 2, ..Limits::default() }).unwrap(); + assert_eq!(count(&d), 20); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Past the limit while looking through them, no container keeps its group, nor the objects + // and guidelines read before it. + let mut guide = vec![0; 12]; + guide.extend(90_000_000i32.to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0)].concat()); + let before = vec![clip_rect(v, 5.0, &[], [0.0, 0.0]), synth::object(v, 0x16, &[(16000, guide)], None), rect]; + let file = clip_drawing(1100, vec![(0x77, before)], vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])]); + let d = read(&file, Limits { clipped_chunks: 1000, ..Limits::default() }).unwrap(); + let layer = &d.pages[0].layers[0]; + assert!(matches!(layer.objects.as_slice(), [Object::Shape(_)]), "{:?}", layer.objects); + assert!(layer.guides.is_empty() && d.guides.is_empty(), "{:?}", layer.guides); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // The same past the limit while looking for an object's `loda`, `flgs` or `trfd` after 1,000 + // chunks. + let synth::Node::List(form, own) = clip_rect(v, 10.0, &[], [0.0, 0.0]) else { panic!("an object is a list") }; + let [flgs, lgob @ synth::Node::List(lgob_form, kids)] = own.as_slice() else { panic!("{own:?}") }; + let [loda, transform @ synth::Node::List(trfl, trfd)] = kids.as_slice() else { panic!("{kids:?}") }; + let pads = || (0..1000).map(|_| chunk(b"pad ", vec![])); + let loda_late = synth::Node::List( + form, + vec![flgs.clone(), synth::Node::List(*lgob_form, std::iter::once(transform.clone()).chain(pads()).chain([loda.clone()]).collect())], + ); + let flags_late = synth::Node::List(form, std::iter::once(lgob.clone()).chain(pads()).chain([flgs.clone()]).collect()); + let trfd_late = synth::Node::List( + form, + vec![flgs.clone(), synth::Node::List(*lgob_form, vec![loda.clone(), synth::Node::List(*trfl, pads().chain(trfd.iter().cloned()).collect())])], + ); + for late in [loda_late, flags_late, trfd_late] { + let file = clip_drawing(1100, vec![(0x77, vec![late])], vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])]); + let d = read(&file, Limits { clipped_chunks: 500, ..Limits::default() }).unwrap(); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)]), "{:?}", d.pages[0].layers[0].objects); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + } + // Chunks after the ones an object keeps for itself are not looked through. + let synth::Node::List(form, own) = clip_rect(v, 10.0, &[], [0.0, 0.0]) else { panic!("an object is a list") }; + let rect = synth::Node::List(form, own.into_iter().chain((0..1000).map(|_| chunk(b"pad ", vec![]))).collect()); + let containers: Vec = (0..20).map(|_| clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])).collect(); + let file = clip_drawing(1100, vec![(0x77, vec![rect])], containers); + let d = read(&file, Limits { clipped_chunks: 3 + 1 + 5 + 20 * 2, ..Limits::default() }).unwrap(); + assert_eq!(count(&d), 20); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); +} + +/// A container, fill, outline or style argument too short for the id it names is damage: the +/// shape comes in as a plain shape without that id. +#[test] +fn an_id_argument_cut_short_is_damage() { + for version in [700, 1100, 1600] { + let v = V(version); + let group = vec![(0x77, vec![clip_rect(v, 10.0, &[], [0.0, 0.0])])]; + let container = clip_rect(v, 40.0, &[(8005, vec![0x77, 0, 0])], [0.0, 0.0]); + let d = read(&clip_drawing(version, group, vec![container]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)]), "{version}: {:?}", d.pages[0].layers[0].objects); + assert_eq!(d.warnings, vec![Warning::Damaged], "{version}"); + for kind in [20, 10, 200] { + let short = synth::object(v, 1, &[(kind, vec![1, 0]), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = read(&clip_drawing(version, vec![], vec![short]), Limits::default()).unwrap_or_else(|e| panic!("{version} {kind}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() == 1 && s[0].fill.is_none() && s[0].outline.is_none(), "{version} {kind}"); + assert_eq!(d.warnings, vec![Warning::Damaged], "{version} {kind}"); + } + } +} + +/// A fill or outline id that no record has is damage: the shape comes in without that paint. Id 0 +/// without a record is no paint. +#[test] +fn a_fill_or_outline_without_its_record_is_damage() { + for version in [700, 1100, 1600] { + let v = V(version); + for kind in [20, 10] { + for (id, want) in [(9u32, vec![Warning::Damaged]), (0, vec![])] { + let object = synth::object(v, 1, &[(kind, id.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = + read(&clip_drawing(version, vec![], vec![object]), Limits::default()).unwrap_or_else(|e| panic!("{version} {kind} {id}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() == 1 && s[0].fill.is_none() && s[0].outline.is_none(), "{version} {kind} {id}"); + assert_eq!(d.warnings, want, "{version} {kind} {id}"); + } + } + } +} + +/// An object with a lens or transparency (argument 8000) comes in opaque, with the lenses +/// warning; one without the argument gives no warning. +#[test] +fn lenses_and_transparency_are_named_in_the_warnings() { + for (version, lens) in [(1000, [1u8, 0, 0, 0].to_vec()), (1200, [5, 0, 0, 0].to_vec()), (1500, [0x14, 5, 0, 0, 0x75, 0, 0, 0, 5].to_vec())] { + let v = V(version); + let plain = clip_rect(v, 10.0, &[], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![], vec![plain]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + let see_through = clip_rect(v, 10.0, &[(8000, lens)], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![], vec![see_through]), Limits::default()).unwrap(); + assert_eq!(shapes(&d.pages[0].layers[0].objects).len(), 1, "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version}"); + } +} + +/// From version 13 a uniform transparency (a 117-byte record of version 1300 in argument 8000) +/// gives the shape its opacity and blend mode, records of other versions before it skipped. A +/// lens record, a value outside 0 to 100, a merge mode without a blend mode, and the record in an +/// earlier version are not applied: the shape stays opaque, with the lenses warning. +#[test] +fn a_uniform_transparency_from_version_13_applies() { + let record = |since: u32, body: Vec| [since.to_le_bytes().to_vec(), (body.len() as u32).to_le_bytes().to_vec(), body].concat(); + for version in [1300, 1500, 1600, 2000] { + let v = V(version); + let read_with = |arg: Vec| { + let d = read(&clip_drawing(version, vec![], vec![clip_rect(v, 10.0, &[(8000, arg)], [0.0, 0.0])]), Limits::default()) + .unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects)[0]; + ((s.opacity, s.blend), d.warnings) + }; + for (percent, merge, want) in [(25.0, 0, Blend::Normal), (0.0, 9, Blend::Multiply), (100.0, 28, Blend::Screen), (60.0, 36, Blend::Exclusion)] + { + let opacity = (1.0 - percent / 100.0) as f32; + assert_eq!(read_with(synth::transparency(percent, merge).1), ((opacity, want), vec![]), "{version} {percent} {merge}"); + } + // A record of a later version comes first. + let later = [record(1600, vec![0; 20]), synth::transparency(25.0, 0).1].concat(); + assert_eq!(read_with(later), ((0.75, Blend::Normal), vec![]), "{version}"); + let opaque = ((1.0, Blend::Normal), vec![Warning::Lenses]); + assert_eq!(read_with(record(1300, vec![0; 84])), opaque, "{version}: a lens"); + for bad in [150.0, -1.0, f64::NAN] { + assert_eq!(read_with(synth::transparency(bad, 0).1), opaque, "{version} {bad}"); + } + for merge in [1, 2, 3, 6, 7, 8, 10, 13, 18, 19, 20, 27, 37, 255] { + assert_eq!(read_with(synth::transparency(25.0, merge).1), opaque, "{version} {merge}"); + } + assert_eq!(read_with(vec![]), opaque, "{version}: empty"); + } + let d = + read(&clip_drawing(1200, vec![], vec![clip_rect(V(1200), 10.0, &[synth::transparency(25.0, 0)], [0.0, 0.0])]), Limits::default()).unwrap(); + assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].opacity, 1.0); + assert_eq!(d.warnings, vec![Warning::Lenses]); +} + +/// Bit 0x01 of byte 1 of a layer's, group's or object's flags hides it and bit 0x10 of byte 0 +/// locks it, in every version; a group left ungrouped at the object limit passes its flags to its +/// objects. +#[test] +fn flags_hide_and_lock_layers_groups_and_objects() { + for version in [300, 700, 1100, 1300, 1600] { + let v = V(version); + let rect = |flags: [u8; 4]| synth::flagged(synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None), flags); + let group = |flags: [u8; 4], objects: Vec| { + let mut kids = vec![chunk(b"flgs", flags.to_vec())]; + kids.extend(objects); + list(b"grp ", kids) + }; + let objects = vec![ + rect([0, 0, 0, 8]), + rect([0, 1, 0, 8]), + rect([0x10, 0, 0, 8]), + rect([0x10, 1, 0, 8]), + group([0x10, 1, 0, 0x10], vec![rect([0, 0, 0, 8])]), + ]; + let layers = + vec![synth::layer(v, [0, 0, 0, 0x98], "Shown", objects), synth::layer(v, [0x10, 1, 0, 0x98], "Hidden", vec![rect([0, 0, 0, 8])])]; + let file = synth::file_of(version, vec![synth::page(false, layers)]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let [shown, hidden] = d.pages[0].layers.as_slice() else { panic!("{version}: {:?}", d.pages[0].layers) }; + assert_eq!(shown.flags, Flags::default(), "{version}"); + assert_eq!(hidden.flags, Flags { hidden: true, locked: true }, "{version}"); + let f = |hidden: bool, locked: bool| Flags { hidden, locked }; + let own: Vec = shown + .objects + .iter() + .map(|o| match o { + Object::Shape(s) => s.flags, + Object::Group { flags, .. } => *flags, + Object::Clip { container, .. } => container.flags, + }) + .collect(); + assert_eq!(own, [f(false, false), f(true, false), f(false, true), f(true, true), f(true, true)], "{version}"); + assert!( + matches!(&shown.objects[4], Object::Group { objects, .. } if matches!(&objects[0], Object::Shape(s) if s.flags == Flags::default())), + "{version}" + ); + assert!(d.warnings.contains(&Warning::UnsupportedObjects) || d.warnings.is_empty(), "{version}: {:?}", d.warnings); + // Past the object limit the group's rectangle comes in ungrouped, hidden and locked. + let d = read(&file, Limits { objects: 5, ..Limits::default() }).unwrap_or_else(|e| panic!("{version}: {e}")); + let last = d.pages[0].layers[0].objects.last(); + assert!(matches!(last, Some(Object::Shape(s)) if s.flags == f(true, true)), "{version}: {last:?}"); + } +} + +/// A guideline is hidden when its own object, a group around it or its layer is. +#[test] +fn hidden_guidelines_say_so() { + for version in [700, 1300, 1600] { + let v = V(version); + let guide = |flags: [u8; 4]| { + let mut arg = vec![0; 12]; + arg.extend(90_000_000i32.to_le_bytes()); + arg.extend([v.coord(36.0), v.coord(0.0)].concat()); + synth::flagged(synth::object(v, 0x16, &[(16000, arg)], None), flags) + }; + let group = list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), guide([0, 0, 0, 8])]); + let layers = vec![ + synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![guide([0, 0, 0, 8]), guide([0, 1, 0, 8]), group]), + synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![guide([0, 0, 0, 8])]), + ]; + let d = read(&synth::file_of(version, vec![synth::page(false, layers)]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let hidden: Vec> = d.pages[0].layers.iter().map(|l| l.guides.iter().map(|g| g.hidden).collect()).collect(); + assert_eq!(hidden, [vec![false, true, true], vec![true]], "{version}"); + } +} + +/// Byte 0 of argument 14001 other than 0 fills the shape nonzero; 0, or no argument, fills it +/// even-odd; an argument without its byte is damage. +#[test] +fn a_winding_flag_fills_nonzero() { + for version in [300, 700, 1200, 1600] { + let v = V(version); + let read_with = |extra: &[(u32, Vec)]| { + let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))]; + args.extend(extra.iter().cloned()); + let file = synth::file_of( + version, + vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])], + ); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].nonzero, d.warnings) + }; + assert_eq!(read_with(&[(14001, vec![1, 0, 0, 0])]), (true, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![2])]), (true, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![0, 0, 0, 0])]), (false, vec![]), "{version}"); + assert_eq!(read_with(&[]), (false, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![])]), (false, vec![Warning::Damaged]), "{version}"); + } +} + +/// A `cdr8` form type makes the file the 8.01 variant whatever its `vrsn` chunk names: its style +/// table is read with the 8.01 layout. +#[test] +fn a_cdr8_file_whose_version_chunk_names_800_reads_as_801() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for named in [800u16, 900, 1300] { + let table = synth::stlt(V(801), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + let mut file = graphic_style_drawing(801, table); + file[8..12].copy_from_slice(b"cdr8"); + let at = file.windows(4).position(|w| w == b"vrsn").unwrap() + 8; + assert_eq!(&file[at..at + 2], &801u16.to_le_bytes()); + file[at..at + 2].copy_from_slice(&named.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{named}: {e}")); + assert_eq!(d.version, 801, "{named}"); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{named}"); + assert!(d.warnings.is_empty(), "{named}: {:?}", d.warnings); + } +} + +/// Before version 6 an object names its style in 2 bytes, which is not damage; an argument too +/// short for them is. +#[test] +fn a_style_id_before_version_6_is_two_bytes() { + for version in [400, 500] { + let v = V(version); + let read_with = |style: Vec| { + let object = synth::object(v, 1, &[(200, style), (30, v.rect(10.0, 10.0, 0.0))], None); + let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects).len(), d.warnings) + }; + assert_eq!(read_with(vec![0x10, 0]), (1, vec![]), "{version}"); + assert_eq!(read_with(vec![0x10]), (1, vec![Warning::Damaged]), "{version}"); + } +} + +/// A hidden or locked group of `LIST clpt` hides or locks the objects a container clips from it. +#[test] +fn a_clipped_groups_flags_reach_its_objects() { + for version in [700, 1300, 1600] { + let v = V(version); + let group = list( + b"grp ", + vec![chunk(b"flgs", vec![0x10, 1, 0x80, 0x10]), chunk(b"spnd", 0x77u32.to_le_bytes().to_vec()), clip_rect(v, 10.0, &[], [0.0, 0.0])], + ); + let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"clpt", vec![group])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])])]); + let d = read(&synth::file_of(version, vec![doc, page]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let [Object::Clip { container, objects }] = d.pages[0].layers[0].objects.as_slice() else { + panic!("{version}: {:?}", d.pages[0].layers[0].objects) + }; + assert_eq!(container.flags, Flags::default(), "{version}"); + assert!(matches!(objects.as_slice(), [Object::Shape(s)] if s.flags == Flags { hidden: true, locked: true }), "{version}: {objects:?}"); + } +} + +/// Before version 6 a clipped group's `spnd` id is 2 bytes. +#[test] +fn a_clipped_group_id_before_version_6_is_two_bytes() { + for version in [400, 500] { + let v = V(version); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let clpt = list(b"clpt", vec![list(b"grp ", vec![chunk(b"spnd", vec![0x77, 0]), rect(10.0, vec![])])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(0x77)])])]); + let d = read(&synth::file_of(version, vec![list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), clpt]), page]), Limits::default()) + .unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + assert!(matches!(objects.as_slice(), [Object::Clip { objects, .. }] if objects.len() == 1), "{version}: {objects:?}"); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } +} + +/// A `trfd` entry ends at the next offset: one too short for its matrix makes the transform +/// damage and leaves the shape in place, even when the bytes after it would read as a matrix. A +/// table that stops before the last entry's end offset leaves that entry the rest of the record. +#[test] +fn a_transform_entry_ends_at_the_next_offset() { + for version in [400, 1100, 1300, 1600] { + let v = V(version); + let w = if version < 600 { 2 } else { 4 }; + let moved = [1.0, 0.0, 0.0, 1.0, 72.0, 0.0]; + let object = |trfd: Vec| { + let own = vec![chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), list(b"trfl", vec![chunk(b"trfd", trfd)])]; + list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 8]), list(b"lgob", own)]) + }; + let read_with = |trfd: Vec| { + let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object(trfd)])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4], d.warnings) + }; + let whole = v.trfd(&[moved]); + assert!((read_with(whole.clone()).0 - 72.0).abs() < 0.01, "{version}"); + // The end offset, right after the first, made 4 bytes past the entry's start. + let mut short = whole.clone(); + let start = if w == 2 { + usize::from(u16::from_le_bytes([short[3 * w], short[3 * w + 1]])) + } else { + u32::from_le_bytes(short[12..16].try_into().unwrap()) as usize + }; + short[4 * w..5 * w].copy_from_slice(&v.word(start + 4)); + assert_eq!(read_with(short), (0.0, vec![Warning::Damaged]), "{version}"); + // The entry first, then a table of its start alone at the record's end. + let entry = whole[5 * w..].to_vec(); + let at = 3 * w + entry.len(); + let mut end = [v.word(at + w), v.word(1), v.word(at)].concat(); + end.extend(entry); + end.extend(v.word(3 * w)); + let (x, warnings) = read_with(end); + assert!((x - 72.0).abs() < 0.01 && warnings.is_empty(), "{version}: {x} {warnings:?}"); + } +} + +/// From version 13 an outline's record of type 2 that names a library color gives the outline +/// that color; one without a name leaves the fixed color field. +#[test] +fn an_outline_takes_a_named_library_color_from_its_property_list() { + for version in [1300, 1500, 1600] { + let v = V(version); + let read_with = |props: Vec| { + let mut outl = v.outline(4, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &synth::color(2, [0, 0, 0, 100]), &[]); + let mut record = 2u32.to_le_bytes().to_vec(); + record.extend((props.len() as u32).to_le_bytes()); + record.extend(props); + outl.splice(4..4, record); + let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"otlt", vec![chunk(b"outl", outl)])]); + let object = synth::object(v, 1, &[(10, 4u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let file = synth::file_of(version, vec![doc, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].outline.as_ref().map(|o| o.color.clone()), d.warnings) + }; + let named = synth::properties(&synth::color(5, [0, 0, 255, 0]), Some("Sky Blue")); + assert_eq!(read_with(named), (Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), vec![]), "{version}"); + let plain = synth::properties(&synth::color(5, [0, 0, 255, 0]), None); + assert_eq!(read_with(plain), (Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0])), vec![]), "{version}"); + } +} + +#[test] +fn linked_groups_are_left_out_with_a_warning() { + let v = V(1100); + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![list(b"lnkg", vec![rect])])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty()); + assert!(d.warnings.contains(&Warning::UnsupportedObjects)); +} + +#[test] +fn a_file_cut_short_keeps_what_it_holds() { + let full = synth::sample(900, false); + let cut = &full[..full.len() - 40]; + let d = read(cut, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + // The last page is cut inside its layer: the lists that hold the cut keep their whole + // children, so the rectangle, ellipse and curve before the cut are read. + assert_eq!(d.pages.len(), 1); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() >= 3, "{}", s.len()); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && matches!(s[1].geometry, Geometry::Ellipse { .. })); +} + +#[test] +fn a_riff_length_shorter_than_the_form_type_is_damage() { + for declared in 0u32..4 { + let mut file = synth::sample(900, false); + file[4..8].copy_from_slice(&declared.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{declared}"); + check_shapes(&d, 900); + } +} + +#[test] +fn a_zip_bomb_stops_at_the_inflate_limit() { + let v = V(1100); + let big = chunk(b"junk", vec![0; 4 << 20]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), synth::cmpr(&[big, synth::mcfg(v, 10.0, 10.0)])]); + assert!(file.len() < 64 << 10); + let limits = Limits { inflated: 1 << 20, ..Limits::default() }; + assert_eq!(read(&file, limits), Err(Error::Limit("inflated size"))); +} + +/// What a compressed stream inflates before it fails counts toward the inflate limit, so that +/// streams failing at their checksum can't each inflate up to the limit. +#[test] +fn bytes_inflated_by_a_failing_stream_count_toward_the_limit() { + let failing = || { + let mut cmpr = synth::cmpr(&[chunk(b"junk", vec![0; 600 << 10])]); + if let synth::Node::Chunk(_, body) = &mut cmpr { + // The last byte of the first block's zlib stream is part of its checksum. + let first = u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize; + body[4 + 16 + first - 1] ^= 0xff; + } + cmpr + }; + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), failing(), failing()]); + let one = + read(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), failing()]), Limits { inflated: 1 << 20, ..Limits::default() }); + assert!(one.is_ok_and(|d| d.warnings == vec![Warning::Damaged])); + assert_eq!(read(&file, Limits { inflated: 1 << 20, ..Limits::default() }), Err(Error::Limit("inflated size"))); +} + +#[test] +fn a_million_empty_chunks_stop_at_the_chunk_limit() { + let kids: Vec<_> = (0..5000).map(|_| chunk(b"junk", vec![])).collect(); + let file = synth::riff(1100, &[list(b"doc ", kids)]); + let limits = Limits { chunks: 1000, ..Limits::default() }; + assert_eq!(read(&file, limits), Err(Error::Limit("chunk count"))); + assert!(read(&file, Limits::default()).is_ok()); +} + +#[test] +fn deep_nesting_is_left_out_with_a_warning() { + let v = V(1100); + let mut inner = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + for _ in 0..300 { + inner = list(b"grp ", vec![inner]); + } + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![inner])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn a_size_pool_index_out_of_range_is_damage() { + // A compressed stream whose one chunk names pool entry 7 of a pool of one. + let mut cmpr = synth::cmpr(&[chunk(b"mcfg", vec![0; 8])]); + if let synth::Node::Chunk(_, body) = &mut cmpr { + // Rebuild the stream with a bad index: the pool keeps its one size. + let mut stream = b"mcfg".to_vec(); + stream.extend(7u32.to_le_bytes()); + stream.extend([0; 8]); + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut e, &stream).unwrap(); + let z = e.finish().unwrap(); + let pool_block = body[4 + 16 + u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize..].to_vec(); + let mut b = b"cmpr".to_vec(); + b.extend(((z.len() + 8) as u32).to_le_bytes()); + b.extend((stream.len() as u32).to_le_bytes()); + b.extend(body[12..20].to_vec()); + b.extend(b"CPng\x01\x00\x04\x00"); + b.extend(z); + b.extend(pool_block); + *body = b; + } + let d = read(&synth::riff(1100, &[cmpr]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn backward_and_huge_loda_offsets_do_not_panic() { + let v = V(1100); + let mut loda = v.loda(3, &[(30, v.points(&[(0.0, 0.0, 0), (1.0, 1.0, 0x40)]))]); + // The offsets table now points before the header and far past the end. + let at = u32::from_le_bytes(loda[8..12].try_into().unwrap()) as usize; + loda[at..at + 4].copy_from_slice(&40u32.to_le_bytes()); + loda[at + 4..at + 8].copy_from_slice(&2u32.to_le_bytes()); + let obj = list(b"obj ", vec![chunk(b"loda", loda)]); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![obj])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +#[test] +fn outlines_flagged_none_and_dashes_read() { + let v = V(1300); + let black = synth::color(2, [0, 0, 0, 100]); + let dashed = v.outline(9, synth::Pen { line_type: 4, width: 1.0, cap: 2, join: 2 }, &black, &[3, 1]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40)]))]; + let file = synth::riff( + 1300, + &[ + chunk(b"vrsn", 1300u16.to_le_bytes().to_vec()), + list(b"otlt", vec![chunk(b"outl", dashed)]), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &style, None)])]), + ], + ); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!(o.dashes, vec![3.0, 1.0]); + assert_eq!((o.cap, o.join), (Cap::Square, craft_cdr::model::Join::Bevel)); +} + +/// A curve or polygon left out at the coordinate limit gives the limit warning, not the damage +/// warning. +#[test] +fn shapes_past_the_coordinate_limit_are_not_damage() { + let v = V(1100); + let curve = synth::object(v, 3, &[(30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]))], None); + let side = synth::POLYGON_SIDE; + let mut sides = vec![0; 4]; + sides.extend(5u32.to_le_bytes()); + sides.extend([0; 8]); + sides.extend(0.05f64.to_le_bytes()); + sides.extend(0.05f64.to_le_bytes()); + sides.extend([v.coord(0.0), v.coord(0.0)].concat()); + let base = v.points(&[(0.0, side, 0x0C), (side * 0.587, side * 0.809, 0x44)]); + let polygon = synth::object(v, 0x14, &[(30, base.clone()), (11000, sides)], None); + for (objects, limit) in [(vec![curve], 2), (vec![polygon], 4)] { + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)])]); + let d = read(&file, Limits { coordinates: limit, ..Limits::default() }).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty()); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + } + // A polygon without its sides is damage, past the limit too. + let sideless = synth::object(v, 0x14, &[(30, base)], None); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![sideless])])]); + let d = read(&file, Limits { coordinates: 1, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +/// Dashes stored in an outline whose line type doesn't mark it dashed (bit 2) are not drawn: the +/// outline is solid. +#[test] +fn dashes_are_drawn_only_when_the_line_type_marks_them() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1200, 1500] { + for (line_type, dashed) in [(2, false), (0x22, false), (0x42, false), (4, true), (0x24, true), (0x44, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 1.0, cap: 0, join: 0 }, &black, &[2, 1]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40)]))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!(o.dashes.is_empty(), !dashed, "{version} {line_type:#x}: {:?}", o.dashes); + } + } +} + +/// Bit 4 of the line type puts the outline behind the fill. +#[test] +fn outlines_flagged_behind_the_fill_say_so() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1300, 1600] { + for (line_type, behind) in [(2, false), (0x22, false), (0x12, true), (0x14, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 4.0, cap: 0, join: 0 }, &black, &[]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].outline.as_ref().map(|o| o.behind_fill), Some(behind), "{version} {line_type:#x}"); + } + } +} + +/// Bit 5 of the line type scales the outline with the shape. +#[test] +fn outlines_flagged_to_scale_with_the_shape_say_so() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1300, 1600] { + for (line_type, scale_with) in [(2, false), (0x22, true), (0x12, false), (0x26, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 4.0, cap: 0, join: 0 }, &black, &[]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].outline.as_ref().map(|o| o.scale_with), Some(scale_with), "{version} {line_type:#x}"); + } + } +} + +#[test] +fn library_colors_from_version_13_keep_their_names_and_tints() { + // A model 21 color (blue, green, red, tint) shown at 50 %, and its library name. + let shown = synth::color(21, [255, 191, 128, 50]); + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(shown); + props.push(8); + let name: Vec = "Sky Blue".encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + props.extend((16 + 4 + name.len() as u32).to_le_bytes()); + props.extend([0; 16]); + props.extend(8u32.to_le_bytes()); + props.extend(name); + props.extend([0, 0, 0, 0, 0]); + let mut solid = 1300u32.to_le_bytes().to_vec(); + solid.extend((props.len() as u32).to_le_bytes()); + solid.extend(props); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(solid); + let mut fill = 4u32.to_le_bytes().to_vec(); + // A record of a later layout first, which the reader steps over. + fill.extend(2400u32.to_le_bytes()); + fill.extend(16u32.to_le_bytes()); + fill.extend([0; 16]); + fill.extend(1300u32.to_le_bytes()); + fill.extend((body.len() as u32).to_le_bytes()); + fill.extend(body); + // The same records in a plain file of version 13 and the packages of later versions. + for version in [1300, 1400, 1700, 2700] { + let v = V(version); + let style = vec![(20, 4u32.to_le_bytes().to_vec()), (30, v.rect(1.0, 1.0, 0.0))]; + let body = [ + chunk(b"vrsn", version.to_le_bytes().to_vec()), + list(b"filt", vec![chunk(b"fild", fill.clone())]), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]), + ]; + let file = match version { + ..1400 => synth::riff(version, &body), + 1400..1600 => synth::package14(synth::riff(version, &body), true), + _ => synth::package16(version, &body, true, &[]), + }; + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Some(Color::Spot { name, tint, look: Some(look) }) = &s[0].fill else { panic!("{version}: {:?}", s[0].fill) }; + assert_eq!((name.as_str(), *tint), ("Sky Blue", 0.5)); + // 128/255 shown at half strength comes from about 1/255 at full strength. + assert!(look[0] < 0.01 && (look[2] - 1.0).abs() < 1e-6, "{version}: {look:?}"); + } +} + +/// One rectangle of version `v` that uses fill `fill` and outline `outline` (0: none). +fn styled_rect(v: V, fill: u32, outline: u32) -> synth::Node { + let mut args = vec![(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())]; + if fill != 0 { + args.push((20, fill.to_le_bytes().to_vec())); + } + if outline != 0 { + args.push((10, outline.to_le_bytes().to_vec())); + } + synth::object(v, 1, &args, None) +} + +/// A drawing of version `v` with `styles` in its `doc` list and `objects` on one page. +fn styled_drawing(v: V, styles: Vec, objects: Vec) -> Vec { + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::riff(v.0, &[chunk(b"vrsn", v.0.to_le_bytes().to_vec()), list(b"doc ", styles), page]) +} + +/// An outline's dashes count toward the read's dashes for every shape that uses it: one outline +/// of 65,535 dashes on 260 shapes would copy 17 million dashes, past the default limit. +#[test] +fn a_shared_dashed_outline_counts_its_dashes_for_every_shape() { + let v = V(1300); + let pen = synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 }; + let outl = |dashes: &[u16]| list(b"otlt", vec![chunk(b"outl", v.outline(9, pen, &synth::color(2, [0, 0, 0, 100]), dashes))]); + let file = styled_drawing(v, vec![outl(&[2, 1].repeat(10))], (0..20).map(|_| styled_rect(v, 0, 9)).collect()); + let d = read(&file, Limits { dashes: 100, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 20); + let dashed = s.iter().filter(|s| s.outline.as_ref().is_some_and(|o| o.dashes.len() == 20)).count(); + assert_eq!(dashed, 5, "100 dashes hold five outlines of 20"); + assert!(s.iter().all(|s| s.outline.as_ref().is_some_and(|o| o.dashes.is_empty() || o.dashes.len() == 20))); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); + // An outline with more dashes than the limit is solid, not cut short. + let file = styled_drawing(v, vec![outl(&[2, 1])], vec![styled_rect(v, 0, 9)]); + let d = read(&file, Limits { dashes: 1, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].outline.as_ref().is_some_and(|o| o.dashes.is_empty()), "{:?}", s[0].outline); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // At the default limit. + let file = styled_drawing(v, vec![outl(&[1; 65_535])], (0..260).map(|_| styled_rect(v, 0, 9)).collect()); + assert!(file.len() < 256 << 10); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let total: usize = s.iter().filter_map(|s| s.outline.as_ref()).map(|o| o.dashes.len()).sum(); + assert!(total <= Limits::default().dashes, "{total}"); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); +} + +/// A library color's name is copied for every shape that uses it: a long one keeps its first 256 +/// units and a hash of the whole name. +#[test] +fn a_library_color_keeps_the_first_256_units_of_its_name() { + let v = V(1300); + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(synth::color(21, [255, 191, 128, 100])); + props.push(8); + let name: Vec = "N".repeat(10_000).encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + props.extend((16 + 4 + name.len() as u32).to_le_bytes()); + props.extend([0; 16]); + props.extend(10_000u32.to_le_bytes()); + props.extend(name); + props.extend([0, 0, 0, 0, 0]); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(1300u32.to_le_bytes()); + body.extend((props.len() as u32).to_le_bytes()); + body.extend(props); + let mut fill = 4u32.to_le_bytes().to_vec(); + fill.extend(1300u32.to_le_bytes()); + fill.extend((body.len() as u32).to_le_bytes()); + fill.extend(body); + let d = read(&styled_drawing(v, vec![list(b"filt", vec![chunk(b"fild", fill)])], vec![styled_rect(v, 4, 0)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Some(Color::Spot { name, .. }) = &s[0].fill else { panic!("{:?}", s[0].fill) }; + assert_eq!(name.chars().count(), 256 + 17, "{name}"); + assert!(name.starts_with(&"N".repeat(256)), "{name}"); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); +} + +/// A transform or a uniform fill's color that is there but can't be read is damage: the shape +/// stays, without its transform or its fill, and the warnings say so. +#[test] +fn unreadable_transforms_and_fill_colors_are_damage() { + let v = V(1100); + let rect = [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat(); + let obj = list(b"obj ", vec![chunk(b"loda", v.loda(1, &[(30, rect)])), list(b"trfl", vec![chunk(b"trfd", vec![1, 2])])]); + let d = read(&styled_drawing(v, vec![], vec![obj]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!((s.len(), s[0].matrix), (1, craft_cdr::model::Matrix::IDENTITY)); + assert!(d.warnings.contains(&Warning::Damaged), "trfd: {:?}", d.warnings); + // A uniform fill cut off in its color record, before version 13 and from it. + for v in [V(1100), V(1300)] { + let mut fill = v.fill(4, &synth::color(2, [0, 100, 0, 0])); + fill.truncate(fill.len() - 10); + let d = read(&styled_drawing(v, vec![list(b"filt", vec![chunk(b"fild", fill)])], vec![styled_rect(v, 4, 0)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, None, "{}", v.0); + assert!(d.warnings.contains(&Warning::Damaged), "fill {}: {:?}", v.0, d.warnings); + } +} + +/// The inflate limit may be as large as `usize` holds. +#[test] +fn the_largest_inflate_limit_reads_compressed_lists() { + let d = read(&synth::sample(1100, true), Limits { inflated: usize::MAX, ..Limits::default() }).unwrap(); + check_shapes(&d, 1100); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { + let mut b = b"RIFF".to_vec(); + b.extend(bytes); + let _ = read(&b, Limits::default()); + let _ = preview(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_samples(version in prop::sample::select(vec![300u16, 400, 500, 700, 900, 1100, 1300]), compress: bool, edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = synth::sample(version, compress && version >= 700); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read(&b, Limits::default()); + let _ = preview(&b, Limits::default()); + } + + #[test] + fn never_panics_on_garbage_after_a_wl_header(marker in prop::sample::select(vec![b'e', b'l', b'm']), bytes in prop::collection::vec(any::(), 0..2048)) { + // Offsets that fit the file, so the garbage is walked as records. + let mut b = vec![b'W', b'L', marker, 0]; + b.extend(28u32.to_le_bytes()); + b.extend(28u32.to_le_bytes()); + b.extend((28 + bytes.len() as u32).to_le_bytes()); + b.extend([0; 12]); + b.extend(bytes); + prop_assert!(craft_cdr::is_cdr(&b)); + let _ = read(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_wl_files(marker in prop::sample::select(vec![b'e', b'l', b'm']), cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = synth::wl_sample(marker); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read(&b, Limits::default()); + let _ = read(&b[..cut % (n + 1)], Limits::default()); + } + + #[test] + fn never_panics_on_mutated_packages(version in prop::sample::select(vec![1400u16, 1500, 1700, 2700]), edits in prop::collection::vec((any::(), any::(), any::()), 1..24)) { + // The members are edited before they are zipped, so that the edits reach the chunks and + // redirect records rather than stop at the CRC-32. + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(version)); + let mut members = if version < 1600 { + vec![synth::Member { name: "content/riffData.cdr".into(), data: synth::sample(version, false), deflate: false }] + } else { + synth::package16_members(version, &body, false, &[]) + }; + for (m, at, v) in edits { + let k = m % members.len(); + let data = &mut members[k].data; + if !data.is_empty() { + let n = data.len(); + data[at % n] = v; + } + } + let zip = synth::zip(&members, b""); + let _ = read(&zip, Limits::default()); + // The package has no picture member, and `preview` does not read the damaged drawing. + prop_assert_eq!(preview(&zip, Limits::default()), Ok(None)); + } + + #[test] + fn preview_never_panics_on_mutated_pictures(version in prop::sample::select(vec![700u16, 1100, 1300, 1500, 1700]), deflate: bool, zipped: bool, edits in prop::collection::vec((any::(), any::()), 1..24)) { + let bitmap = disp_body(5, 3, 8); + let mut b = if version < 1400 { + // A compressed list before the `DISP` chunk, which the walk passes over. + let mut content = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + content.push(synth::cmpr(&synth::sample_content(version))); + content.push(chunk(b"DISP", bitmap)); + synth::riff(version, &content) + } else { + let (name, picture) = if version < 1700 { + ("metadata/thumbnails/thumbnail.bmp", [b"BM".as_slice(), &bitmap].concat()) + } else { + ("previews/thumbnail.png", [b"\x89PNG\r\n\x1a\n".as_slice(), &bitmap].concat()) + }; + let mut picture = synth::Member { name: name.into(), data: picture, deflate }; + // Edits to the member before it is zipped reach past its CRC-32. + if !zipped { + let n = picture.data.len(); + for &(at, v) in &edits { + picture.data[at % n] = v; + } + } + if version < 1600 { + synth::zip(&[synth::Member { name: "content/riffData.cdr".into(), data: synth::sample(version, false), deflate }, picture], b"") + } else { + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(version)); + synth::package16(version, &body, deflate, &[picture]) + } + }; + if zipped || version < 1400 { + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + } + let _ = preview(&b, Limits::default()); + } +} + +/// A `DISP` body: 4 bytes, a 40-byte bitmap info header for `bits` per pixel, a full color table +/// and the rows. +fn disp_body(width: u32, rows: u32, bits: u16) -> Vec { + let mut b = 8u32.to_le_bytes().to_vec(); + b.extend(40u32.to_le_bytes()); + b.extend(width.to_le_bytes()); + b.extend(rows.to_le_bytes()); + b.extend(1u16.to_le_bytes()); + b.extend(bits.to_le_bytes()); + b.extend([0; 24]); + b.extend((0..(1u32 << bits) * 4).map(|i| i as u8)); + let stride = (width * u32::from(bits)).div_ceil(32) * 4; + b.extend((0..stride * rows).map(|i| (i * 3) as u8)); + b +} diff --git a/crates/cms/tests/main.rs b/crates/cms/tests/main.rs index 8c1e80f08d..1087e4d9e3 100644 --- a/crates/cms/tests/main.rs +++ b/crates/cms/tests/main.rs @@ -4,6 +4,7 @@ mod bench; mod cms; mod constructors; mod fogra39; +mod gpu_matrix_shaper; mod named; mod profile_id; mod regen; diff --git a/crates/color-ui/Cargo.toml b/crates/color-ui/Cargo.toml index d6cbb1c107..ca8ee89afe 100644 --- a/crates/color-ui/Cargo.toml +++ b/crates/color-ui/Cargo.toml @@ -42,6 +42,7 @@ serde_json = { workspace = true, optional = true } [dev-dependencies] craft-ui = { workspace = true, features = ["suite"] } egui = { workspace = true } +serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] egui_kittest = { version = "0.37", features = ["wgpu"] } diff --git a/crates/color-ui/src/display.rs b/crates/color-ui/src/display.rs index bf891985cb..aed937fe38 100644 --- a/crates/color-ui/src/display.rs +++ b/crates/color-ui/src/display.rs @@ -23,6 +23,9 @@ pub type DisplayId = Option; /// Bytes per conversion chunk of [`DisplayTransform::apply_rgba8`] (a whole number of pixels). const CHUNK_BYTES: usize = 4 * 65536; +/// Bytes of the stack scratch of [`DisplayTransform::apply_premultiplied_rgba8`] (4096 whole pixels). +const SCRATCH_BYTES: usize = 4 * 4096; + /// Most cached transforms before the cache is cleared. const MAX_TRANSFORMS: usize = 32; @@ -67,6 +70,11 @@ fn usable_monitor(profile: Profile) -> Result, MonitorProblem> { Ok(Arc::new(profile)) } +/// `icc` parsed and validated as a monitor profile. +fn parse_monitor(icc: &[u8]) -> Result, MonitorProblem> { + Profile::parse(icc).map_err(|e| MonitorProblem::Unreadable { reason: e.to_string() }).and_then(usable_monitor) +} + fn srgb_entry(status: MonitorStatus) -> MonitorEntry { MonitorEntry { profile: Arc::new(Builtin::Srgb.profile().clone()), status } } @@ -135,6 +143,52 @@ impl DisplayTransform { } } } + + /// Premultiplied RGBA8 pixels converted in place through a fixed scratch of whole pixels: + /// alpha 0 is skipped, partial alpha is divided out and multiplied back, a failed chunk is + /// left as it was; nothing happens for the identity. + // new: the canvas frames hold premultiplied pixels; `display_profile::usable` shares the + // monitor check through `check_monitor`. + pub fn apply_premultiplied_rgba8(&self, pixels: &mut [u8]) { + let Some(t) = &self.transform else { return }; + let mut scratch = [0u8; SCRATCH_BYTES]; + for chunk in pixels.chunks_mut(SCRATCH_BYTES).map(|c| { + let n = c.len() / 4 * 4; + &mut c[..n] + }) { + let Some(src) = scratch.get_mut(..chunk.len()) else { continue }; + src.copy_from_slice(chunk); + for px in src.as_chunks_mut::<4>().0 { + let a = u32::from(px[3]); + if a != 0 && a != 255 { + for c in &mut px[..3] { + *c = ((u32::from(*c) * 255 + a / 2) / a).min(255) as u8; + } + } + } + // A failed conversion writes nothing (the buffers are checked first): the chunk stays. + if t.convert_u8(src, 4, chunk, 4, true).is_err() { + continue; + } + for (d, s) in chunk.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) { + let a = u32::from(d[3]); + if a == 0 { + *d = *s; + } else if a != 255 { + for c in &mut d[..3] { + *c = ((u32::from(*c) * a + 127) / 255) as u8; + } + } + } + } + } +} + +/// Whether `icc` is usable as a monitor profile: [`Profile::parse`] plus the monitor checks, a +/// parse error giving [`MonitorProblem::Unreadable`]. +// new: `display_profile::usable` in the app tries each profile source until one passes. +pub fn check_monitor(icc: &[u8]) -> Result<(), MonitorProblem> { + parse_monitor(icc).map(drop) } /// Why the monitor profile is what it is. @@ -216,18 +270,16 @@ impl DisplayCaches { pub fn set_monitor(&self, display: DisplayId, icc: Option<&[u8]>) { let entry = match icc { None => srgb_entry(MonitorStatus::NoProfile), - Some(bytes) => match Profile::parse(bytes) { - Ok(p) => match usable_monitor(p) { - Ok(profile) => MonitorEntry { profile, status: MonitorStatus::Detected }, - Err(reason) => srgb_entry(MonitorStatus::Unusable(reason)), - }, - Err(e) => { + Some(bytes) => match parse_monitor(bytes) { + Ok(profile) => MonitorEntry { profile, status: MonitorStatus::Detected }, + Err(problem @ MonitorProblem::Unreadable { .. }) => { if let std::collections::hash_map::Entry::Vacant(v) = lock(&self.monitors).entry(display) { - v.insert(srgb_entry(MonitorStatus::Unusable(MonitorProblem::Unreadable { reason: e.to_string() }))); + v.insert(srgb_entry(MonitorStatus::Unusable(problem))); lock(&self.transforms).clear(); } return; } + Err(problem) => srgb_entry(MonitorStatus::Unusable(problem)), }, }; lock(&self.monitors).insert(display, entry); @@ -310,6 +362,39 @@ pub(crate) mod tests { Arc::new(Builtin::Srgb.profile().clone()) } + /// Premultiplied conversion agrees with the straight one, leaves alpha and empty pixels alone. + #[trial] + fn a_premultiplied_conversion_matches_the_straight_one() { + let t = DisplayTransform::new(srgb(), p3()).unwrap(); + assert!(!t.is_identity()); + let colours = [[255u8, 0, 0], [200, 120, 40], [10, 220, 90]]; + for c in colours { + let mut straight = [c[0], c[1], c[2], 255]; + t.apply_rgba8(&mut straight); + let mut opaque = [c[0], c[1], c[2], 255]; + t.apply_premultiplied_rgba8(&mut opaque); + assert_eq!(opaque, straight, "opaque pixels agree"); + + let a = 128u32; + let mut half = [0, 1, 2].map(|i| ((u32::from(c[i]) * a + 127) / 255) as u8).to_vec(); + half.push(a as u8); + t.apply_premultiplied_rgba8(&mut half); + assert_eq!(half[3], a as u8, "alpha stays"); + for i in 0..3 { + let want = (u32::from(straight[i]) * a + 127) / 255; + assert!(want.abs_diff(u32::from(half[i])) <= 1, "channel {i}: {} vs {want}", half[i]); + } + } + let mut empty = [9u8, 8, 7, 0]; + t.apply_premultiplied_rgba8(&mut empty); + assert_eq!(empty, [9, 8, 7, 0]); + + let same = DisplayTransform::new(srgb(), srgb()).unwrap(); + let mut px = [50u8, 60, 70, 100, 1, 2, 3, 255]; + same.apply_premultiplied_rgba8(&mut px); + assert_eq!(px, [50, 60, 70, 100, 1, 2, 3, 255]); + } + /// Choosing another monitor profile changes the signature and drops the cached transform. #[trial] fn choosing_a_monitor_profile_changes_the_signature() { diff --git a/crates/color-ui/src/gradient/stops.rs b/crates/color-ui/src/gradient/stops.rs index 25894faeac..fa791791b6 100644 --- a/crates/color-ui/src/gradient/stops.rs +++ b/crates/color-ui/src/gradient/stops.rs @@ -16,6 +16,17 @@ use super::value::{ColorStop, GradientStops, OpacityStop, StopRow, StopRows}; /// new stops; the default is [`default_sampler`]. pub type Sampler = dyn Fn(&GradientStops, f32) -> Srgba; +/// What an Alt-drag of a colour stop does when it is held over another colour stop. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum AltDrop { + /// The drag copies the stop (the default). + #[default] + Copy, + /// The drag swaps the two stops' colours. + Swap, +} + /// What a host allows of the stops of one row. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -28,6 +39,8 @@ pub struct StopRules { pub max: usize, /// The range a midpoint may take (PhotoCraft 0.05..=0.95; InDesign and Illustrator 0.13..=0.87). pub midpoint: RangeInclusive, + /// What an Alt-drag of a colour stop over another colour stop does. + pub alt_drop: AltDrop, } impl StopRules { @@ -50,14 +63,36 @@ impl StopRules { self.midpoint = range; self } + + /// What an Alt-drag of a colour stop over another colour stop does. + #[must_use] + pub fn alt_drop(mut self, rule: AltDrop) -> Self { + self.alt_drop = rule; + self + } } impl Default for StopRules { fn default() -> Self { - Self { rows: StopRows::Split, min: 2, max: 1024, midpoint: 0.05..=0.95 } + Self { rows: StopRows::Split, min: 2, max: 1024, midpoint: 0.05..=0.95, alt_drop: AltDrop::Copy } } } +/// The stops with the colours of stops `i` and `j` exchanged (RGB and `tag`; locations, alpha and +/// midpoints stay), and the index of the stop `i`; `None` for `i == j` or an index out of range. +pub fn swap_colors(stops: &GradientStops, i: usize, j: usize) -> Option<(GradientStops, usize)> { + if i == j || i >= stops.color.len() || j >= stops.color.len() { + return None; + } + let (a, b) = (stops.color[i], stops.color[j]); + let mut out = stops.clone(); + out.color[i].color = Srgba { a: a.color.a, ..b.color }; + out.color[i].tag = b.tag; + out.color[j].color = Srgba { a: b.color.a, ..a.color }; + out.color[j].tag = a.tag; + Some((out, i)) +} + /// One Left or Right press moves a stop or midpoint by this share of the bar or line. pub const STOP_STEP: f32 = 0.01; /// One Shift press. @@ -113,6 +148,7 @@ impl Stop for OpacityStop { } /// The location of stop `i` of `row`. +#[cfg(feature = "ui")] pub(crate) fn location(stops: &GradientStops, row: StopRow, i: usize) -> f32 { match row { StopRow::Color => stops.color[i].location, @@ -121,6 +157,7 @@ pub(crate) fn location(stops: &GradientStops, row: StopRow, i: usize) -> f32 { } /// The midpoint after stop `i` of `row`. +#[cfg(feature = "ui")] pub(crate) fn midpoint(stops: &GradientStops, row: StopRow, i: usize) -> f32 { match row { StopRow::Color => stops.color[i].midpoint, @@ -129,6 +166,7 @@ pub(crate) fn midpoint(stops: &GradientStops, row: StopRow, i: usize) -> f32 { } /// The locations of `row`'s stops as the bar shows them. +#[cfg(feature = "ui")] pub(crate) fn locations(stops: &GradientStops, row: StopRow) -> Vec { match row { StopRow::Color => stops.color.iter().map(|s| s.location).collect(), @@ -137,6 +175,7 @@ pub(crate) fn locations(stops: &GradientStops, row: StopRow) -> Vec { } /// Where the midpoint after stop `i` of `row` is, 0..=1 of the bar. +#[cfg(feature = "ui")] pub(crate) fn midpoint_at(stops: &GradientStops, row: StopRow, i: usize) -> f32 { let at = locations(stops, row); at[i] + (at[i + 1] - at[i]) * midpoint(stops, row, i) diff --git a/crates/color-ui/src/harmony.rs b/crates/color-ui/src/harmony.rs index eb421af66c..7b03889bae 100644 --- a/crates/color-ui/src/harmony.rs +++ b/crates/color-ui/src/harmony.rs @@ -172,18 +172,36 @@ impl Harmony { // inv-vectorcraft: crates/color/src/harmony.rs:178 `apply`, with the `tones` table at :36–70 // (`t`, `soft`, `deep`, `hc`) and `contrast` at :72; `keep_model` is not needed (sRGB only). pub fn apply(self, base: Srgba) -> Vec { - let Hsb { h, s, b: v } = base.to_hsb(); - std::iter::once(base) - .chain(self.tones()[1..].iter().map(|tone| { + let Hsb { h, s, b } = base.to_hsb(); + let rest = self.apply_hsb([h, s, b]).into_iter().skip(1); + std::iter::once(base).chain(rest.map(|[h, s, b]| hsb(h, s, b).with_alpha(base.a))).collect() + } + + /// The rule's colours as HSB from the base's HSB, the base first: hue in degrees from 0 to + /// 360, saturation and brightness from 0 to 1. A grey base keeps its hue, so the colours keep + /// their places around a hue wheel. + // inv-vectorcraft: crates/color/src/harmony.rs:186 `apply_hsb`. + pub fn apply_hsb(self, [h, s, v]: [f32; 3]) -> Vec<[f32; 3]> { + self.tones() + .iter() + .map(|tone| { let b = match tone.bright { Bright::Times(f) => v * f, Bright::Contrast => contrast(v), }; - hsb(h + tone.turn, (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)).with_alpha(base.a) - })) + [(h + tone.turn).rem_euclid(360.0), (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)] + }) .collect() } + /// Whether every colour of the rule has a hue of its own (Triad, but not Triad 2 or + /// Monochromatic), so that each can sit on a hue ring apart from the others. + // inv-vectorcraft: crates/color/src/harmony.rs:201 `hues_differ`. + pub fn hues_differ(self) -> bool { + let turns: Vec = self.tones().iter().map(|t| t.turn.rem_euclid(360.0)).collect(); + turns.iter().enumerate().all(|(i, a)| turns[..i].iter().all(|b| a != b)) + } + fn tones(self) -> &'static [Tone] { match self { Harmony::Complementary => const { &[t(0.0), t(180.0)] }, @@ -383,3 +401,38 @@ impl Guide { self } } + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use craft_ui::testing::trial; + + /// A rule's HSB colours match the colours `apply` gives, and a grey base keeps its hue, so its + /// colours turn around the hue ring from it. + #[trial] + fn hsb_colours_match_and_keep_a_greys_hue() { + let base = Srgba::rgb(230.0 / 255.0, 120.0 / 255.0, 40.0 / 255.0); + let Hsb { h, s, b } = base.to_hsb(); + for rule in Harmony::ALL { + let hsb = rule.apply_hsb([h, s, b]); + let colors = rule.apply(base); + assert_eq!(hsb.len(), colors.len(), "{}", rule.id()); + for (a, c) in hsb.iter().zip(&colors).skip(1) { + assert_eq!(Srgba::from_hsb(Hsb { h: a[0], s: a[1], b: a[2] }), *c, "{}", rule.id()); + } + } + let grey = Harmony::Triad.apply_hsb([40.0, 0.0, 0.5]); + assert_eq!(grey.iter().map(|c| c[0]).collect::>(), [40.0, 160.0, 280.0]); + assert_eq!(Harmony::Analogous.apply_hsb([10.0, 1.0, 1.0])[2][0], 340.0, "hues wrap to 0..360"); + } + + /// Fifteen rules give every colour its own hue; the six that repeat a hue are left out. + #[trial] + fn rules_whose_colours_all_have_their_own_hue() { + let differ: Vec = Harmony::ALL.into_iter().filter(|h| h.hues_differ()).collect(); + assert_eq!(differ.len(), 15); + for h in [Harmony::Complementary2, Harmony::Monochromatic, Harmony::Shades, Harmony::Triad2, Harmony::Triad3, Harmony::HighContrast2] { + assert!(!h.hues_differ(), "{}", h.id()); + } + } +} diff --git a/crates/color-ui/src/palette.rs b/crates/color-ui/src/palette.rs index fb7b692308..4cffd10a35 100644 --- a/crates/color-ui/src/palette.rs +++ b/crates/color-ui/src/palette.rs @@ -147,7 +147,7 @@ impl SwatchColor { } } -/// How an `.ase` file marks a colour. +/// How a swatch is marked: its `.ase` kind, or the built-in Registration swatch. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] @@ -159,25 +159,102 @@ pub enum SwatchKind { Global, #[allow(missing_docs)] Spot, + /// The built-in Registration swatch: the global CMYK colour that prints on every plate. + Registration, +} + +/// What a swatch holds. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] +#[non_exhaustive] +pub enum SwatchPaint { + /// A colour. + Color(SwatchColor), + /// A tint of a named base swatch, with the colour it resolves to. + Tint { + /// The base swatch's name. + base: String, + /// The tint, 0–1. + tint: f32, + /// The resolved colour. + color: SwatchColor, + }, + /// A gradient; its value is the host's, keyed by the entry's name. + Gradient, + /// A pattern; its value is the host's, keyed by the entry's name. + Pattern, + /// The None swatch. + None, +} + +impl From for SwatchPaint { + /// The colour as a [`SwatchPaint::Color`]. + fn from(color: SwatchColor) -> Self { + SwatchPaint::Color(color) + } } /// One named swatch. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] +#[serde(from = "SwatchEntryWire", into = "SwatchEntryWire")] pub struct SwatchEntry { /// The swatch's label. pub name: String, - /// The swatch's colour. - pub color: SwatchColor, - #[serde(default)] + /// What the swatch holds. + pub paint: SwatchPaint, /// How the file marks the colour; `Process` unless the file says otherwise. pub kind: SwatchKind, } +/// The stored form of a [`SwatchEntry`]. It still reads an entry stored as `{name, color, kind}`, which holds a +/// colour, and writes `paint` only. +#[derive(serde::Serialize, serde::Deserialize)] +struct SwatchEntryWire { + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + paint: Option, + #[serde(default)] + kind: SwatchKind, +} + +impl From for SwatchEntry { + fn from(wire: SwatchEntryWire) -> Self { + let paint = wire.paint.or(wire.color.map(SwatchPaint::Color)).unwrap_or(SwatchPaint::None); + SwatchEntry { name: wire.name, paint, kind: wire.kind } + } +} + +impl From for SwatchEntryWire { + fn from(entry: SwatchEntry) -> Self { + SwatchEntryWire { name: entry.name, color: None, paint: Some(entry.paint), kind: entry.kind } + } +} + impl SwatchEntry { /// A process swatch. pub fn new(name: impl Into, color: SwatchColor) -> SwatchEntry { - SwatchEntry { name: name.into(), color, kind: SwatchKind::Process } + SwatchEntry { name: name.into(), paint: SwatchPaint::Color(color), kind: SwatchKind::Process } + } + + /// A process swatch holding `paint`. + pub fn with_paint(name: impl Into, paint: SwatchPaint) -> SwatchEntry { + SwatchEntry { name: name.into(), paint, kind: SwatchKind::Process } + } + + /// The swatch's colour: the colour of a `Color` or `Tint` paint, else `None`. + pub fn color(&self) -> Option<&SwatchColor> { + match &self.paint { + SwatchPaint::Color(color) | SwatchPaint::Tint { color, .. } => Some(color), + _ => None, + } + } + + /// Whether the swatch is reserved: a `None` paint or the Registration kind. + pub fn is_reserved(&self) -> bool { + self.kind == SwatchKind::Registration || matches!(self.paint, SwatchPaint::None) } } @@ -223,6 +300,9 @@ pub enum SwatchNote { /// An `.act` read whose trailer names a transparent index: the 1-based colour number, so a read reports what it /// could not keep. TransparentKept(usize), + /// The format holds colours only: gradient, pattern and None swatches were skipped, with their + /// count. + PaintsSkipped(usize), } /// Why a swatch file could not be read or written. @@ -291,7 +371,8 @@ pub fn read_swatches(bytes: &[u8], file_name: &str) -> Result<(Vec, let (mut n, mut skipped) = (0usize, 0usize); let mut convert = |s: &AseSwatch| { n += 1; - let entry = from_ase(&s.color).map(|color| SwatchEntry { name: entry_name(n - 1, &s.name), color, kind: s.kind }); + let entry = + from_ase(&s.color).map(|color| SwatchEntry { name: entry_name(n - 1, &s.name), paint: SwatchPaint::Color(color), kind: s.kind }); skipped += usize::from(entry.is_none()); entry }; @@ -330,20 +411,21 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V } let mut report = SwatchReport::default(); let all = || groups.iter().flat_map(|g| g.entries.iter()); - let kinds = all().filter(|e| e.kind != SwatchKind::Process).count(); + let kinds = all().filter(|e| e.color().is_some() && e.kind != SwatchKind::Process).count(); + let skipped = all().filter(|e| e.color().is_none()).count(); let flattened = groups.len() > 1; - match format { + let bytes = match format { SwatchFormat::Aco => { if count_swatches(groups) > ACO_MAX_SWATCHES { return Err(malformed(format, "an .aco file holds at most 65535 swatches")); } - let entries: Vec<(String, AcoColor)> = all().map(|e| (e.name.clone(), to_aco(&e.color))).collect(); + let entries: Vec<(String, AcoColor)> = all().filter_map(|e| e.color().map(|c| (e.name.clone(), to_aco(c)))).collect(); if flattened { report.notes.push(SwatchNote::GroupsFlattened); } push_note(&mut report, kinds, SwatchNote::KindsDropped); push_note(&mut report, names_cut(groups, false), SwatchNote::NamesCut); - Ok((write_aco(&entries), report)) + write_aco(&entries) } SwatchFormat::Act => { let (colors, books, converted) = rgb_colors(groups); @@ -364,7 +446,7 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V out.resize(ACT_PALETTE_LEN, 0); out.extend((triplets.len() as u16).to_be_bytes()); out.extend(0xFFFFu16.to_be_bytes()); - Ok((out, report)) + out } SwatchFormat::Ase => { if count_swatches(groups) > ASE_MAX_SWATCHES || groups.len() > ASE_MAX_GROUPS { @@ -377,8 +459,8 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V put_ase_name(&mut name, &g.name); put_ase_block(&mut body, ASE_GROUP_START, &name); blocks += 2; - for e in &g.entries { - match to_ase(&e.color) { + for (e, color) in g.entries.iter().filter_map(|e| e.color().map(|c| (e, c))) { + match to_ase(color) { Some(color) => { put_ase_color(&mut body, &e.name, &color, e.kind); blocks += 1; @@ -396,7 +478,7 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V out.extend(0u16.to_be_bytes()); out.extend(blocks.to_be_bytes()); out.extend(body); - Ok((out, report)) + out } SwatchFormat::Gpl | SwatchFormat::Css => { let (colors, books, converted) = rgb_colors(groups); @@ -409,9 +491,11 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V } else { write_css(groups, &colors) }; - Ok((text.into_bytes(), report)) + text.into_bytes() } - } + }; + push_note(&mut report, skipped, SwatchNote::PaintsSkipped); + Ok((bytes, report)) } /// PhotoCraft's default swatches (46 RGB colours in five groups: Grays, the exact RGB primaries diff --git a/crates/color-ui/src/palette/ase.rs b/crates/color-ui/src/palette/ase.rs index 1155bf883d..ea3b36ca18 100644 --- a/crates/color-ui/src/palette/ase.rs +++ b/crates/color-ui/src/palette/ase.rs @@ -190,7 +190,7 @@ pub(super) fn put_ase_color(out: &mut Vec, name: &str, color: &AseColor, kin AseColor::Other => {} } let code: u16 = match kind { - SwatchKind::Global => 0, + SwatchKind::Global | SwatchKind::Registration => 0, SwatchKind::Spot => 1, SwatchKind::Process => 2, }; diff --git a/crates/color-ui/src/palette/reader.rs b/crates/color-ui/src/palette/reader.rs index 9662efdb9c..538075bc83 100644 --- a/crates/color-ui/src/palette/reader.rs +++ b/crates/color-ui/src/palette/reader.rs @@ -75,8 +75,10 @@ pub(super) fn stem_of(file_name: &str) -> String { if stem.is_empty() { "Imported Swatches".into() } else { stem } } +/// The swatches a file can carry: those with a colour. Gradient, pattern and None swatches are not counted, so a +/// library of them alone is empty to every writer. pub(super) fn count_swatches(groups: &[SwatchGroup]) -> usize { - groups.iter().map(|g| g.entries.len()).sum() + groups.iter().map(|g| g.entries.iter().filter(|e| e.color().is_some()).count()).sum() } /// Whole UTF-16 scalar values of `name` that fit in `max` units. @@ -94,7 +96,7 @@ pub(super) fn utf16_units(name: &str, max: usize) -> Vec { pub(super) fn names_cut(groups: &[SwatchGroup], include_groups: bool) -> usize { let cut = |name: &str| name.encode_utf16().count() > MAX_NAME_UNITS; - let swatches = groups.iter().flat_map(|g| g.entries.iter()).filter(|e| cut(&e.name)).count(); + let swatches = groups.iter().flat_map(|g| g.entries.iter()).filter(|e| e.color().is_some() && cut(&e.name)).count(); swatches + if include_groups { groups.iter().filter(|g| cut(&g.name)).count() } else { 0 } } @@ -167,7 +169,8 @@ pub(super) fn rgb_colors(groups: &[SwatchGroup]) -> (Vec>, usize, g.entries .iter() .filter_map(|e| { - match e.color { + let color = e.color()?; + match color { SwatchColor::Book { .. } => { books += 1; return None; @@ -175,7 +178,7 @@ pub(super) fn rgb_colors(groups: &[SwatchGroup]) -> (Vec>, usize, SwatchColor::Cmyk(_) | SwatchColor::Lab(_) | SwatchColor::Gray(_) => converted += 1, SwatchColor::Rgb(_) | SwatchColor::Hsb(_) => {} } - Some((e.name.clone(), rgb8(e.color.to_srgb(CmykConverter::coated()).to_rgb_array()), e.kind == SwatchKind::Spot)) + Some((e.name.clone(), rgb8(color.to_srgb(CmykConverter::coated()).to_rgb_array()), e.kind == SwatchKind::Spot)) }) .collect() }) diff --git a/crates/color-ui/src/palette/tests.rs b/crates/color-ui/src/palette/tests.rs index 47c223276e..498366b4e8 100644 --- a/crates/color-ui/src/palette/tests.rs +++ b/crates/color-ui/src/palette/tests.rs @@ -47,7 +47,7 @@ fn aco_round_trips_colours_in_their_own_model() { assert_eq!(groups[0].name, "Brand"); for ((name, color), entry) in colors.iter().zip(&groups[0].entries) { assert_eq!(entry.name, *name); - assert_same(color, &entry.color); + assert_same(color, entry.color().unwrap()); } // A version 1 section comes first, then version 2 with the names. assert_eq!(&bytes[..4], &[0, 1, 0, 6]); @@ -68,8 +68,8 @@ fn ase_keeps_groups_and_aco_reports_flattening() { let (back, _) = read_swatches(&ase, "x.ase").unwrap(); assert_eq!(back.iter().map(|g| g.name.as_str()).collect::>(), ["Brand", "Greys"]); assert_eq!(back[0].entries[1].kind, SwatchKind::Spot); - assert_same(&back[0].entries[1].color, &groups[0].entries[1].color); - assert_same(&back[1].entries[0].color, &SwatchColor::Gray(0.5)); + assert_same(back[0].entries[1].color().unwrap(), groups[0].entries[1].color().unwrap()); + assert_same(back[1].entries[0].color().unwrap(), &SwatchColor::Gray(0.5)); // A colour in a model this crate does not read is skipped and counted. let mut unknown = Vec::new(); @@ -90,3 +90,43 @@ fn ase_keeps_groups_and_aco_reports_flattening() { assert_eq!(flat.len(), 1); assert_eq!(flat[0].entries.len(), 3); } + +/// Every writer leaves out the swatches that have no colour and counts them once, after its other notes; colours, +/// tints and the Registration swatch are written. A library of paints alone is empty. An entry stored without a +/// paint reads as a colour. +#[trial] +fn writers_skip_paint_swatches_and_report_them() { + let mut registration = SwatchEntry::new("Registration", SwatchColor::Cmyk([1.0; 4])); + registration.kind = SwatchKind::Registration; + let paints = vec![ + SwatchEntry::with_paint("Sky", SwatchPaint::Gradient), + SwatchEntry::with_paint("Dots", SwatchPaint::Pattern), + SwatchEntry::with_paint("None", SwatchPaint::None), + ]; + let mut entries = vec![ + SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), + SwatchEntry::with_paint("Pink", SwatchPaint::Tint { base: "Red".into(), tint: 0.5, color: SwatchColor::Rgb([1.0, 0.5, 0.5]) }), + registration, + ]; + entries.extend(paints.clone()); + let groups = vec![group("All", entries)]; + for format in SwatchFormat::ALL { + let (bytes, report) = write_swatches(&groups, format).unwrap(); + let counted = report.notes.iter().filter(|n| matches!(n, SwatchNote::PaintsSkipped(_))).count(); + assert_eq!(counted, 1, "{format:?}: {report:?}"); + assert_eq!(report.notes.last(), Some(&SwatchNote::PaintsSkipped(3)), "{format:?}: {report:?}"); + if format.can_read() { + let (back, _) = read_swatches(&bytes, &format!("x.{}", format.extension())).unwrap(); + assert_eq!(count_swatches(&back), 3, "{format:?}"); + } + assert_eq!(write_swatches(&[group("Paints", paints.clone())], format).unwrap_err(), SwatchError::Empty, "{format:?}"); + } + + let legacy: SwatchEntry = serde_json::from_str(r#"{"name":"Old","color":{"model":"rgb","values":[1.0,0.0,0.0]},"kind":"spot"}"#).unwrap(); + assert_eq!(legacy.paint, SwatchPaint::Color(SwatchColor::Rgb([1.0, 0.0, 0.0]))); + assert_eq!(legacy.kind, SwatchKind::Spot); + for entry in &groups[0].entries { + let json = serde_json::to_string(entry).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), *entry, "{json}"); + } +} diff --git a/crates/color-ui/src/ui/area.rs b/crates/color-ui/src/ui/area.rs index 1ded48bc60..052cf0c97f 100644 --- a/crates/color-ui/src/ui/area.rs +++ b/crates/color-ui/src/ui/area.rs @@ -1,17 +1,18 @@ //! [`ColorArea`]: two components of a colour across and down a field, the others fixed. use super::channels::{QUANTIZE_CELLS, channel_range, channel_step, quantized, settled, snapped, spoken}; +use super::ramp::Gamut; use crate::AreaMode; use craft_behavior::{Metrics, Mixed, Proposal, Sense}; -use craft_theme::ModelValues; +use craft_theme::{ModelValues, Srgba}; use craft_ui::contract::{ Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, MeasureCx, PaintUi, Props as _, Role, Sizing, WordSetCx as _, }; use craft_ui::primitives::ContentPainterCx; use craft_ui::runtime::env::Label; -use craft_ui::style::{ComponentStyle, StyleCx}; +use craft_ui::style::{ComponentStyle, MarkerLook, StyleColor, StyleCx}; use craft_ui::value_drag::{PointMark, PointPicker}; -use egui::{Mesh, Pos2, Rect, Vec2, pos2}; +use egui::{Color32, Mesh, Painter, Pos2, Rect, Stroke, Vec2, pos2}; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -19,12 +20,19 @@ pub(crate) mod stories; /// Vertices along each side of the area's colour mesh (PhotoCraft's 32). const MESH: usize = 32; +/// Cells along each side of the gamut shading grid. +const GRID: usize = 16; + /// The style of a colour area: the field is a point picker, which brings its own look. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct ColorAreaStyle { #[style(metrics)] metrics: Metrics, + /// The fill of a cell the gamut moves (`surface.scrim`). + scrim: StyleColor, + /// The marker look: its halo is the dark edge line and its ring the light one. + marker: MarkerLook, } /// The 2D field of a colour picker: two components of the colour across and down, the others fixed, as an @@ -60,6 +68,10 @@ pub struct ColorArea<'a> { /// The size of an area that does not fill its room; plot proportions by default. #[prop] shape: AreaShape, + /// The host's gamut: a cell of the 16 × 16 grid whose centre colour it moves is shaded with `surface.scrim`, with + /// a dark line under a light one along the edges between shaded and unshaded cells; drawn under the marker. + #[prop] + gamut: Option>, } /// The size of a [`ColorArea`] that does not fill its room. @@ -77,7 +89,7 @@ pub enum AreaShape { impl<'a> ColorArea<'a> { /// An area named `label` ("Saturation and brightness") showing `values`, values of `mode`'s model. pub fn new(label: impl Into