From 926779cd2fa1c13203c28b75035b8a54b08703ef Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 15 Nov 2026 12:00:01 +0800 Subject: [PATCH 01/14] Preserve RAW calibration, decoder notices and bounded admission --- Cargo.lock | 75 +++---- Cargo.toml | 60 +++--- crates/raw/src/develop.rs | 293 +++++++++++++++++++++++++-- crates/raw/src/lib.rs | 23 ++- crates/raw/src/look.rs | 5 + crates/raw/src/shared.rs | 117 ++++++++++- crates/raw/src/testgen/canon.rs | 10 +- crates/raw/src/testgen/dng.rs | 22 +- crates/raw/src/testgen/raf.rs | 40 ++-- crates/raw/src/testgen/rw2.rs | 15 +- crates/raw/tests/it/dng.rs | 189 +++++++++++------ crates/raw/tests/it/hasselblad.rs | 14 +- crates/raw/tests/it/raf.rs | 38 +++- crates/raw/tests/it/raw_corpus.rs | 34 +++- crates/raw/tests/it/vendor_codecs.rs | 30 ++- crates/raw/tests/it/vendors.rs | 45 +++- 16 files changed, 800 insertions(+), 210 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c0e3142ebd7..e67b385b688 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1323,7 +1323,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "crc32fast", "flate2", @@ -1344,7 +1344,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "rustix 1.1.5", ] @@ -1352,7 +1352,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "md-5", "rayon", @@ -1361,7 +1361,7 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-metadata", "craft-xml", @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "thiserror 2.0.21", ] @@ -1379,17 +1379,17 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-eps", "craft-idml", @@ -1407,7 +1407,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-atomic", "dirs", @@ -1417,12 +1417,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "heic-rs", "rayon", @@ -1431,7 +1431,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1454,7 +1454,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-xml", "craft-zip", @@ -1464,13 +1464,15 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-heif", "craft-jpeg", + "craft-metadata", "exr", "flate2", "half", + "hayro-jpeg2000", "image", "image-webp", "jpeg-encoder", @@ -1487,7 +1489,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "thiserror 2.0.21", ] @@ -1495,7 +1497,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-xml", "craft-zip", @@ -1505,7 +1507,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "brotli-decompressor 6.3.1", "chrono", @@ -1517,7 +1519,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-xml", "craft-zip", @@ -1527,7 +1529,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "blake3", "craft-atomic", @@ -1540,7 +1542,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "serde", "serde_json", @@ -1550,7 +1552,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "bytemuck", "flate2", @@ -1564,7 +1566,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1573,7 +1575,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-winprint-gdi", "log", @@ -1587,7 +1589,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "encoding_rs", "flate2", @@ -1598,7 +1600,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "chrono", "craft-crw", @@ -1616,7 +1618,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1633,7 +1635,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "serde", "thiserror 2.0.21", @@ -1642,7 +1644,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1663,7 +1665,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "chrono", "dunce", @@ -1698,7 +1700,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1707,16 +1709,17 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3143,7 +3146,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "bytemuck", "hayro-interpret", @@ -3173,7 +3176,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3191,7 +3194,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3215,7 +3218,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" dependencies = [ "flate2", "hayro-ccitt", diff --git a/Cargo.toml b/Cargo.toml index 1ec3fe6b374..fa6b02e376a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,9 +10,9 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["serde"] } # Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119). -craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } # The ArtCraft Launcher's agents switch and app list, shared with the launcher, the MCP gateway and # every Craft app (storytold/craft-ai-integrations#195). Pinned to the head of # storytold/craft-ai-integrations#197 until it merges. @@ -23,11 +23,11 @@ photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -46,31 +46,31 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft-ui. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e2dc681a3", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["egui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -229,7 +229,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7 egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README). -hayro = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index 6254c2f8776..d55009b3233 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -87,7 +87,7 @@ pub struct Developed { pub warnings: Vec, } -/// Linearization + black/white scaling for one sample (pre white balance), 0..1. +/// Linearization + black/white scaling for one sample (pre white balance), without clipping. pub(crate) struct Scale<'a> { s: &'a Sensor, lin: Option<&'a [u16]>, @@ -115,7 +115,9 @@ impl<'a> Scale<'a> { let black = s.black.at(x.saturating_sub(s.active.x), y.saturating_sub(s.active.y), sample, s.samples); let white = s.white[sample.min(2)]; let range = white - black; - if range.is_nan() || range < 1.0 { + // Floating-point sensor levels use source units: a valid white-minus-black + // range may be smaller than one. Only invalid or nonpositive ranges fail. + if !range.is_finite() || range <= 0.0 { return 0.0; } let n = (v - black) / range; @@ -189,7 +191,7 @@ fn fill_samples(row: &mut [f32], raw: impl Iterator, table: &[[ phase = if phase + 1 == table.len() { 0 } else { phase + 1 }; for k in 0..3 { let (black, range) = t[k]; - let n = if range.is_nan() || range < 1.0 { + let n = if !range.is_finite() || range <= 0.0 { 0.0 } else { let n = (lin(raw[k]) - black) / range; @@ -399,8 +401,16 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result = (0..period) .map(|p| { let x = c.x + p; @@ -408,33 +418,41 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result= 1.0 && black.is_finite()) { + if !(range.is_finite() && range > 0.0 && black.is_finite()) { return (0.0, 0.0); } - (black, mult[usize::from(cfa.color(x, y)).min(2)] / range) + let gain = mult[usize::from(cfa.color(x, y)).min(2)] / range; + // Scalar normalization rejects a non-finite quotient before + // white balance. A finite gain alone does not prove that + // every U16 numerator divided by this range stays finite. + finite_gains &= gain.is_finite() && ((0.0 - black) / range).is_finite() && ((f32::from(u16::MAX) - black) / range).is_finite(); + (black, gain) }) .collect(); - let src = &s.data[y * s.width + c.x..y * s.width + c.x + w]; - let ks = k.iter().cycle(); - match &sc.lin { - None => { - for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { - *v = ((f32::from(raw) - black) * gain).clamp(0.0, 1.0); + // Tiny positive ranges can overflow either the combined gain + // or scalar U16 normalization. Select the scalar row once; + // keep the ordinary fast pixel loop intact. + if finite_gains { + let src = &s.data[y * s.width + c.x..y * s.width + c.x + w]; + let ks = k.iter().cycle(); + match &sc.lin { + None => { + for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { + *v = ((f32::from(raw) - black) * gain).clamp(0.0, 1.0); + } } - } - Some(l) => { - for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { - let lin = f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw)); - *v = ((lin - black) * gain).clamp(0.0, 1.0); + Some(l) => { + for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { + let lin = f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw)); + *v = ((lin - black) * gain).clamp(0.0, 1.0); + } } } + } else { + fill_scalar(row); } } else { - for (i, v) in row.iter_mut().enumerate() { - let x = c.x + i; - let ch = usize::from(cfa.color(x, y)).min(2); - *v = (sc.value(x, y, 0) * mult[ch]).clamp(0.0, 1.0); - } + fill_scalar(row); } // Lens-shading gain maps, after the white-balance clip so clipped // highlights stay neutral. @@ -1176,4 +1194,237 @@ mod tests { assert_eq!(px(&orient(src.clone(), 3, 2, 5).0), vec![0, 3, 1, 4, 2, 5]); assert_eq!(px(&orient(src, 3, 2, 7).0), vec![5, 2, 4, 1, 3, 0]); } + + mod scale_review_tests { + use super::*; + + fn float_sensor(values: &[f32], black: f32, white: f32) -> Sensor { + let mut sensor = test_sensor(values.len(), 1, None, 1); + sensor.data.clear(); + sensor.float_data = Some(values.to_vec()); + sensor.black = crate::BlackLevels::uniform(black); + sensor.white = [white; 3]; + sensor.tone_curve.clear(); + sensor + } + + #[test] + fn fractional_float_levels_normalize_exactly_without_early_clipping() { + for (black, white, values, expected) in [ + (0., 0.5, vec![-0.25, 0., 0.125, 0.25, 0.5, 0.75], vec![-0.5, 0., 0.25, 0.5, 1., 1.5]), + (0.25, 0.75, vec![0., 0.25, 0.5, 0.75, 1.], vec![-0.5, 0., 0.5, 1., 1.5]), + ] { + let sensor = float_sensor(&values, black, white); + let scale = Scale::new(&sensor); + let actual: Vec<_> = (0..values.len()).map(|x| scale.value(x, 0, 0)).collect(); + assert_eq!(actual, expected); + let mut row = vec![0.; values.len() * 3]; + fill_linear_row(&scale, &[1.; 3], 0, 0, &mut row); + let clipped: Vec<_> = expected.iter().flat_map(|value| [value.clamp(0., 1.); 3]).collect(); + assert_eq!(row, clipped, "clipping remains at the existing develop boundary"); + } + } + + #[test] + fn invalid_ranges_and_nonfinite_samples_keep_the_existing_zero_fallback() { + for (black, white) in + [(0., 0.), (0.5, 0.25), (0., f32::NAN), (0., f32::INFINITY), (0., f32::NEG_INFINITY), (f32::NAN, 0.5), (f32::INFINITY, f32::INFINITY)] + { + let sensor = float_sensor(&[0.25], black, white); + assert_eq!(Scale::new(&sensor).value(0, 0, 0), 0.); + } + let sensor = float_sensor(&[f32::NAN, f32::INFINITY, f32::NEG_INFINITY], 0., 0.5); + for x in 0..3 { + assert_eq!(Scale::new(&sensor).value(x, 0, 0), 0.); + } + } + + #[test] + fn integer_unit_ranges_black_subtraction_and_linearization_remain_unchanged() { + let mut sensor = test_sensor(3, 1, None, 1); + sensor.data = vec![0, 1, 2]; + sensor.black = crate::BlackLevels::uniform(0.); + sensor.white = [1.; 3]; + assert_eq!((0..3).map(|x| Scale::new(&sensor).value(x, 0, 0)).collect::>(), [0., 1., 2.]); + sensor.data = vec![64, 1024, 4000]; + sensor.black = crate::BlackLevels::uniform(64.); + sensor.white = [4000.; 3]; + assert_eq!((0..3).map(|x| Scale::new(&sensor).value(x, 0, 0)).collect::>(), [0., 960. / 3936., 1.]); + sensor.data = vec![0, 1, 2]; + sensor.linearization = Some(vec![0, 64, 128]); + sensor.black = crate::BlackLevels::uniform(0.); + sensor.white = [128.; 3]; + assert_eq!((0..3).map(|x| Scale::new(&sensor).value(x, 0, 0)).collect::>(), [0., 0.5, 1.]); + } + + #[test] + fn fractional_integer_monochrome_rows_match_scalar_and_keep_clipping_at_the_row_boundary() { + let mut sensor = test_sensor(3, 1, None, 1); + sensor.data = vec![0, 1, 2]; + sensor.black = crate::BlackLevels::uniform(0.75); + sensor.white = [1.25; 3]; + for linearization in [None, Some(vec![0, 1, 2])] { + sensor.linearization = linearization; + let scale = Scale::new(&sensor); + let scalar: Vec<_> = (0..3).map(|x| scale.value(x, 0, 0)).collect(); + assert_eq!(scalar, [-1.5, 0.5, 2.5], "scalar values remain unclipped"); + let mut row = [0.; 9]; + fill_linear_row(&scale, &[1.; 3], 0, 0, &mut row); + assert_eq!(row, [0., 0., 0., 0.5, 0.5, 0.5, 1., 1., 1.]); + assert_eq!(row.to_vec(), scalar.iter().flat_map(|value| [value.clamp(0., 1.); 3]).collect::>()); + } + } + + #[test] + fn fractional_integer_periodic_cfa_rows_match_forced_scalar_development() { + let mut periodic = test_sensor(16, 12, crate::Cfa::bayer("RGGB"), 1); + periodic.data = (0..16 * 12).map(|i| (i % 3) as u16).collect(); + periodic.black = crate::BlackLevels { rows: 2, cols: 2, values: vec![0.75, 1., 1., 0.75], delta_h: vec![], delta_v: vec![] }; + periodic.white = [1.25; 3]; + periodic.tone_curve.clear(); + let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), demosaic: Demosaic::Bilinear, ..Default::default() }; + for linearization in [None, Some(vec![0, 1, 2])] { + periodic.linearization = linearization; + let mut scalar = periodic.clone(); + // Zero column deltas preserve every black level but select the + // existing Scale::value row path rather than periodic gains. + scalar.black.delta_h = vec![0.; scalar.width]; + for fused in [false, true] { + let expected = develop(&scalar, &options, fused).unwrap(); + let actual = develop(&periodic, &options, fused).unwrap(); + assert!(expected.rgb.iter().any(|&value| value > 0), "the independent scalar reference must contain visible pixels"); + assert_eq!(actual.rgb, expected.rgb, "periodic and scalar rows, fused={fused}"); + } + } + } + + #[test] + fn subnormal_integer_cfa_ranges_use_scalar_rows_when_periodic_gains_overflow() { + let tiny = f32::from_bits(1); + let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), demosaic: Demosaic::Bilinear, ..Default::default() }; + for (black, white, raw, expected_scale) in [(0., tiny, 1u16, 0.), (-tiny, 0., 0u16, 1.)] { + let mut periodic = test_sensor(8, 8, crate::Cfa::bayer("RGGB"), 1); + periodic.data.fill(raw); + periodic.black = crate::BlackLevels::uniform(black); + periodic.white = [white; 3]; + periodic.tone_curve.clear(); + assert_eq!(Scale::new(&periodic).value(0, 0, 0), expected_scale); + let mut scalar = periodic.clone(); + scalar.black.delta_h = vec![0.; scalar.width]; + for fused in [false, true] { + let expected = develop(&scalar, &options, fused).unwrap(); + let actual = develop(&periodic, &options, fused).unwrap(); + assert_eq!(actual.rgb, expected.rgb, "subnormal scalar normalization, raw={raw}, fused={fused}"); + if expected_scale == 0. { + assert!(actual.rgb.iter().all(|&value| value == 0)); + } else { + assert!(actual.rgb.iter().all(|&value| value > 0), "the valid scalar result must not be replaced by black"); + } + } + } + } + + #[test] + fn finite_periodic_gains_preserve_scalar_sanitization_of_overflowing_u16_normalization() { + let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), demosaic: Demosaic::Bilinear, ..Default::default() }; + for (white, raw, expected_scale) in [(1e-38f32, u16::MAX, 0f32), (4095., 2048u16, 2048. / 4095.)] { + assert!((1.0f32 / white).is_finite(), "this case must not rely on the existing non-finite-gain fallback"); + let mut periodic = test_sensor(8, 8, crate::Cfa::bayer("RGGB"), 1); + periodic.data.fill(raw); + periodic.black = crate::BlackLevels::uniform(0.); + periodic.white = [white; 3]; + periodic.tone_curve.clear(); + assert_eq!(Scale::new(&periodic).value(0, 0, 0), expected_scale); + let mut scalar = periodic.clone(); + // A zero column delta selects the independent scalar row without + // changing any level, sample, white balance or colour policy. + scalar.black.delta_h = vec![0.; scalar.width]; + for fused in [false, true] { + let expected = develop(&scalar, &options, fused).unwrap(); + let actual = develop(&periodic, &options, fused).unwrap(); + assert_eq!(actual.rgb, expected.rgb, "finite gain, white={white}, raw={raw}, fused={fused}"); + if expected_scale == 0. { + assert!(actual.rgb.iter().all(|&value| value == 0), "overflowing scalar normalization must not become white"); + } else { + assert!(actual.rgb.iter().any(|&value| value > 0), "ordinary finite normalization must retain visible pixels"); + } + } + } + } + + #[test] + fn integer_row_paths_reject_nonfinite_and_nonpositive_ranges_like_scalar() { + for (black, white) in + [(0., 0.), (1., 0.5), (0., f32::NAN), (0., f32::INFINITY), (0., f32::NEG_INFINITY), (f32::NAN, 1.), (f32::INFINITY, f32::INFINITY)] + { + let mut sensor = test_sensor(8, 8, None, 1); + sensor.data.fill(1); + sensor.black = crate::BlackLevels::uniform(black); + sensor.white = [white; 3]; + let scale = Scale::new(&sensor); + assert_eq!(scale.value(0, 0, 0), 0.); + let mut row = [1.; 24]; + fill_linear_row(&scale, &[1.; 3], 0, 0, &mut row); + assert_eq!(row, [0.; 24]); + sensor.cfa = crate::Cfa::bayer("RGGB"); + sensor.tone_curve.clear(); + let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), demosaic: Demosaic::Bilinear, ..Default::default() }; + let periodic = develop(&sensor, &options, false).unwrap(); + sensor.black.delta_h = vec![0.; sensor.width]; + let scalar = develop(&sensor, &options, false).unwrap(); + assert_eq!(periodic.rgb, scalar.rgb); + assert!(periodic.rgb.iter().all(|&value| value == 0)); + } + } + + /// Independent TIFF/DNG strip layout: three little-endian IEEE754 binary32 + /// monochrome samples, with explicit fractional WhiteLevel and no calibration. + fn fractional_white_dng() -> Vec { + use crate::testgen::{TiffBuilder, Val}; + let mut file = TiffBuilder::default(); + let pixels = file.blob([0f32, 0.25, 0.5].iter().flat_map(|value| value.to_le_bytes()).collect()); + let image = file.ifd(vec![ + (256, Val::Long(vec![3])), + (257, Val::Long(vec![1])), + (258, Val::Short(vec![32])), + (259, Val::Short(vec![1])), + (262, Val::Short(vec![34892])), + (273, Val::Blobs(vec![pixels])), + (277, Val::Short(vec![1])), + (278, Val::Long(vec![1])), + (279, Val::Long(vec![12])), + (339, Val::Short(vec![3])), + (50706, Val::Byte(vec![1, 4, 0, 0])), + (50714, Val::Double(vec![0.])), + (50717, Val::Double(vec![0.5])), + ]); + file.chain = vec![image]; + file.build() + } + + #[test] + fn fractional_white_float_dng_develops_black_half_gray_and_white_instead_of_all_black() { + let bytes = fractional_white_dng(); + let sensor = crate::decode(&bytes, &crate::Limits::default()).unwrap(); + assert_eq!(sensor.float_data.as_deref(), Some([0., 0.25, 0.5].as_slice())); + assert_eq!(sensor.white, [0.5; 3]); + assert!(sensor.is_monochrome()); + let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), ..Default::default() }; + let developed = crate::develop(&bytes, &options).unwrap(); + assert_eq!((developed.width, developed.height), (3, 1)); + assert_eq!(developed.rgb.len(), 9); + for (pixel, expected) in developed.rgb.as_chunks::<3>().0.iter().zip([0u16, 44590, 65535]) { + // Half linear gray is 0.5^(1/1.8), with at most one output code + // of rounding/interpolation in the existing gamma-1.8 LUT. + if expected == 0 || expected == u16::MAX { + assert!(pixel.iter().all(|actual| *actual == expected), "{pixel:?} vs {expected}"); + } else { + assert!(pixel.iter().all(|actual| actual.abs_diff(expected) <= 1), "{pixel:?} vs {expected}"); + } + } + let mut broken = sensor; + broken.float_data.as_mut().unwrap().pop(); + assert!(matches!(develop_sensor(&broken, &options), Err(RawError::Malformed(_))), "a truncated buffer remains a data error, never silently black"); + } + } } diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index f0d82391e8e..f1c144ce22b 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -184,8 +184,13 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result { let mut shared_limits = craft_raw::Limits::default(); shared_limits.max_samples = max_samples; let info = craft_raw::probe_info_with(bytes, &shared_limits).map_err(shared_error)?; - if info.width > limits.max_width as usize || info.height > limits.max_height as usize { - return Err(RawError::LimitExceeded(format!("dimensions {}×{} exceed {}×{}", info.width, info.height, limits.max_width, limits.max_height))); + // A three-component sample allowance is not a pixel allowance: a CFA plane + // must still obey the caller's max_pixels before any sample allocation. + limits.check(info.width as u64, info.height as u64, (info.cpp as u64).saturating_mul(4))?; + // The shared parser supports additional component layouts; PhotoCraft's developer + // currently accepts only one CFA/monochrome plane or three RGB planes. + if !matches!(info.cpp, 1 | 3) { + return Err(RawError::unsupported(format!("{} samples per pixel", info.cpp))); } let image = craft_raw::decode_with(bytes, &shared_limits).map_err(shared_error)?; Ok(crate::shared::adapt(image)) @@ -213,3 +218,17 @@ pub fn develop(bytes: &[u8], opts: &DevelopOptions) -> Result Vec { fn warnings(image: &craft_raw::RawImage) -> Vec { let mut out = Vec::new(); + if image.notices.default_crop_adjusted { + out.push("raw default crop was invalid, incomplete or out-of-range; adjusted within the active area".into()); + } + if image.notices.assumed_cfa { + out.push("raw colour filter phase (Bayer phase) was not recorded or recognized; the decoder's fallback pattern was used".into()); + } + // Unknown means the decoder has not annotated provenance; it does not mean + // the file omitted its levels. Report only an explicit fallback decision. + if image.format != craft_raw::RawFormat::Dng { + if image.level_sources.black == craft_raw::LevelSource::Fallback { + out.push("raw black level not recorded in a documented tag; assumed default".into()); + } + if image.level_sources.white == craft_raw::LevelSource::Fallback { + out.push("raw white level not recorded in a documented tag; assumed full sample range".into()); + } + } for op in image.opcodes.list1.iter().chain(&image.opcodes.list2).chain(&image.opcodes.list3) { if !matches!(op, craft_raw::Opcode::GainMap { .. } | craft_raw::Opcode::MapPolynomial { .. }) { out.push("some raw correction opcodes are not applied by PhotoCraft".to_string()); break; } } - if image.color.profile.gain_table_map.is_some() { - out.push("the raw camera profile's gain table map is not applied by PhotoCraft".to_string()); + if image.notices.gain_table_omitted || image.color.profile.gain_table_map.is_some() { + out.push("the raw camera profile's ProfileGainTableMap is not applied by PhotoCraft".to_string()); } out } @@ -130,6 +146,15 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { as_shot_white_xy: image.color.as_shot_white_xy, }; let tone_curve = image.color.profile.tone_curve.map_or_else(Vec::new, |c| c.points); + // Non-DNG TIFF/EP bodies can state their balance through AsShotNeutral. + // Keep the public camera-WB field populated without changing DNG color policy. + let camera_wb = image.wb_multipliers.map(|v| v.map(f64::from)).or_else(|| { + (image.format != craft_raw::RawFormat::Dng) + .then_some(image.color.as_shot_neutral) + .flatten() + .filter(|values| values.iter().all(|value| value.is_finite() && *value > 0.0 && (1.0 / value).is_finite())) + .map(|values| values.map(|value| 1.0 / value)) + }); let (data, float_data) = match image.data { craft_raw::RawData::U16(v) => (v, None), craft_raw::RawData::F32(v) => (Vec::new(), Some(v)), @@ -137,7 +162,7 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { let mut sensor = Sensor { format: format(image.format), make: image.camera.make, - model: image.camera.unique_model.or(image.camera.model), + model: image.camera.model.or(image.camera.unique_model), width: image.width, height: image.height, samples: image.cpp, @@ -150,7 +175,7 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { active, crop, color, - camera_wb: image.wb_multipliers.map(|v| v.map(f64::from)), + camera_wb, orientation: image.orientation.to_exif(), baseline_exposure: image.color.baseline_exposure, gain_maps, @@ -160,8 +185,90 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { warnings, }; crate::cameras::apply(&mut sensor, image.bits); - if sensor.float_data.is_none() { + // DNG's declared white can exceed the stored clipping plateau. Other raw + // decoders have already chosen their camera-specific or measured levels; + // their decoded samples must not be silently rescaled a second time. + if sensor.float_data.is_none() && sensor.format == RawFormat::Dng { sensor.lift_clipped_samples(); } sensor } + +#[cfg(test)] +mod tests { + use super::*; + + fn raw_image() -> craft_raw::RawImage { + let mut spec = crate::testgen::DngSpec::cfa(64, 64, (0..64 * 64).map(|i| (528 + ((i % 64) * 60 + (i / 64) * 7) as u16 % 4000).min(3567)).collect()); + spec.black = vec![528]; + spec.white = 4095; + let mut image = craft_raw::decode_with(&spec.build(), &Default::default()).unwrap(); + image.camera.make = None; + image.camera.model = None; + image.camera.unique_model = None; + image + } + + #[test] + fn only_declared_fallback_level_provenance_produces_missing_level_notices() { + let mut image = raw_image(); + image.format = craft_raw::RawFormat::Nef; + for source in + [craft_raw::LevelSource::Unknown, craft_raw::LevelSource::Metadata, craft_raw::LevelSource::MaskedPixels, craft_raw::LevelSource::Inferred] + { + image.level_sources.black = source; + image.level_sources.white = source; + assert!(warnings(&image).iter().all(|warning| !warning.contains("level")), "{source:?}"); + } + image.level_sources.black = craft_raw::LevelSource::Fallback; + image.level_sources.white = craft_raw::LevelSource::Fallback; + let notices = warnings(&image); + assert!(notices.iter().any(|warning| warning.contains("black level"))); + assert!(notices.iter().any(|warning| warning.contains("white level"))); + image.format = craft_raw::RawFormat::Dng; + assert!(warnings(&image).iter().all(|warning| !warning.contains("level")), "DNG's documented defaults are not missing camera metadata"); + } + + #[test] + fn non_dng_decode_preserves_samples_while_dng_clipping_policy_still_applies() { + let image = raw_image(); + let craft_raw::RawData::U16(stored) = &image.data else { panic!("integer fixture") }; + let original = stored.clone(); + let mut other = image.clone(); + other.format = craft_raw::RawFormat::Nef; + assert_eq!(adapt(other).data, original, "camera-specific levels must not trigger a second sample rewrite"); + let dng = adapt(image); + assert_ne!(dng.data, original, "independent early saturation fixture exercises DNG lifting"); + assert!(dng.data.iter().zip(original).all(|(actual, source)| *actual == source || *actual == 4095)); + } + + #[test] + fn non_dng_as_shot_neutral_populates_camera_balance_and_model_keeps_its_own_identity() { + let mut image = raw_image(); + image.format = craft_raw::RawFormat::CfaTiff; + image.camera.model = Some("X2D II 100C".into()); + image.camera.unique_model = Some("Hasselblad X2D II 100C".into()); + image.wb_multipliers = None; + image.color.as_shot_neutral = Some([0.375, 1., 0.617]); + let sensor = adapt(image.clone()); + assert_eq!(sensor.model.as_deref(), Some("X2D II 100C")); + assert_eq!(sensor.camera_wb, Some([1. / 0.375, 1., 1. / 0.617])); + image.color.as_shot_neutral = Some([0., 1., f64::NAN]); + assert_eq!(adapt(image).camera_wb, None, "invalid neutral must not create nonfinite balance"); + } + + #[test] + fn decoder_notices_remain_visible_without_inventing_loss_for_absent_metadata() { + let mut image = raw_image(); + image.notices = Default::default(); + assert!(warnings(&image).is_empty()); + image.notices.default_crop_adjusted = true; + assert!(warnings(&image).iter().any(|warning| warning.contains("default crop") && warning.contains("out-of-range"))); + image.notices.default_crop_adjusted = false; + image.notices.assumed_cfa = true; + assert!(warnings(&image).iter().any(|warning| warning.contains("colour filter phase") && warning.contains("Bayer phase"))); + image.notices.assumed_cfa = false; + image.notices.gain_table_omitted = true; + assert!(warnings(&image).iter().any(|warning| warning.contains("ProfileGainTableMap"))); + } +} diff --git a/crates/raw/src/testgen/canon.rs b/crates/raw/src/testgen/canon.rs index 2c4ad54f968..41a0229f1ac 100644 --- a/crates/raw/src/testgen/canon.rs +++ b/crates/raw/src/testgen/canon.rs @@ -212,10 +212,12 @@ pub fn tiff_ep(make: &str, width: usize, height: usize, data: &[u16], cfa: [u8; (33421, Val::Short(vec![2, 2])), (33422, Val::Byte(cfa.to_vec())), ]; - raw.extend(extra_raw_tags); + // Make and Model belong to IFD0, where readers look for them; anything else is raw-IFD data. + let (ifd0_tags, raw_tags): (Vec<_>, Vec<_>) = extra_raw_tags.into_iter().partition(|(tag, _)| matches!(tag, 271 | 272)); + raw.extend(raw_tags); let raw_ifd = t.ifd(raw); let thumb = t.blob(vec![128; 12]); - let ifd0 = t.ifd(vec![ + let mut ifd0 = vec![ (254, Val::Long(vec![1])), (256, Val::Long(vec![2])), (257, Val::Long(vec![2])), @@ -226,7 +228,9 @@ pub fn tiff_ep(make: &str, width: usize, height: usize, data: &[u16], cfa: [u8; (277, Val::Short(vec![3])), (279, Val::Long(vec![12])), (330, Val::Ifds(vec![raw_ifd])), - ]); + ]; + ifd0.extend(ifd0_tags); + let ifd0 = t.ifd(ifd0); t.chain = vec![ifd0]; t.build() } diff --git a/crates/raw/src/testgen/dng.rs b/crates/raw/src/testgen/dng.rs index f9d252c391c..db8d787edb8 100644 --- a/crates/raw/src/testgen/dng.rs +++ b/crates/raw/src/testgen/dng.rs @@ -365,7 +365,27 @@ impl DngSpec { let bytes: Vec = match self.bits { 8 => v.iter().map(|&x| x as u8).collect(), 16 => v.iter().flat_map(|&x| if self.big_endian { x.to_be_bytes() } else { x.to_le_bytes() }).collect(), - _ => v.iter().flat_map(|x| x.to_le_bytes()).collect(), + // Other depths are bit-packed, most significant bit first, a row at a time (the TIFF layout). + bits => v + .chunks(n) + .flat_map(|row| { + let mut out = Vec::new(); + let (mut acc, mut have) = (0u32, 0u32); + for &x in row { + acc = acc << bits | u32::from(x) & ((1 << bits) - 1); + have += u32::from(bits); + while have >= 8 { + have -= 8; + out.push((acc >> have) as u8); + } + acc &= (1 << have) - 1; + } + if have > 0 { + out.push((acc << (8 - have)) as u8); + } + out + }) + .collect(), }; let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); e.write_all(&bytes).expect("zlib"); diff --git a/crates/raw/src/testgen/raf.rs b/crates/raw/src/testgen/raf.rs index 9a2ddb7e385..6d34d4f9a9b 100644 --- a/crates/raw/src/testgen/raf.rs +++ b/crates/raw/src/testgen/raf.rs @@ -154,22 +154,28 @@ impl RafSpec { } out } - RafPacking::Words14 => { - let (mut logical, mut acc, mut n) = (Vec::new(), 0u64, 0u32); - for &v in &self.data { - acc = (acc << 14) | u64::from(v & 0x3FFF); - n += 14; - while n >= 8 { - logical.push((acc >> (n - 8)) as u8); - n -= 8; + // Rows of 14-bit samples, most significant bit first, in little-endian 32-bit words: each row + // starts on a word boundary (the stride is the raw IFD's 0xF005). + RafPacking::Words14 => self + .data + .chunks(self.width.max(1)) + .flat_map(|row| { + let (mut logical, mut acc, mut n) = (Vec::new(), 0u64, 0u32); + for &v in row { + acc = (acc << 14) | u64::from(v & 0x3FFF); + n += 14; + while n >= 8 { + logical.push((acc >> (n - 8)) as u8); + n -= 8; + } } - } - if n > 0 { - logical.push((acc << (8 - n)) as u8); - } - logical.resize(logical.len().next_multiple_of(4), 0); - logical.chunks(4).flat_map(|w| w.iter().rev().copied().collect::>()).collect() - } + if n > 0 { + logical.push((acc << (8 - n)) as u8); + } + logical.resize(logical.len().next_multiple_of(4), 0); + logical.chunks(4).flat_map(|w| w.iter().rev().copied().collect::>()).collect::>() + }) + .collect(), RafPacking::Compressed { lossy } => { assert!(self.width == 780 && self.height.is_multiple_of(6) && self.data.iter().all(|&v| v == 0), "see RafPacking::Compressed"); let quantizers: Vec = (0..self.height / 6).map(|g| [2, 0, 5][g % 3]).collect(); @@ -194,6 +200,10 @@ impl RafSpec { (0xF00A, self.black.clone()), ] .into_iter() + .chain(matches!(self.packing, RafPacking::Words14).then(|| (0xF005, vec![(self.width * 14).div_ceil(32) as u32]))) + // Padded narrow rows can occupy two bytes per sample, so stride alone + // cannot distinguish packed words from ordinary 16-bit containers. + .chain(matches!(self.packing, RafPacking::Words14).then(|| (0xF006, vec![1]))) .chain(self.wb_grb.map(|w| (0xF00E, w.to_vec()))) .collect(); let mut out = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; diff --git a/crates/raw/src/testgen/rw2.rs b/crates/raw/src/testgen/rw2.rs index 8dedfad007c..1b423500804 100644 --- a/crates/raw/src/testgen/rw2.rs +++ b/crates/raw/src/testgen/rw2.rs @@ -95,14 +95,17 @@ impl V4Writer<'_> { self.nbits += (RW2_PAGE as u32) * 8; self.pos += RW2_PAGE; } - let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0; - at = (at + RW2_PAGE - RW2_COMPRESSED_SPLIT) % RW2_PAGE; - let at = self.base + at + self.pos - RW2_PAGE; + // The field is a little-endian 16-bit word at a byte of the logical page; each of its two bytes + // lands where the page split puts it (the word can straddle the split). + let logical = ((self.nbits - num) >> 3) as usize ^ 0x3FF0; + let page = self.base + self.pos - RW2_PAGE; + let physical = |l: usize| page + (l + RW2_PAGE - RW2_COMPRESSED_SPLIT) % RW2_PAGE; + let (lo, hi) = (physical(logical), physical(logical + 1)); self.nbits -= num; - let cur = u32::from(self.buf[at]) | (u32::from(self.buf[at + 1]) << 8); + let cur = u32::from(self.buf[lo]) | (u32::from(self.buf[hi]) << 8); let cur = cur | ((v & ((1 << num) - 1)) << (self.nbits & 7)); - self.buf[at] = cur as u8; - self.buf[at + 1] = (cur >> 8) as u8; + self.buf[lo] = cur as u8; + self.buf[hi] = (cur >> 8) as u8; } /// Encodes one row as 14-pixel groups: the scale selector is always 0 and diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index ca9d8959601..616fd346e67 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -8,6 +8,19 @@ fn sensor(bytes: &[u8]) -> Sensor { decode(bytes, &Limits::default()).unwrap() } +/// Float DNG samples remain in their source white-level units, without U16 quantization. +fn floats(s: &Sensor) -> &[f32] { + s.float_data.as_deref().expect("floating-point samples") +} + +fn unit(data: &[u16]) -> Vec { + data.iter().map(|&v| f32::from(v) / 65535.0).collect() +} + +fn near(got: &[f32], want: &[f32]) -> bool { + got.len() == want.len() && got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-6) +} + /// Deterministic sensor-like samples below `2^bits`. fn noise(n: usize, bits: u16) -> Vec { let mut s = 0x9E37_79B9_7F4A_7C15u64; @@ -243,7 +256,8 @@ fn metadata_is_read() { assert_eq!(s.color.as_shot_neutral, Some([0.5, 1.0, 0.8])); assert!((s.baseline_exposure - 0.5).abs() < 1e-6); assert_eq!(s.orientation, 6); - assert_eq!(s.linearization.as_ref().map(Vec::len), Some(4096)); + assert!(s.linearization.is_none(), "the shared decoder has already applied the table"); + assert!(s.data.iter().all(|&sample| sample == 3000), "all stored1000 samples use the3x table"); let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); // Orientation 6 swaps the cropped 20×16 to 16×20. assert_eq!((d.width, d.height), (16, 20)); @@ -253,38 +267,47 @@ fn metadata_is_read() { } #[test] -fn enormous_double_crop_origin_is_rejected() { +fn enormous_double_crop_origin_keeps_the_whole_active_area_with_warning() { let (w, h) = (16, 12); - let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]); - spec.active_area = Some([2, 3, 10, 14]); - spec.default_crop = Some(([0, 0], [11, 8])); - spec.default_crop_origin_double = Some([1e300, 0.0]); - - assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); + for origin in [1e300, f64::INFINITY, f64::NAN, -1.] { + let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]); + spec.active_area = Some([2, 3, 10, 14]); + spec.default_crop = Some(([0, 0], [11, 8])); + spec.default_crop_origin_double = Some([origin, 0.0]); + let s = sensor(&spec.build()); + assert_eq!(s.active, Rect::new(3, 2, 11, 8)); + assert_eq!(s.crop, Rect::new(3, 2, 11, 8), "invalid coordinates cannot create a clipped sliver"); + assert_eq!(s.data, spec.data, "fallback preserves every stored sensor value"); + assert!(s.warnings.iter().any(|warning| warning.contains("default crop")), "{origin}: {:?}", s.warnings); + } } #[test] -fn out_of_range_default_crop_falls_back_to_active_area_with_warning() { +fn out_of_range_default_crop_uses_checked_intersection_with_warning() { let (w, h) = (16, 12); let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]); spec.active_area = Some([2, 3, 10, 14]); spec.default_crop = Some(([10, 0], [5, 4])); let s = sensor(&spec.build()); - assert_eq!(s.crop, s.active); + assert_eq!(s.active, Rect::new(3, 2, 11, 8)); + assert_eq!(s.crop, Rect::new(13, 2, 1, 4), "[10,0,5,4] intersected with relative[0,0,11,8]"); + assert_eq!(s.data, spec.data, "crop adjustment does not rewrite sensor samples"); assert!(s.warnings.iter().any(|warning| warning.contains("out-of-range") && warning.contains("default crop")), "{:?}", s.warnings); } -/// DefaultCropSize defaults to the whole image, which can't fit once the origin moves in. +/// A missing DefaultCropSize uses the shared full-area default, intersected with the active area. #[test] -fn default_crop_origin_without_size_falls_back_to_active_area_with_warning() { +fn default_crop_origin_without_size_uses_checked_intersection_with_warning() { let (w, h) = (16, 12); let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]); spec.active_area = Some([2, 3, 10, 14]); spec.default_crop_origin_double = Some([1.0, 1.0]); let s = sensor(&spec.build()); - assert_eq!(s.crop, s.active); + assert_eq!(s.active, Rect::new(3, 2, 11, 8)); + assert_eq!(s.crop, Rect::new(4, 3, 10, 7), "relative origin1,1 clips only the default area edges"); + assert_eq!(s.data, spec.data); assert!(s.warnings.iter().any(|warning| warning.contains("out-of-range") && warning.contains("default crop")), "{:?}", s.warnings); } @@ -508,8 +531,21 @@ fn smooth_scene_develops_with_every_method() { #[test] fn unsupported_variants_say_so() { - let mut spec = DngSpec::cfa(8, 8, vec![0; 64]); - spec.cfa = [0, 1, 2, 1]; // not Bayer + // The shared reader now supports periodic non-Bayer CFA. Prove the source + // pattern and constant-scene development rather than deleting its coverage. + let mut spec = DngSpec::cfa(8, 8, vec![1000; 64]); + let mut bayer = spec.clone(); + bayer.white = 4000; + spec.white = 4000; + spec.cfa = [0, 1, 2, 1]; + let sensor = sensor(&spec.build()); + assert_eq!(sensor.data, spec.data); + assert_eq!(sensor.cfa.as_ref().unwrap().phase(0, 0), spec.cfa); + assert!(!sensor.cfa.as_ref().unwrap().is_bayer()); + let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), ..Default::default() }; + assert_eq!(develop_sensor(&sensor, &options).unwrap().rgb, develop(&bayer.build(), &options).unwrap().rgb); + // Integer sample widths above16 remain unsupported, never truncated toU16. + spec.bits = 17; assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Unsupported(_)))); } @@ -583,22 +619,18 @@ fn deflate_8_bit_predictor_and_packed_12_bit() { spec.white = 255; spec.storage = DngStorage::DeflateStrips { rows: h, predictor: 2 }; assert_eq!(sensor(&spec.build()).data, data8, "8-bit predictor 2"); - // 12-bit packed: two samples in three bytes, MSB first. Swap the testgen's 16-bit - // containers for a packed stream of the same samples. + // Independently frame two 12-bit samples in three bytes, MSB first. The + // fixture writer now emits valid packed samples too: verify its actual + // compressed payload against this separate construction before decoding. let data12: Vec = (0..w * h).map(|i| (i as u16 * 61) & 0xFFF).collect(); let mut spec = DngSpec::cfa(w, h, data12.clone()); spec.bits = 12; spec.white = 4095; spec.storage = DngStorage::DeflateStrips { rows: h, predictor: 1 }; - let mut bytes = spec.build(); - let containers: Vec = data12.iter().flat_map(|v| v.to_le_bytes()).collect(); - let old = zlib(&containers); + let bytes = spec.build(); let packed: Vec = data12.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 0xF) << 4 | p[1] >> 8) as u8, p[1] as u8]).collect(); - let mut new = zlib(&packed); - let at = bytes.windows(old.len()).position(|c| c == old.as_slice()).expect("the strip"); - assert!(new.len() <= old.len()); - new.resize(old.len(), 0); // trailing bytes after the zlib stream are ignored - bytes[at..at + old.len()].copy_from_slice(&new); + let compressed = zlib(&packed); + assert!(bytes.windows(compressed.len()).any(|chunk| chunk == compressed.as_slice()), "fixture contains independently packed 12-bit strip"); assert_eq!(sensor(&bytes).data, data12, "12-bit packed"); } @@ -706,15 +738,16 @@ fn float_jxl_dng(data: &[u16], w: usize, h: usize, white: Option) -> DngSpe fn floating_point_jpeg_xl_linear_raw_decodes() { let (w, h) = (24, 16); let data = noise(w * h * 3, 16); - // White level 1.0 (the default) becomes 65535: the samples read back as stored. + // White level 1.0 (the default): the samples read back as stored, as floats. let s = sensor(&float_jxl_dng(&data, w, h, None).build()); assert_eq!((s.width, s.height, s.samples), (w, h, 3)); - assert_eq!(s.data, data); - assert_eq!(s.white, [65535.0; 3]); - // A stated white level of 0.5 becomes 65535 too: samples double, those above it clip. + assert!(s.data.is_empty()); + assert!(near(floats(&s), &unit(&data))); + assert_eq!(s.white, [1.0; 3]); + // A stated white level of 0.5 is kept in the floats' own unit. let s = sensor(&float_jxl_dng(&data, w, h, Some(0.5)).build()); - assert_eq!(s.white, [65535.0; 3]); - assert_eq!(s.data, data.iter().map(|&v| (u32::from(v) * 2).min(65535) as u16).collect::>()); + assert_eq!(s.white, [0.5; 3]); + assert!(near(floats(&s), &unit(&data))); // It develops like the same samples stored as integers. let pixels: Vec = scene(w, h).iter().flat_map(|p| p.map(|v| (v * 20000.0) as u16)).collect(); let float = develop(&float_jxl_dng(&pixels, w, h, None).build(), &DevelopOptions::default()).unwrap(); @@ -726,14 +759,18 @@ fn floating_point_jpeg_xl_linear_raw_decodes() { } #[test] -fn floating_point_raw_data_that_isnt_jpeg_xl_is_unsupported() { +fn uncompressed_float_raw_preserves_known_half_values_including_signed_hdr() { let (w, h) = (8, 4); - let mut spec = float_jxl_dng(&noise(w * h * 3, 16), w, h, None); + let mut spec = DngSpec::cfa(w, h, [0x3800u16, 0x3c00, 0x4000, 0xbc00].repeat(w * h * 3 / 4)); + spec.samples = 3; + spec.white = 0; + spec.raw_extra = vec![(339, Val::Short(vec![3; 3]))]; spec.storage = DngStorage::Strips { rows: h }; - match decode(&spec.build(), &Limits::default()) { - Err(RawError::Unsupported(m)) => assert!(m.contains("floating-point"), "{m}"), - other => panic!("expected unsupported, got {other:?}"), - } + let s = sensor(&spec.build()); + assert_eq!((s.width, s.height, s.samples), (w, h, 3)); + assert!(s.data.is_empty()); + assert_eq!(floats(&s), [0.5f32, 1.0, 2.0, -1.0].repeat(w * h * 3 / 4)); + assert_eq!(s.white, [1.0; 3]); } /// WhiteLevel has one value per sample plane: the floats are scaled by the highest, so a plane @@ -745,8 +782,8 @@ fn floating_point_white_levels_per_plane_scale_from_the_highest() { let mut spec = float_jxl_dng(&data, w, h, None); spec.raw_extra.push((50717, Val::Double(vec![0.5, 1.0, 0.5]))); let s = sensor(&spec.build()); - assert_eq!(s.data, data, "scaled by 1.0, the highest: nothing clipped"); - assert_eq!(s.white, [32767.5, 65535.0, 32767.5]); + assert!(near(floats(&s), &unit(&data)), "the floats are not scaled"); + assert_eq!(s.white, [0.5, 1.0, 0.5]); } /// `Σ cᵢ · xⁱ` at `x`, both clipped to 0..1 (as MapPolynomial). @@ -755,6 +792,24 @@ fn poly(c: &[f64], x: f64) -> f64 { c.iter().rev().fold(0.0, |acc, c| acc * x + c).clamp(0.0, 1.0) } +/// Compare deferred development against independently evaluated normalized samples. +/// The reference uses the source's F32 domain and then the public polynomial formula, +/// avoiding the old intermediate U16 quantization and any wider output tolerance. +fn assert_polynomial_development(actual: &Sensor, normalized: Vec) { + let mut expected = actual.clone(); + expected.float_data = Some(normalized); + expected.data.clear(); + expected.linearization = None; + expected.polynomials.clear(); + expected.white = [1.; 3]; + expected.black = BlackLevels::uniform(0.); + let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), ..Default::default() }; + let got = develop_sensor(actual, &options).unwrap(); + let want = develop_sensor(&expected, &options).unwrap(); + assert_eq!((got.width, got.height), (want.width, want.height)); + assert_eq!(got.rgb, want.rgb, "deferred polynomial matches independently mapped source samples"); +} + /// #8125: a lossy DNG's OpcodeList2 carries a MapPolynomial per plane, and its colours depend on /// it. Each plane's samples are mapped through its polynomial, on the linear reference values. #[test] @@ -769,8 +824,9 @@ fn map_polynomial_maps_each_plane_of_floating_point_data() { )); let bytes = spec.build(); let s = sensor(&bytes); - let want: Vec = data.iter().enumerate().map(|(i, &v)| (poly(&planes[i % 3], f64::from(v) / 65535.0) * 65535.0).round() as u16).collect(); - assert_eq!(s.data, want); + let want: Vec = data.iter().enumerate().map(|(i, &v)| poly(&planes[i % 3], f64::from(f32::from(v) / 65535.)) as f32).collect(); + assert!(near(floats(&s), &unit(&data)), "stored float values stay unprocessed until development"); + assert_polynomial_development(&s, want); assert!(s.warnings.iter().all(|w| !w.contains("MapPolynomial")), "{:?}", s.warnings); let d = develop(&bytes, &DevelopOptions::default()).unwrap(); assert!(d.warnings.iter().all(|w| !w.contains("MapPolynomial")), "{:?}", d.warnings); @@ -789,9 +845,10 @@ fn map_polynomial_follows_the_linearization_table() { spec.linearization = Some(table.clone()); spec.opcode_list2 = Some(testgen::map_polynomial_opcode_list([0, 0, h as u32, w as u32], &[(0, vec![0.0, 0.0, 1.0])])); let s = sensor(&spec.build()); - assert!(s.linearization.is_none(), "applied with the polynomial"); - let want: Vec = data.iter().map(|&v| (poly(&[0.0, 0.0, 1.0], f64::from(table[usize::from(v)]) / 8190.0) * 8190.0).round() as u16).collect(); - assert_eq!(s.data, want); + assert!(s.linearization.is_none(), "linearization applied at decode, polynomial deferred to development"); + assert_eq!(s.data, data.iter().map(|&value| table[usize::from(value)]).collect::>()); + let want: Vec = data.iter().map(|&v| poly(&[0.0, 0.0, 1.0], f64::from(f32::from(table[usize::from(v)]) / 8190.)) as f32).collect(); + assert_polynomial_development(&s, want); } /// A LinearizationTable maps integer samples: floating-point data ignores one. @@ -803,10 +860,10 @@ fn floating_point_raw_data_ignores_a_linearization_table() { spec.linearization = Some(vec![0; 4]); let s = sensor(&spec.build()); assert!(s.linearization.is_none()); - assert_eq!(s.data, data); + assert!(near(floats(&s), &unit(&data))); } -/// Floating-point samples are read into four bytes each before they become 16-bit: the limits +/// Floating-point samples stay four bytes each: the limits /// are charged for that buffer, not for the two-byte result. #[test] fn floating_point_jpeg_xl_is_charged_four_bytes_a_sample() { @@ -896,7 +953,7 @@ fn an_infinite_white_level_falls_back_to_the_default() { ints.raw_extra.push((50717, Val::Double(vec![1e300; 3]))); assert_eq!(sensor(&ints.build()).white, [65535.0; 3], "integer data"); let float = float_jxl_dng(&pixels, w, h, Some(1e300)).build(); - assert_eq!(sensor(&float).white, [65535.0; 3], "floating-point data"); + assert_eq!(sensor(&float).white, [1.0; 3], "floating-point data"); let default = develop(&float_jxl_dng(&pixels, w, h, None).build(), &DevelopOptions::default()).unwrap(); assert_eq!(develop(&float, &DevelopOptions::default()).unwrap().rgb, default.rgb); } @@ -911,9 +968,10 @@ fn jpeg_xl_mismatches_are_errors() { // Codestream smaller than the strip. spec.jxl_segments = vec![jxl(&data[..w * 4 * 3], w, 4, 3, 16)]; assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); - // Grey codestream for RGB samples. + // A grey codestream contradicts the RGB IFD: this is damaged framing, + // not a supported one-plane image or a conversion request. spec.jxl_segments = vec![jxl(&data[..w * h], w, h, 1, 16)]; - assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Unsupported(_)))); + assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); // Not a codestream at all. spec.jxl_segments = vec![vec![0xff, 0x0a, 1, 2, 3, 4, 5]]; assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); @@ -1055,7 +1113,8 @@ fn lossy_jpeg_levels_and_linearization_apply_to_stored_values() { spec.linearization = Some(table.clone()); spec.storage = storage; let s = sensor(&spec.build()); - assert_eq!(s.linearization.as_deref(), Some(table.as_slice())); + assert!(s.linearization.is_none(), "table already applied to stored samples"); + assert_eq!(s.data, vec![40_000; w * h]); assert_eq!(s.white, [65535.0; 3], "the table's maximum is white"); grey(&develop_sensor(&s, &DevelopOptions::default()).unwrap()) }; @@ -1074,31 +1133,37 @@ fn lossy_jpeg_truncated_tile_errors() { assert!(matches!(decode(cut, &Limits::default()), Err(RawError::Malformed(_))), "a cut JPEG tile must not decode"); } -/// A tile JPEG whose header disagrees with the tile size fails the header check, before any -/// pixel decode (a hostile SOF must not be able to size the decoder's buffers first). +/// JPEG tiles must cover all visible pixels within bounded MCU padding. Hostile +/// frame dimensions fail the header check before the decoder allocates pixels. #[test] fn lossy_jpeg_tile_dimension_mismatch_errors() { let (w, h) = (32, 32); let mut spec = lossy_spec(w, h, vec![100; w * h], DngStorage::LossyJpegTiles { width: 32, height: 32 }); let small: Vec = (0..16 * 16).map(|i| (i % 16 * 16) as u8).collect(); spec.lossy_segments = vec![baseline_jpeg(&small, 16, 16, 1)]; - let err = decode(&spec.build(), &Limits::default()).unwrap_err().to_string(); - assert!(err.contains("16x16") && err.contains("32x32"), "{err}"); - // A tile coded at the image's row count instead of the tile's is tolerated (a strip-like - // encoder); anything else is not. + let err = decode(&spec.build(), &Limits::default()).unwrap_err(); + assert!(matches!(&err, RawError::Malformed(message) if message.contains("16 x 16") && message.contains("32 x 32") && message.contains("tile")), "{err}"); + // Edge frames may cover only the visible image or bounded MCU padding. + // Neither path may omit visible rows or introduce zero-filled pixels. let (w, h) = (16, 12); let mut spec = lossy_spec(w, h, vec![100; w * h], DngStorage::LossyJpegTiles { width: 16, height: 16 }); - spec.lossy_segments = vec![baseline_jpeg(&[100u8; 16 * 12], 16, 12, 1)]; - let s = sensor(&spec.build()); - assert_eq!((s.width, s.height), (w, h)); - assert!(s.data.iter().all(|&v| v.abs_diff(100) <= 2)); - for (tw, th) in [(16, 14), (16, 18), (12, 16), (18, 16)] { + for (tw, th) in [(16, 12), (16, 14), (16, 18), (18, 16)] { + spec.lossy_segments = vec![baseline_jpeg(&vec![100u8; tw * th], tw, th, 1)]; + let s = sensor(&spec.build()); + assert_eq!((s.width, s.height, s.data.len()), (w, h, w * h)); + assert!(s.data.iter().all(|&v| v.abs_diff(100) <= 2), "{tw}x{th}: visible source pixels survive padding"); + } + for (tw, th) in [(16, 11), (15, 16), (12, 16), (16, 33), (33, 16)] { spec.lossy_segments = vec![baseline_jpeg(&vec![100u8; tw * th], tw, th, 1)]; assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_))), "{tw}x{th}"); } - // A strip must be coded at its own row count. + // The last strip can include padding, but it must cover its four visible rows. let mut spec = lossy_spec(w, h, vec![100; w * h], DngStorage::LossyJpegStrips { rows: 8 }); spec.lossy_segments = vec![baseline_jpeg(&[100u8; 16 * 8], 16, 8, 1), baseline_jpeg(&[100u8; 16 * 8], 16, 8, 1)]; + let padded = sensor(&spec.build()); + assert_eq!(padded.data.len(), w * h); + assert!(padded.data.iter().all(|&v| v.abs_diff(100) <= 2)); + spec.lossy_segments[1] = baseline_jpeg(&[100u8; 16 * 3], 16, 3, 1); assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); } diff --git a/crates/raw/tests/it/hasselblad.rs b/crates/raw/tests/it/hasselblad.rs index 8bdf5c29572..4eeefa7a366 100644 --- a/crates/raw/tests/it/hasselblad.rs +++ b/crates/raw/tests/it/hasselblad.rs @@ -50,7 +50,10 @@ fn metadata() { assert!((wb[2] - 1.0 / 0.617).abs() < 1e-9, "{wb:?}"); assert_eq!((sensor.make.as_deref(), sensor.model.as_deref()), (Some("Hasselblad"), Some("X2D II 100C"))); assert_eq!(sensor.orientation, 1); - assert!(sensor.warnings.is_empty(), "{:?}", sensor.warnings); + // This real-layout fixture deliberately has no CFAPattern tag. All source + // metadata is retained, while the decoder discloses its assumed RGGB phase. + assert_eq!(sensor.warnings.len(), 1, "{:?}", sensor.warnings); + assert!(sensor.warnings[0].contains("Bayer phase") && sensor.warnings[0].contains("fallback"), "{:?}", sensor.warnings); } #[test] @@ -77,7 +80,7 @@ fn compressed_3fr_is_reported_unsupported() { let mut s = spec(); s.compression = 7; let e = decode(&s.build(), &Limits::default()).unwrap_err(); - assert!(matches!(&e, RawError::Unsupported(reason) if reason.contains("lossless-JPEG")), "{e:?}"); + assert!(matches!(&e, RawError::Unsupported(reason) if reason.contains("lossless JPEG")), "{e:?}"); } #[test] @@ -92,8 +95,11 @@ fn missing_levels_fall_back() { let sensor = decode(&s.build(), &Limits::default()).unwrap(); assert_eq!(sensor.black, BlackLevels::uniform(0.0)); assert!(sensor.warnings.iter().any(|w| w.contains("black level")), "{:?}", sensor.warnings); - // clip_level backs the clipped plateau off slightly. - assert!((sensor.white[0] - f32::from(u16::MAX) * 0.995).abs() < 1.0, "{:?}", sensor.white); + // Shared provenance identifies this as the declared-depth default. The + // non-DNG adapter must not silently rescale the stored samples afterward. + assert_eq!(sensor.white, [f32::from(u16::MAX); 3]); + assert_eq!(sensor.data, s.data); + assert!(sensor.warnings.iter().any(|warning| warning.contains("white level")), "{:?}", sensor.warnings); } #[test] diff --git a/crates/raw/tests/it/raf.rs b/crates/raw/tests/it/raf.rs index 4d54d8a4a05..1c50c75449d 100644 --- a/crates/raw/tests/it/raf.rs +++ b/crates/raw/tests/it/raf.rs @@ -30,6 +30,36 @@ fn every_storage_decodes_exactly() { } } +const SMALL_ROW_VALUES: [u16; 16] = [0, 1, 0x3FFF, 0x2000, 0x1234, 42, 255, 0x1555, 0x2AAA, 2, 0x3FFE, 4096, 8191, 1023, 7, 37]; + +#[test] +fn small_word_packed_rows_decode_exactly() { + // Eight 14-bit samples need four words per row. At two rows this has the + // same payload size as U16, so the packed-word flag must select the decoder. + for data in [vec![1; 16], SMALL_ROW_VALUES.to_vec()] { + let mut spec = RafSpec::new(8, 2, data.clone(), RGGB.to_vec()); + spec.packing = RafPacking::Words14; + spec.bits = 14; + let sensor = decode(&spec.build(), &Limits::default()).unwrap(); + assert_eq!((sensor.width, sensor.height), (8, 2)); + assert_eq!(sensor.data, data); + } +} + +#[test] +fn small_u16_rows_keep_their_container_packing() { + for le in [false, true] { + for data in [vec![1; 16], SMALL_ROW_VALUES.to_vec()] { + let mut spec = RafSpec::new(8, 2, data.clone(), RGGB.to_vec()); + spec.packing = RafPacking::U16 { le }; + spec.bits = 14; + let sensor = decode(&spec.build(), &Limits::default()).unwrap(); + assert_eq!((sensor.width, sensor.height), (8, 2)); + assert_eq!(sensor.data, data, "U16 little-endian: {le}"); + } + } +} + #[test] fn xtrans_metadata() { let mut spec = xtrans(RafPacking::U16 { le: true }, 14); @@ -48,7 +78,11 @@ fn xtrans_metadata() { assert!((s.baseline_exposure - 0.72).abs() < 1e-9); assert_eq!(s.orientation, 6); assert_eq!((s.make.as_deref(), s.model.as_deref()), (Some("FUJIFILM"), Some("X-Synthetic"))); - assert!(s.warnings.is_empty(), "{:?}", s.warnings); + // This RAF records black/WB but no white tag; the full 14-bit range is an + // explicit fallback, not a missing-CFA or missing-black warning. + assert_eq!(s.white, [16383.; 3]); + assert_eq!(s.warnings.len(), 1, "{:?}", s.warnings); + assert!(s.warnings[0].contains("white level") && s.warnings[0].contains("full sample range"), "{:?}", s.warnings); } #[test] @@ -152,7 +186,7 @@ fn compressed_variants_that_cannot_be_decoded_fail_cleanly() { for cfa in [other.as_slice(), &[1, 0, 2, 1]] { let b = compressed(cfa, 14, false).build(); match decode(&b, &Limits::default()) { - Err(RawError::Unsupported(m)) => assert!(m.contains("CFA"), "{m}"), + Err(RawError::Unsupported(m)) => assert!(m.contains("layout"), "{m}"), other => panic!("expected unsupported, got {other:?}"), } } diff --git a/crates/raw/tests/it/raw_corpus.rs b/crates/raw/tests/it/raw_corpus.rs index 7d2ca341d2c..83f5388b2bb 100644 --- a/crates/raw/tests/it/raw_corpus.rs +++ b/crates/raw/tests/it/raw_corpus.rs @@ -26,6 +26,8 @@ struct Want<'a> { cfa: [u8; 4], black: &'a [f32], white: [f32; 3], + /// Exact source-sample maximum and its population at the pinned corpus revision. + sample_max: (u16, usize), } const WANTS: &[Want] = &[ @@ -37,7 +39,8 @@ const WANTS: &[Want] = &[ size: (4176, 3062), cfa: [0, 1, 1, 2], black: &[128.0; 4], - white: [4095.0; 3], + white: [4080.0; 3], + sample_max: (4095, 2207), }, // The same camera after DNG Converter: the sensor data round-trips identically. Want { @@ -49,6 +52,7 @@ const WANTS: &[Want] = &[ cfa: [0, 1, 1, 2], black: &[127.0], white: [4095.0; 3], + sample_max: (4093, 6886), }, Want { file: "JD1_8203.NEF", @@ -59,8 +63,9 @@ const WANTS: &[Want] = &[ cfa: [0, 1, 1, 2], black: &[0.0], white: [4095.0; 3], + sample_max: (4095, 222), }, - // Sony cRAW: the saturation level comes from the compressed code's range. + // Sony cRAW: white is the inferred lower edge of its saturated sample band. Want { file: "DSC00009.ARW", format: RawFormat::Arw, @@ -69,8 +74,9 @@ const WANTS: &[Want] = &[ size: (4832, 3224), cfa: [0, 1, 1, 2], // SR2SubIFD black levels, verified with the metadata oracle (not the 512 fallback). - black: &[800.0; 4], - white: [16301.0; 3], + black: &[800.0], + white: [16320.0; 3], + sample_max: (16383, 3326), }, // The G9's high-resolution mode: a 10480 × 7794 sensor cropped to 10368 × 7776. Want { @@ -81,7 +87,8 @@ const WANTS: &[Want] = &[ size: (10480, 7794), cfa: [0, 1, 1, 2], black: &[127.0, 128.0, 128.0, 127.0], - white: [4095.0; 3], + white: [4080.0; 3], + sample_max: (4095, 558549), }, // Four Thirds Olympus: GRBG instead of the usual RGGB. Want { @@ -93,6 +100,7 @@ const WANTS: &[Want] = &[ cfa: [1, 0, 2, 1], black: &[65.0; 4], white: [4095.0; 3], + sample_max: (4095, 10), }, ]; @@ -108,7 +116,23 @@ fn decode_matches_the_measured_oracles() { let cfa = s.cfa.as_ref().unwrap_or_else(|| panic!("{}: no CFA", w.file)); assert_eq!(cfa.colors, w.cfa, "{}", w.file); assert_eq!(s.black.values, w.black, "{}", w.file); + // An inferred white is a band boundary, not the largest decoded sample. + // Pin the sample maximum and its population independently of that policy. + let sample_max = s.data.iter().fold((0u16, 0usize), |(maximum, count), &value| { + if value > maximum { + (value, 1) + } else if value == maximum { + (maximum, count + 1) + } else { + (maximum, count) + } + }); + assert_eq!(sample_max, w.sample_max, "{} source maximum and population", w.file); if w.file == "DSC00009.ARW" { + for (x, y) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + assert_eq!(s.black.at(x, y, 0, 1), 800.0, "Sony metadata black at CFA site ({x}, {y})"); + } + assert_eq!(s.data.iter().filter(|&&value| value == 16372).count(), 74490, "Sony saturated compressed-code population"); assert_eq!(s.camera_wb, Some([2056.0 / 1024.0, 1.0, 1908.0 / 1024.0])); } for ch in 0..3 { diff --git a/crates/raw/tests/it/vendor_codecs.rs b/crates/raw/tests/it/vendor_codecs.rs index 7c9e53ba4f0..1b1f6cee774 100644 --- a/crates/raw/tests/it/vendor_codecs.rs +++ b/crates/raw/tests/it/vendor_codecs.rs @@ -144,7 +144,9 @@ fn craw_without_a_black_level_tag_reads_black_from_the_tone_curve() { fn rw2_round_trip_12_and_14_bit() { for (bits, w, h) in [(12u32, 120usize, 300usize), (14, 117, 260)] { let max = (1u16 << bits) - 1; - let data = mosaic(&scene(w, h), w, [0, 1, 1, 2], 128, max); + // Uniformly exercise the entire declared code range, without a sensor + // saturation plateau that would intentionally infer a lower white level. + let data: Vec = (0..w * h).map(|i| ((i * 23 + 191) % (usize::from(max) + 1)) as u16).collect(); let b = rw2(w, h, &data, bits); assert!(b.len() > 3 * 0x4000, "spans several pages"); assert_eq!(identify(&b), Some(RawFormat::Rw2)); @@ -196,7 +198,10 @@ fn rw2_format4_round_trip_is_exact() { assert_eq!(s.white, [4095.0; 3]); assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5])); assert_eq!(s.crop, Rect::new(2, 2, w - 4, h - 4)); - assert!(s.warnings.is_empty(), "{:?}", s.warnings); + // The decoded white is the full-range fallback. Keep every other decoder + // disclosure unexpected while preserving exact samples, CFA, levels and crop. + assert_eq!(s.warnings.len(), 1, "{:?}", s.warnings); + assert!(s.warnings[0].contains("white level") && s.warnings[0].contains("full sample range"), "{:?}", s.warnings); let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); assert_eq!((d.width as usize, d.height as usize), (w - 4, h - 4)); } @@ -217,12 +222,14 @@ fn rw2_format4_crosses_pages() { } #[test] -fn rw2_format4_rejects_other_block_widths() { +fn rw2_format4_preserves_samples_with_a_partial_final_block() { let (w, h) = (42, 2); let data: Vec = (0..w * h).map(|i| 200 + (i % 14) as u16 * 3).collect(); let mut b = rw2_format4(w, h, &data); patch_ifd0_short(&mut b, 0x0002, 41); - assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_)))); + let s = decode(&b, &Limits::default()).unwrap(); + assert_eq!((s.width, s.height), (41, h)); + assert_eq!(s.data, data[..41 * h]); } #[test] @@ -230,15 +237,17 @@ fn rw2_undecoded_formats_fall_back() { let data = vec![200u16; 20 * 4]; let mut b = rw2(20, 4, &data, 12); assert!(decode(&b, &Limits::default()).is_ok()); - patch_ifd0_short(&mut b, 0x002D, 6); + patch_ifd0_short(&mut b, 0x002D, 9); match decode(&b, &Limits::default()) { - Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 6"), "{m}"), + Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 9"), "{m}"), other => panic!("expected unsupported, got {other:?}"), } - // Width not made of whole blocks. + // The stream is continuous: a final partial block keeps exactly the declared samples. let mut b = rw2(20, 4, &data, 12); patch_ifd0_short(&mut b, 0x0002, 19); - assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_)))); + let s = decode(&b, &Limits::default()).unwrap(); + assert_eq!((s.width, s.height), (19, 4)); + assert_eq!(s.data, data[..19 * 4]); // Sizes beyond the limits are refused before allocating. let mut b = rw2(20, 4, &data, 12); patch_ifd0_short(&mut b, 0x0003, 60000); @@ -259,7 +268,10 @@ fn orf_uncompressed_round_trip() { assert_eq!(s.white, [4095.0; 3]); assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5])); assert_eq!(s.crop, Rect::new(2, 2, w - 4, h - 4)); - assert!(s.warnings.is_empty(), "{:?}", s.warnings); + // The decoded white is the full-range fallback. Keep every other decoder + // disclosure unexpected while preserving exact samples, CFA, levels and crop. + assert_eq!(s.warnings.len(), 1, "{:?}", s.warnings); + assert!(s.warnings[0].contains("white level") && s.warnings[0].contains("full sample range"), "{:?}", s.warnings); assert!(develop_sensor(&s, &DevelopOptions::default()).is_ok()); // The maker-note preview is found too (used when the data is compressed). assert!(embedded_preview(&b).is_some()); diff --git a/crates/raw/tests/it/vendors.rs b/crates/raw/tests/it/vendors.rs index 20ceb152a5f..8b5248dac0d 100644 --- a/crates/raw/tests/it/vendors.rs +++ b/crates/raw/tests/it/vendors.rs @@ -62,7 +62,7 @@ fn cr2_srgb_raw_is_unsupported() { let sof = b.windows(2).position(|w| w == [0xFF, 0xC3]).unwrap(); b[sof + 11] = 0x21; match decode(&b, &Limits::default()) { - Err(RawError::Unsupported(m)) => assert!(m.contains("sRAW"), "{m}"), + Err(RawError::Unsupported(m)) => assert!(m.contains("subsampled"), "{m}"), other => panic!("expected unsupported sRAW, got {other:?}"), } } @@ -110,11 +110,11 @@ fn other_raw_containers_are_recognised_but_unsupported() { cr3.extend_from_slice(&[0; 12]); assert_eq!(identify(&cr3), Some(RawFormat::Cr3)); assert!(matches!(decode(&cr3, &Limits::default()), Err(RawError::Unsupported(_)))); - // A bare RAF header has no CFA TIFF (like early FinePix files): recognised, unsupported. + // A bare RAF signature has no declared raw data: recognized, but malformed. let mut raf = b"FUJIFILMCCD-RAW 0201FF383501".to_vec(); raf.resize(200, 0); assert_eq!(identify(&raf), Some(RawFormat::Raf)); - assert!(matches!(decode(&raf, &Limits::default()), Err(RawError::Unsupported(_)))); + assert!(matches!(decode(&raf, &Limits::default()), Err(RawError::Malformed(_)))); assert_eq!(decode(b"not a raw file", &Limits::default()).unwrap_err(), RawError::NotRaw); } @@ -185,16 +185,22 @@ fn grey_patch(d: &Developed, x0: usize) -> [f64; 3] { } #[test] -fn cr2_cfa_phase_is_measured_for_every_row_phase_and_border_parity() { +fn cr2_model_cfa_phase_is_stable_for_every_border_parity_and_discloses_assumptions() { // Canon data has red in the even columns; the red rows are even (RGGB at the data // origin: 40D, 5D Mark III, …) or odd (GBRG: 7D, 550D, 5D Mark II, …). Odd image-area // borders used to shift the assumed pattern and swap green with red/blue. - for cfa in [[0, 1, 1, 2], [1, 2, 0, 1]] { + // This fixture omits CR2CFAPattern. Use the observed model fallback for + // green-first data; scene content cannot establish a missing source tag. + for (cfa, model) in [([0, 1, 1, 2], None), ([1, 2, 0, 1], Some(0x8000_0250))] { for (l, t) in [(16, 4), (17, 4), (16, 5), (17, 5)] { - let b = cr2_phase_spec(cfa, l, t, None).build(); + let b = cr2_phase_spec(cfa, l, t, model).build(); let s = decode(&b, &Limits::default()).unwrap(); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), cfa, "cfa {cfa:?} borders ({l}, {t})"); - assert!(s.warnings.is_empty(), "{:?}", s.warnings); + // Both missing source values remain disclosed, even when the + // selected model/default layout agrees with the generated scene. + assert_eq!(s.warnings.len(), 2, "{:?}", s.warnings); + assert!(s.warnings.iter().any(|w| w.contains("colour filter phase")), "{:?}", s.warnings); + assert!(s.warnings.iter().any(|w| w.contains("white level") && w.contains("full sample range")), "{:?}", s.warnings); let d = develop_sensor(&s, &DevelopOptions { orient: false, ..Default::default() }).unwrap(); let [r, g, bl] = grey_patch(&d, 192 / 2 - l); // Neutral grey decodes neutral (a swapped phase gives a strong magenta or green cast). @@ -203,6 +209,26 @@ fn cr2_cfa_phase_is_measured_for_every_row_phase_and_border_parity() { } } +#[test] +fn cr2_untagged_scaled_gradients_keep_model_or_default_layout_and_warning() { + for (model, red_row, expected) in [(None, 0, [0, 1, 1, 2]), (Some(0x8000_0250), 1, [1, 2, 0, 1])] { + for scale in [1u16, 2, 4] { + let mut spec = cr2_phase_spec(expected, 0, 0, model); + spec.borders = None; + spec.data = (0..spec.width * spec.height) + .map(|i| { + let (x, y) = (i % spec.width, i / spec.width); + scale * if (x + y + red_row) & 1 == 1 { 1000 + 8 * x as u16 } else { 500 } + }) + .collect(); + let sensor = decode(&spec.build(), &Limits::default()).unwrap(); + assert_eq!(sensor.cfa.as_ref().unwrap().phase(0, 0), expected, "model={model:?}, scale={scale}"); + assert!(sensor.warnings.iter().any(|w| w.contains("colour filter phase")), "{:?}", sensor.warnings); + assert_eq!(sensor.data, spec.data); + } + } +} + #[test] fn cr2_cfa_phase_falls_back_to_the_model_table() { // A flat black frame gives the measurement nothing to go on. @@ -211,14 +237,15 @@ fn cr2_cfa_phase_falls_back_to_the_model_table() { spec.data.iter_mut().for_each(|v| *v = 512); decode(&spec.build(), &Limits::default()).unwrap() }; - // EOS 7D (Canon model ID 0x80000250): green/blue first. + // EOS 7D (Canon model ID 0x80000250): green/blue first, still an assumed phase. let s = flat(Some(0x8000_0250)); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [1, 2, 0, 1]); - assert!(!s.warnings.iter().any(|w| w.contains("colour filter phase")), "{:?}", s.warnings); + assert!(s.warnings.iter().any(|w| w.contains("colour filter phase")), "{:?}", s.warnings); // Unknown model: red/green first, with a warning. let s = flat(Some(0x8000_0001)); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]); assert!(s.warnings.iter().any(|w| w.contains("colour filter phase")), "{:?}", s.warnings); let s = flat(None); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]); + assert!(s.warnings.iter().any(|w| w.contains("colour filter phase")), "{:?}", s.warnings); } From 1d45e640513136bb7ecd9640d2476e850357039a Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 15 Nov 2026 12:45:47 +0800 Subject: [PATCH 02/14] Adopt the published shared-adapter merge --- Cargo.lock | 72 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 60 ++++++++++++++++++++++----------------------- 2 files changed, 66 insertions(+), 66 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e67b385b688..0d73f35c7ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1323,7 +1323,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "crc32fast", "flate2", @@ -1344,7 +1344,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "rustix 1.1.5", ] @@ -1352,7 +1352,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "md-5", "rayon", @@ -1361,7 +1361,7 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-metadata", "craft-xml", @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "thiserror 2.0.21", ] @@ -1379,17 +1379,17 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-eps", "craft-idml", @@ -1407,7 +1407,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-atomic", "dirs", @@ -1417,12 +1417,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "heic-rs", "rayon", @@ -1431,7 +1431,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1454,7 +1454,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-xml", "craft-zip", @@ -1464,7 +1464,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-heif", "craft-jpeg", @@ -1489,7 +1489,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "thiserror 2.0.21", ] @@ -1497,7 +1497,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-xml", "craft-zip", @@ -1507,7 +1507,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "brotli-decompressor 6.3.1", "chrono", @@ -1519,7 +1519,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-xml", "craft-zip", @@ -1529,7 +1529,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "blake3", "craft-atomic", @@ -1542,7 +1542,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "serde", "serde_json", @@ -1552,7 +1552,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "bytemuck", "flate2", @@ -1566,7 +1566,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1575,7 +1575,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-winprint-gdi", "log", @@ -1589,7 +1589,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "encoding_rs", "flate2", @@ -1600,7 +1600,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "chrono", "craft-crw", @@ -1618,7 +1618,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1635,7 +1635,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "serde", "thiserror 2.0.21", @@ -1644,7 +1644,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1665,7 +1665,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "chrono", "dunce", @@ -1700,7 +1700,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1709,7 +1709,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1719,7 +1719,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3146,7 +3146,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "bytemuck", "hayro-interpret", @@ -3176,7 +3176,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3194,7 +3194,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3218,7 +3218,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=c6e469ea3473ba76574c273c66cdb21a94feb574#c6e469ea3473ba76574c273c66cdb21a94feb574" +source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" dependencies = [ "flate2", "hayro-ccitt", diff --git a/Cargo.toml b/Cargo.toml index fa6b02e376a..56c71b1ac0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,9 +10,9 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["serde"] } # Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119). -craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } # The ArtCraft Launcher's agents switch and app list, shared with the launcher, the MCP gateway and # every Craft app (storytold/craft-ai-integrations#195). Pinned to the head of # storytold/craft-ai-integrations#197 until it merges. @@ -23,11 +23,11 @@ photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -46,31 +46,31 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft-ui. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["egui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -229,7 +229,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7 egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README). -hayro = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c6e469ea3473ba76574c273c66cdb21a94feb574" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } From e88e24cf193e7946f25dc3c7d7d4d7de502329df Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 15 Nov 2026 13:51:48 +0800 Subject: [PATCH 03/14] Migrate SVG omission handling with unified shared adapters --- crates/io/src/svg.rs | 63 ++++-- .../io/src/svg/optional_image_review_tests.rs | 193 ++++++++++++++++++ 2 files changed, 241 insertions(+), 15 deletions(-) create mode 100644 crates/io/src/svg/optional_image_review_tests.rs diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 62aac29008d..c512a303ef1 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -401,6 +401,9 @@ struct Parsed { /// text while parsing, before any node reaches the conversion, so this is the only place /// that knows why the text is missing. fontless_text: bool, + /// Resolution may safely omit hostile/unreadable data URLs; disclose those omissions + /// after conversion, including when editable nodes collapse to one raster layer. + image_usage: craft_svg::tree::ImageUsage, } /// Parses a drawing, `.svgz` included. The XML is inflated and checked here, before the parser @@ -430,6 +433,10 @@ fn tree_limits(depth: usize, raster_pixels: u64) -> craft_svg::tree::Limits { /// [`parse`] with the font database `fonts` supplies (the tests hand in an empty one). fn parse_with(bytes: &[u8], fonts: fn() -> Arc) -> Result { + parse_with_image_limit(bytes, fonts, MAX_RASTER_PIXELS) +} + +fn parse_with_image_limit(bytes: &[u8], fonts: fn() -> Arc, max_image_pixels: u64) -> Result { let xml = inflate(bytes)?; let depth = nesting_depth(&xml, MAX_XML_DEPTH)?; if depth > MAX_XML_DEPTH { @@ -442,20 +449,16 @@ fn parse_with(bytes: &[u8], fonts: fn() -> Arc) -> Resul // re-checks the gzip magic and would decompress a second time without our size limit if // the inflated content happened to start with a nested gzip stream. let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; - let image_resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))); + let image_resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, max_image_pixels))); image_resolver.set_document_depth(depth); parse_at_depth(depth, false, |isolated| { let opt = options_with_isolation(fontdb, MAX_XML_DEPTH.saturating_sub(depth), isolated, Arc::clone(&image_resolver)); - let tree = guarded_parse(|| craft_svg::tree::parse_text(text, &tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS), &opt))?; + let tree = guarded_parse(|| craft_svg::tree::parse_text(text, &tree_limits(MAX_XML_DEPTH, max_image_pixels), &opt))?; let tree = tree.map_err(svg_parse_error)?; - let usage = image_resolver.usage(); - if usage.raster_limit_images > 0 { - return Err(IoError::Svg("embedded SVG raster images exceed the decoded pixel budget".into())); - } - if usage.svg_limit_images > 0 { - return Err(IoError::Svg("embedded SVG images exceed the byte or nesting budget".into())); - } - Ok(Parsed { tree, fontless_text }) + // The resolver already rejects each over-budget optional image before decode. + // Ordinary Open keeps the usable outer drawing, as before the shared-parser + // migration; strict stored previews enforce completeness in their separate path. + Ok(Parsed { tree, fontless_text, image_usage: image_resolver.usage() }) }) .map_err(IoError::from) } @@ -555,9 +558,11 @@ fn parse_image_bounded_with( counter.xml_bytes = counter.xml_bytes.saturating_sub(u64::try_from(usage.embedded_svg_bytes).unwrap_or(u64::MAX)); counter.svg_images = usage.embedded_svg_count as u64; counter.svg_chain = usage.embedded_svg_depth as u64; + // Resource overruns fail bounded renders; non-strict renders may omit a child + // whose XML depth exceeds the allowance left by the outer drawing. if usage.raster_limit_images > 0 { counter.error.get_or_insert_with(|| "embedded SVG raster images exceed the decoded pixel budget".into()); - } else if counter.strict && usage.svg_limit_images > 0 { + } else if usage.svg_resource_limit_images > 0 || (counter.strict && usage.svg_limit_images > 0) { counter.error.get_or_insert_with(|| "embedded SVG images exceed the byte or nesting budget".into()); } else if counter.strict && (usage.invalid_raster_images > 0 || usage.invalid_svg_images > 0) { counter.error.get_or_insert_with(|| "can't parse an embedded SVG image".into()); @@ -690,7 +695,7 @@ fn parse_bounded_work_with(bytes: &[u8], max_pixels: u64, strict: bool, fonts: f let counter = budget.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let decoded = max_pixels.min(MAX_RASTER_PIXELS).saturating_sub(counter.pixels); Ok(ParsedWork { - parsed: Parsed { tree, fontless_text: counter.fontless_text }, + parsed: Parsed { tree, fontless_text: counter.fontless_text, image_usage: counter.resolver.usage() }, svg_images: counter.svg_images, svg_chain: counter.svg_chain, decoded, @@ -984,8 +989,11 @@ fn import_parsed_with_limits( reject_cache_overflow: bool, pixel_budget: u64, ) -> Result { - let Parsed { tree, fontless_text } = parsed; + let Parsed { tree, fontless_text, image_usage } = parsed; let mut warnings = Vec::new(); + if let Some(warning) = omitted_image_warning(image_usage) { + warnings.push(warning); + } if fontless_text { warnings.push("SVG: the text needs a font and none is installed, so it was dropped".to_string()); } @@ -1040,11 +1048,33 @@ fn import_parsed_with_limits( Ok(ImportResult { document: doc, warnings: conv.warnings, source_read_only: false, preview_only: false }) } +/// One count-only warning bounds disclosure independently of the number or length of data URLs. +fn omitted_image_warning(usage: craft_svg::tree::ImageUsage) -> Option { + // svg_resource_limit_images is a subset of svg_limit_images, not another omitted image. + let count = omitted_image_count(usage); + (count != 0).then(|| { + let noun = if count == 1 { "image was" } else { "images were" }; + format!("SVG: {count} embedded {noun} omitted because the data was unreadable or exceeded image limits; the remaining drawing was preserved") + }) +} + +fn omitted_image_count(usage: craft_svg::tree::ImageUsage) -> usize { + usage.raster_limit_images.saturating_add(usage.svg_limit_images).saturating_add(usage.invalid_raster_images).saturating_add(usage.invalid_svg_images) +} + +/// Raster-only callers have no warning channel: never publish silently incomplete pixels. +fn complete_raster_tree(parsed: Parsed) -> Result { + if omitted_image_count(parsed.image_usage) != 0 { + return Err(IoError::Svg("embedded images were unreadable or exceeded image limits; cannot rasterize an incomplete drawing".into())); + } + Ok(parsed.tree) +} + /// The whole drawing rendered at `scale` (1 = its own size), as a straight-alpha RGBA buffer at /// the origin. Smart objects use it to stay sharp at any placement. pub fn rasterize(bytes: &[u8], scale: f32) -> Result { on_svg_stack(|| { - let tree = parse(bytes)?.tree; + let tree = complete_raster_tree(parse(bytes)?)?; rasterize_tree(&tree, scale) }) } @@ -1081,7 +1111,7 @@ fn rasterize_tree(tree: &usvg::Tree, scale: f32) -> Result Result<(u32, u32, Vec), IoError> { on_svg_stack(|| { - let tree = parse(bytes)?.tree; + let tree = complete_raster_tree(parse(bytes)?)?; let cv = canvas(&tree, &mut Vec::new()); let (w, h) = (f64::from(tree.size().width() * cv.scale), f64::from(tree.size().height() * cv.scale)); // The largest k ≤ 1 with (w·k + 2)(h·k + 2) ≤ the limit: `render` rounds each side up, and @@ -1727,3 +1757,6 @@ fn knots(path: &tiny_skia::Path) -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +mod optional_image_review_tests; diff --git a/crates/io/src/svg/optional_image_review_tests.rs b/crates/io/src/svg/optional_image_review_tests.rs new file mode 100644 index 00000000000..fca50c44656 --- /dev/null +++ b/crates/io/src/svg/optional_image_review_tests.rs @@ -0,0 +1,193 @@ +use super::*; +use std::io::Write; + +fn url(mime: &str, bytes: &[u8]) -> String { + let mut value = format!("data:{mime},"); + for byte in bytes { + value.push_str(&format!("%{byte:02X}")); + } + value +} + +fn gzip(bytes: &[u8]) -> Vec { + let mut writer = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + writer.write_all(bytes).unwrap(); + writer.finish().unwrap() +} + +fn drawing(url: &str) -> String { + format!( + "" + ) +} + +fn omission_warnings(imported: &ImportResult) -> Vec<&str> { + imported.warnings.iter().filter(|warning| warning.contains("embedded") && warning.contains("omitted")).map(String::as_str).collect() +} + +fn assert_omission_warning(imported: &ImportResult, count: usize) { + let warnings = omission_warnings(imported); + assert_eq!(warnings.len(), 1, "all omitted references share one bounded warning"); + assert!(warnings[0].starts_with(&format!("SVG: {count} embedded ")), "{}", warnings[0]); + assert!(warnings[0].len() < 256); + assert!(!warnings[0].contains("data:")); +} + +fn oversized_png(seed: u8) -> Vec { + let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![0, seed, 0]).unwrap(); + let mut png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + png[16..20].copy_from_slice(&40_000u32.to_be_bytes()); + png[20..24].copy_from_slice(&40_000u32.to_be_bytes()); + let checksum = crc32fast::hash(&png[12..29]); + png[29..33].copy_from_slice(&checksum.to_be_bytes()); + png +} + +#[test] +fn ordinary_open_preserves_outer_pixels_when_optional_images_exceed_limits_but_previews_refuse() { + let deep = format!( + "{}{}", + "".repeat(MAX_XML_DEPTH + 1), + "".repeat(MAX_XML_DEPTH + 1) + ); + let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![0, 255, 0]).unwrap(); + let mut png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + png[16..20].copy_from_slice(&40_000u32.to_be_bytes()); + png[20..24].copy_from_slice(&40_000u32.to_be_bytes()); + let checksum = crc32fast::hash(&png[12..29]); + png[29..33].copy_from_slice(&checksum.to_be_bytes()); + for source in [url("image/png", &png), url("image/svg+xml", deep.as_bytes()), url("image/svg+xml", &gzip(deep.as_bytes()))] { + let text = drawing(&source); + let imported = crate::import("outer.svg", text.as_bytes()).expect("only the over-budget optional image is omitted"); + let pixel = photocraft_compose::flatten(&imported.document).get(1, 1); + assert_eq!(pixel, [1., 0., 0., 1.], "the valid outer shape survives, and the rejected child is not decoded/drawn"); + assert_omission_warning(&imported, 1); + assert!(import_svg_preview_with_work("strict.svg", text.as_bytes(), MAX_RASTER_PIXELS).is_err(), "stored previews must still draw completely"); + } +} + +#[test] +fn valid_embedded_images_do_not_acquire_omission_warnings() { + let green = ""; + let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![0, 255, 0]).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + for source in [url("image/png", &png), url("image/svg+xml", green.as_bytes()), url("image/svg+xml", &gzip(green.as_bytes()))] { + let text = drawing(&source); + let imported = import_svg_with_group_depth("valid.svg", text.as_bytes(), MAX_GROUP_DEPTH).unwrap(); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [0., 1., 0., 1.]); + assert!(omission_warnings(&imported).is_empty(), "a valid child must not acquire an omission warning"); + import_svg_preview_with_work("valid-preview.svg", text.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + } +} + +#[test] +fn ordinary_open_warns_once_for_embedded_svg_byte_and_chain_limits() { + let green = ""; + let mut oversized = green.as_bytes().to_vec(); + oversized.resize(MAX_BOUNDED_SVG_BYTES as usize + 1, b' '); + let bytes = drawing(&url("image/svg+xml", &gzip(&oversized))); + drop(oversized); + // Compress each level before embedding it; the chain remains tiny rather + // than multiplying a base64 payload, and it reaches the actual chain cap. + let mut chain = green.to_string(); + for _ in 0..=MAX_EMBEDDED_SVG_DEPTH { + chain = drawing(&url("image/svg+xml", &gzip(chain.as_bytes()))); + } + for text in [bytes, chain] { + let imported = crate::import("omitted.svg", text.as_bytes()).unwrap(); + assert_omission_warning(&imported, 1); // The resource counter is a subset, not a second omission. + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); + assert!(import_svg_preview_with_work("strict.svg", text.as_bytes(), MAX_RASTER_PIXELS).is_err()); + let saved = photocraft_format::save_to_bytes(&imported.document, &Default::default()).unwrap(); + let reopened = photocraft_format::load_from_bytes(&saved).unwrap(); + assert_eq!(photocraft_compose::flatten(&reopened).get(1, 1), [1., 0., 0., 1.]); + } +} + +#[test] +fn omitted_image_flood_has_one_bounded_warning_even_in_whole_drawing_fallback() { + let mut text = "".to_string(); + for _ in 0..=MAX_NODES { + text.push_str(""); + } + for seed in 0..64 { + text.push_str(&format!("", url("image/png", &oversized_png(seed)))); + } + text.push_str(""); + let imported = crate::import("flood.svg", text.as_bytes()).unwrap(); + assert_omission_warning(&imported, 64); + assert_eq!(imported.document.layers.len(), 1); + assert!(matches!(imported.document.layers[0].content, LayerContent::Raster(_))); + assert!(imported.warnings.iter().any(|warning| warning.contains("one pixel layer")), "exercise the whole-drawing fallback"); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); +} + +#[test] +fn bounded_non_strict_xml_omission_warns_while_strict_preview_still_refuses() { + let child = format!( + "{}{}", + "".repeat(MAX_XML_DEPTH - 2), + "".repeat(MAX_XML_DEPTH - 2) + ); + let text = format!( + "{}{}", + "".repeat(MAX_XML_DEPTH - 2), + url("image/svg+xml", child.as_bytes()), + "".repeat(MAX_XML_DEPTH - 2) + ); + let imported = import_svg_bounded_images("soft.svg", text.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert_omission_warning(&imported, 1); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); + assert!(import_svg_preview_with_work("strict.svg", text.as_bytes(), MAX_RASTER_PIXELS).is_err()); +} + +#[test] +fn raster_only_callers_reject_small_budget_omissions_while_import_keeps_its_warning() { + fn no_fonts() -> Arc { + Arc::new(usvg::fontdb::Database::new()) + } + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let text = drawing(&url("image/png", &png)); + let parsed = || parse_with_image_limit(text.as_bytes(), no_fonts, 3).unwrap(); + assert_eq!(parsed().image_usage.raster_limit_images, 1, "a valid four-pixel PNG exceeds the three-pixel allowance before decode"); + assert!(matches!(complete_raster_tree(parsed()), Err(IoError::Svg(message)) if message.contains("incomplete drawing"))); + let imported = import_parsed("limited.svg", parsed(), MAX_GROUP_DEPTH, None, false).unwrap(); + assert_omission_warning(&imported, 1); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); + let complete = parse_with_image_limit(text.as_bytes(), no_fonts, 4).unwrap(); + assert_eq!(omitted_image_count(complete.image_usage), 0); + let pixels = rasterize_tree(&complete_raster_tree(complete).unwrap(), 1.).unwrap(); + assert_eq!(pixels.get(1, 1), [0., 1., 0., 1.]); +} + +#[test] +fn raster_only_public_apis_reject_omitted_images_instead_of_returning_partial_pixels() { + let deep = format!( + "{}{}", + "".repeat(MAX_XML_DEPTH + 1), + "".repeat(MAX_XML_DEPTH + 1) + ); + for source in [url("image/png", &oversized_png(0)), url("image/svg+xml", deep.as_bytes()), url("image/png", b"not a PNG")] { + let text = drawing(&source); + assert!(matches!(rasterize(text.as_bytes(), 1.), Err(IoError::Svg(message)) if message.contains("incomplete drawing"))); + assert!(matches!(rasterize_rgba8(text.as_bytes()), Err(IoError::Svg(message)) if message.contains("incomplete drawing"))); + let imported = crate::import("outer.svg", text.as_bytes()).unwrap(); + assert_omission_warning(&imported, 1); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); + } +} + +#[test] +fn raster_only_public_apis_preserve_complete_embedded_image_pixels() { + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let green = ""; + for source in [url("image/png", &png), url("image/svg+xml", green.as_bytes())] { + let text = drawing(&source); + assert_eq!(rasterize(text.as_bytes(), 1.).unwrap().get(1, 1), [0., 1., 0., 1.]); + let (width, height, pixels) = rasterize_rgba8(text.as_bytes()).unwrap(); + assert_eq!((width, height), (2, 2)); + assert_eq!(pixels, [0, 255, 0, 255].repeat(4)); + } +} From 274c99f94dea1c0db1b5a9f0c83a9ebecff199b5 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 15 Nov 2026 15:05:47 +0800 Subject: [PATCH 04/14] Complete shared-format migration and fix RAW/SVG review findings --- crates/format/src/store.rs | 44 ++++++++++++++++++ crates/format/tests/it/directory_symlinks.rs | 10 +++++ crates/format/tests/it/roundtrip.rs | 7 ++- crates/io/src/svg.rs | 2 +- .../io/src/svg/optional_image_review_tests.rs | 4 +- crates/io/src/svg/tests.rs | 45 ++++++++++++------- crates/raw/src/testgen/raf.rs | 4 +- crates/raw/tests/it/raf.rs | 39 ++++++++++++++++ 8 files changed, 135 insertions(+), 20 deletions(-) diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 2b84a4a124d..e1b87e55c90 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -155,10 +155,54 @@ impl ByteSource for ZipSource<'_> { fn bundle_error(error: craft_pcraft_bundle::Error) -> FormatError { match error { craft_pcraft_bundle::Error::LimitExceeded { entry, limit } => FormatError::LimitExceeded(format!("`{entry}` exceeds {limit} bytes")), + craft_pcraft_bundle::Error::Zip(error) if error.is_limit() => FormatError::LimitExceeded(error.to_string()), + craft_pcraft_bundle::Error::Io(message) => FormatError::Io(std::io::Error::other(message)), other => FormatError::corrupt(other.to_string()), } } +#[cfg(test)] +mod bundle_error_tests { + use super::*; + + #[test] + fn shared_io_errors_keep_the_native_io_type_and_message() { + let error = bundle_error(craft_pcraft_bundle::Error::Io("manifest publication failed".into())); + let FormatError::Io(error) = error else { panic!("I/O failure must remain typed") }; + assert_eq!(error.kind(), std::io::ErrorKind::Other); + assert_eq!(error.to_string(), "manifest publication failed"); + } + + #[test] + fn direct_and_nested_zip_limits_remain_limits() { + let error = bundle_error(craft_pcraft_bundle::Error::LimitExceeded { entry: "manifest.json".into(), limit: 16 }); + assert!(matches!(error, FormatError::LimitExceeded(message) if message == "`manifest.json` exceeds 16 bytes")); + for error in [ + craft_zip::Error::TooManyEntries { declared: 3, limit: 2 }, + craft_zip::Error::TooManyEndRecords(2), + craft_zip::Error::EntryTooLarge { name: "manifest.json".into(), limit: 16 }, + craft_zip::Error::BudgetSpent { name: "manifest.json".into(), limit: 16 }, + ] { + let message = error.to_string(); + assert!(matches!(bundle_error(craft_pcraft_bundle::Error::Zip(error)), FormatError::LimitExceeded(found) if found == message)); + } + } + + #[test] + fn malformed_paths_archives_and_hashes_remain_corrupt() { + for error in [ + craft_pcraft_bundle::Error::InvalidPath("../manifest.json".into()), + craft_pcraft_bundle::Error::InvalidBundle("missing manifest".into()), + craft_pcraft_bundle::Error::HashMismatch("tiles/object.zst".into()), + craft_pcraft_bundle::Error::Zip(craft_zip::Error::NotZip("truncated".into())), + craft_pcraft_bundle::Error::Zip(craft_zip::Error::Entry { name: "manifest.json".into(), msg: "checksum".into() }), + ] { + let message = error.to_string(); + assert!(matches!(bundle_error(error), FormatError::Corrupt(found) if found == message)); + } + } +} + pub(crate) struct DirSource { bundle: craft_pcraft_bundle::DirectoryBundle, } diff --git a/crates/format/tests/it/directory_symlinks.rs b/crates/format/tests/it/directory_symlinks.rs index 0a8d7d24626..7061b8d516c 100644 --- a/crates/format/tests/it/directory_symlinks.rs +++ b/crates/format/tests/it/directory_symlinks.rs @@ -19,6 +19,10 @@ fn directory_cleanup_preserves_unrelated_zst_files() { let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + // An empty shared bundle creates object directories only when it writes objects. + // These directories belong to the fixture that plants the files below. + std::fs::create_dir_all(bundle.join("tiles")).unwrap(); + std::fs::create_dir_all(bundle.join("blobs")).unwrap(); let unrelated = bundle.join("tiles/personal-notes.zst"); let orphan = bundle.join("blobs").join(format!("{}.zst", "b".repeat(64))); std::fs::write(&unrelated, b"unrelated file").unwrap(); @@ -64,6 +68,7 @@ mod permissions { let bundle = root.join("project.pcraft"); let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + std::fs::create_dir_all(bundle.join("composite")).unwrap(); let restricted = RestoreMode::set(&bundle.join("composite"), 0o300); let mut changed = empty_doc(); changed.name = "saved without previews".into(); @@ -81,6 +86,8 @@ mod permissions { let link = root.join("linked.pcraft"); let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + std::fs::create_dir_all(bundle.join("composite")).unwrap(); + std::fs::create_dir_all(bundle.join("blobs")).unwrap(); symlink(&bundle, &link).unwrap(); std::fs::write(bundle.join("thumb.png"), b"stale thumbnail").unwrap(); std::fs::write(bundle.join("composite/preview.png"), b"stale composite").unwrap(); @@ -108,6 +115,7 @@ mod permissions { let bundle = root.join("project.pcraft"); let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + std::fs::create_dir_all(bundle.join("composite")).unwrap(); let restricted = RestoreMode::set(&bundle.join("composite"), 0o300); let mut changed = empty_doc(); changed.name = "saved with preview".into(); @@ -127,6 +135,7 @@ mod permissions { let mut writer = PcraftWriter::new(); let original = empty_doc(); writer.save_dir(&original, &bundle, &SaveOptions::default()).unwrap(); + std::fs::create_dir_all(bundle.join("composite")).unwrap(); let preview = bundle.join("composite/preview.png"); std::fs::write(&preview, b"stale composite").unwrap(); let restricted = RestoreMode::set(&bundle.join("composite"), 0o500); @@ -156,6 +165,7 @@ mod permissions { let bundle = root.join("project.pcraft"); let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); + std::fs::create_dir_all(bundle.join("tiles")).unwrap(); let orphan = bundle.join("tiles").join(format!("{}.zst", "d".repeat(64))); std::fs::write(&orphan, b"unreferenced object").unwrap(); let restricted = RestoreMode::set(&bundle.join("tiles"), 0o500); diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index f127291bc69..0cb4b1589eb 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -688,6 +688,9 @@ fn directory_save_rejects_manifest_symlink_without_overwriting_target() { let doc = rich_doc(ColorMode::Rgb, SampleType::U8); let dir = temp_dir("symlink-manifest"); + // The fixture inspects this directory even when preflight refuses the save before any + // object is written; empty bundles no longer create object directories eagerly. + std::fs::create_dir(dir.join("tiles")).unwrap(); let outside = temp_dir("symlink-manifest-outside"); let external_manifest = outside.join("external.json"); std::fs::write(&external_manifest, b"keep manifest").unwrap(); @@ -805,7 +808,7 @@ fn bundles_without_the_full_composite_still_open() { } let older = z.finish().unwrap(); assert_eq!(read_full_composite(&older).unwrap(), None); - // A member that names any other entry is refused, and the document still opens. + // The shared manifest reader refuses a noncanonical full-composite reference. manifest["full_composite"] = serde_json::Value::from("thumb.png"); let mut z = zip::ZipWriter::new(); z.add("manifest.json", &serde_json::to_vec_pretty(&manifest).unwrap()).unwrap(); @@ -814,7 +817,7 @@ fn bundles_without_the_full_composite_still_open() { } let other = z.finish().unwrap(); assert!(read_full_composite(&other).is_err()); - assert_eq!(load_from_bytes(&other).unwrap(), doc); + assert!(matches!(load_from_bytes(&other), Err(FormatError::Corrupt(_)))); assert_eq!(load_from_bytes(&older).unwrap(), load_from_bytes(&bytes).unwrap()); assert_eq!(load_from_bytes(&older).unwrap(), doc); // A save without it writes no member at all, as older writers did. diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index c512a303ef1..9b2d311de47 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -1083,7 +1083,7 @@ pub fn rasterize(bytes: &[u8], scale: f32) -> Result Result { on_svg_stack(|| { let (parsed, chain) = parse_bounded_inner(bytes, max_decoded_pixels)?; - let tree = parsed.tree; + let tree = complete_raster_tree(parsed)?; if chain != 0 { let cv = canvas(&tree, &mut Vec::new()); let k = cv.scale * scale.clamp(1.0 / 64.0, 64.0); diff --git a/crates/io/src/svg/optional_image_review_tests.rs b/crates/io/src/svg/optional_image_review_tests.rs index fca50c44656..51a63a0f996 100644 --- a/crates/io/src/svg/optional_image_review_tests.rs +++ b/crates/io/src/svg/optional_image_review_tests.rs @@ -172,6 +172,7 @@ fn raster_only_public_apis_reject_omitted_images_instead_of_returning_partial_pi let text = drawing(&source); assert!(matches!(rasterize(text.as_bytes(), 1.), Err(IoError::Svg(message)) if message.contains("incomplete drawing"))); assert!(matches!(rasterize_rgba8(text.as_bytes()), Err(IoError::Svg(message)) if message.contains("incomplete drawing"))); + assert!(rasterize_bounded(text.as_bytes(), 1., MAX_RASTER_PIXELS).is_err(), "bounded rasterization must also refuse omitted images"); let imported = crate::import("outer.svg", text.as_bytes()).unwrap(); assert_omission_warning(&imported, 1); assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); @@ -183,9 +184,10 @@ fn raster_only_public_apis_preserve_complete_embedded_image_pixels() { let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); let green = ""; - for source in [url("image/png", &png), url("image/svg+xml", green.as_bytes())] { + for source in [url("image/png", &png), url("text/plain", &png), url("image/svg+xml", green.as_bytes())] { let text = drawing(&source); assert_eq!(rasterize(text.as_bytes(), 1.).unwrap().get(1, 1), [0., 1., 0., 1.]); + assert_eq!(rasterize_bounded(text.as_bytes(), 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [0., 1., 0., 1.]); let (width, height, pixels) = rasterize_rgba8(text.as_bytes()).unwrap(); assert_eq!((width, height), (2, 2)); assert_eq!(pixels, [0, 255, 0, 255].repeat(4)); diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 2fe64fbd877..a8149bfb489 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -931,27 +931,42 @@ fn bounded_svg_rejects_nested_gzip_at_top_level_and_inside_data_urls() { /// An embedded image the bounded resolver can't charge (an unknown MIME type, a format resvg /// doesn't draw, a PNG under another MIME type, a corrupt PNG) is left out as usvg's own -/// resolver leaves it out, and the rest of the drawing still renders. +/// resolver leaves it out. Import preserves the rest with a warning; warningless rasterization +/// must reject the incomplete drawing. #[test] fn unreadable_embedded_images_are_left_out_and_the_drawing_still_renders() { let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap(); let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - for (mime, bytes) in [ - ("image/x-foo", png.clone()), - ("application/octet-stream", png.clone()), - ("application/octet-stream", png_dimensions(6000, 5000)), - ("image/png", png_dimensions(0, 4)), - ("image/bmp", b"BM\0\0\0\0".to_vec()), - ("image/png", png[..20].to_vec()), - ] { + for (mime, bytes) in + [("image/x-foo", png.clone()), ("image/png", png_dimensions(0, 4)), ("image/bmp", b"BM\0\0\0\0".to_vec()), ("image/png", png[..20].to_vec())] + { let svg = format!( "{}", embedded_image(mime, &bytes) ); - let buf = rasterize_bounded(svg.as_bytes(), 1.0, MAX_RASTER_PIXELS).unwrap_or_else(|e| panic!("{mime}: {e}")); - let at = |x: usize, y: usize| buf.px[y * 4 + x]; - assert!(at(3, 1)[0] > 0.99 && at(3, 1)[3] > 0.99, "{mime}: the rect still draws"); - assert!(import_svg_bounded("clipboard", svg.as_bytes(), MAX_RASTER_PIXELS).is_ok(), "{mime}"); + assert!(rasterize_bounded(svg.as_bytes(), 1.0, MAX_RASTER_PIXELS).is_err(), "{mime}: incomplete pixels need a warning channel"); + let imported = import_svg_bounded("clipboard", svg.as_bytes(), MAX_RASTER_PIXELS).unwrap_or_else(|e| panic!("{mime}: {e}")); + let pixel = photocraft_compose::flatten(&imported.document).get(3, 1); + assert!(pixel[0] > 0.99 && pixel[3] > 0.99, "{mime}: the rect still draws"); + assert!(imported.warnings.iter().any(|warning| warning.contains("embedded") && warning.contains("omitted")), "{mime}: the loss is disclosed"); + } +} + +#[test] +fn non_image_data_urls_remain_ignored_without_decoding() { + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + for bytes in [png, png_dimensions(6000, 5000)] { + let svg = format!( + "{}", + embedded_image("application/octet-stream", &bytes) + ); + // The resolver ignores non-image media types before decoding. They do not count as + // failed declared images, even when their bytes resemble an oversized PNG. + let buf = rasterize_bounded(svg.as_bytes(), 1.0, MAX_RASTER_PIXELS).unwrap(); + assert_eq!(buf.get(3, 1), [1., 0., 0., 1.]); + let imported = import_svg_bounded("clipboard", svg.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert!(!imported.warnings.iter().any(|warning| warning.contains("embedded") && warning.contains("omitted"))); } } @@ -1000,8 +1015,8 @@ fn bounded_embedded_svg_gets_only_the_nesting_depth_the_drawing_left() { .stack_size(1 << 20) .spawn(move || { let deep = embed(MAX_XML_DEPTH - 2, MAX_XML_DEPTH - 2); - let buf = rasterize_bounded(deep.as_bytes(), 1.0, MAX_RASTER_PIXELS).unwrap(); - assert!(buf.px[4 * 8 + 4][3] < 0.01, "the too-deep image is left out"); + assert!(omitted_image_count(parse_bounded(deep.as_bytes(), MAX_RASTER_PIXELS).unwrap().image_usage) > 0, "the too-deep image is left out"); + assert!(rasterize_bounded(deep.as_bytes(), 1.0, MAX_RASTER_PIXELS).is_err(), "incomplete pixels need a warning channel"); let fine = embed(200, 200); let buf = rasterize_bounded(fine.as_bytes(), 1.0, MAX_RASTER_PIXELS).unwrap(); assert!(buf.px[4 * 8 + 4][3] > 0.99, "within the shared budget the image draws"); diff --git a/crates/raw/src/testgen/raf.rs b/crates/raw/src/testgen/raf.rs index 6d34d4f9a9b..0ccdbf0b110 100644 --- a/crates/raw/src/testgen/raf.rs +++ b/crates/raw/src/testgen/raf.rs @@ -191,7 +191,7 @@ impl RafSpec { let u32b = |v: u32| if le { v.to_le_bytes() } else { v.to_be_bytes() }; let strip = self.strip(); let strip_at = 2048u32; - let entries: Vec<(u16, Vec)> = vec![ + let mut entries: Vec<(u16, Vec)> = vec![ (0xF001, vec![self.width as u32]), (0xF002, vec![self.height as u32]), (0xF003, vec![self.bits]), @@ -206,6 +206,8 @@ impl RafSpec { .chain(matches!(self.packing, RafPacking::Words14).then(|| (0xF006, vec![1]))) .chain(self.wb_grb.map(|w| (0xF00E, w.to_vec()))) .collect(); + // TIFF directories require ascending tags, including optional packing fields. + entries.sort_unstable_by_key(|(tag, _)| *tag); let mut out = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; out.extend_from_slice(&u32b(8)); // IFD0: one entry, 0xF000 (type IFD) → the Fuji IFD at 26. diff --git a/crates/raw/tests/it/raf.rs b/crates/raw/tests/it/raf.rs index 1c50c75449d..7ffcb349e25 100644 --- a/crates/raw/tests/it/raf.rs +++ b/crates/raw/tests/it/raf.rs @@ -32,6 +32,45 @@ fn every_storage_decodes_exactly() { const SMALL_ROW_VALUES: [u16; 16] = [0, 1, 0x3FFF, 0x2000, 0x1234, 42, 255, 0x1555, 0x2AAA, 2, 0x3FFE, 4096, 8191, 1023, 7, 37]; +#[test] +fn generated_raw_ifd_tags_are_strictly_ascending() { + let specs = [ + xtrans(RafPacking::U16 { le: true }, 14), + xtrans(RafPacking::U16 { le: false }, 16), + xtrans(RafPacking::Lsb12, 12), + xtrans(RafPacking::Words14, 14), + compressed(&XTRANS, 14, false), + compressed(&XTRANS, 14, true), + ]; + for mut spec in specs { + for wb in [None, Some([302, 604, 453])] { + spec.wb_grb = wb; + let bytes = spec.build(); + let region_at = u32::from_be_bytes(bytes[100..104].try_into().unwrap()) as usize; + let region = &bytes[region_at..]; + let le = ®ion[..2] == b"II"; + let word = |at| { + let bytes = region[at..at + 2].try_into().unwrap(); + if le { u16::from_le_bytes(bytes) } else { u16::from_be_bytes(bytes) } + }; + let long = |at| { + let bytes = region[at..at + 4].try_into().unwrap(); + if le { u32::from_le_bytes(bytes) } else { u32::from_be_bytes(bytes) } + }; + // Follow the serialized TIFF pointers independently of the decoder. + let ifd0 = long(4) as usize; + assert_eq!(word(ifd0), 1); + assert_eq!(word(ifd0 + 2), 0xF000); + let raw_ifd = long(ifd0 + 10) as usize; + let tags: Vec<_> = (0..usize::from(word(raw_ifd))).map(|i| word(raw_ifd + 2 + 12 * i)).collect(); + assert!(tags.windows(2).all(|pair| pair[0] < pair[1]), "{:?}, WB {wb:?}: {tags:X?}", spec.packing); + assert_eq!(tags.contains(&0xF005), spec.packing == RafPacking::Words14); + assert_eq!(tags.contains(&0xF006), spec.packing == RafPacking::Words14); + assert_eq!(tags.contains(&0xF00E), wb.is_some()); + } + } +} + #[test] fn small_word_packed_rows_decode_exactly() { // Eight 14-bit samples need four words per row. At two rows this has the From 0f7433b5a23b5d78badb23dbf35f14dfbdc434cb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 04:10:06 -0500 Subject: [PATCH 05/14] fix(svg): preserve smart artwork with explicit omission warnings --- crates/engine/src/cmd/file_cmds/open.rs | 5 +-- .../engine/src/cmd/file_cmds/place_steps.rs | 23 ++++++++++-- crates/engine/src/cmd/smart_cmds.rs | 2 +- crates/engine/src/cmd/smart_cmds/rendering.rs | 35 +++++++++++++++++-- .../src/cmd/smart_cmds/tests/svg_profile.rs | 12 +++++++ crates/engine/src/cmd/smart_svg_cmds.rs | 14 ++++++-- crates/engine/src/cmd/smart_svg_cmds/tests.rs | 4 ++- crates/io/src/svg.rs | 16 +++++++-- crates/io/tests/it/svg.rs | 11 ++++++ 9 files changed, 108 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index a6adfed3739..959ff3a15b5 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -460,6 +460,7 @@ impl PlaceInput { /// A place decoded, flattened and fitted, ready to be inserted by [`apply_place`]. pub(crate) struct Prepared { + pub(super) warnings: Vec, pub(super) content: LayerContent, pub(super) layer_name: String, /// The history step's name. @@ -473,7 +474,7 @@ pub(crate) struct Prepared { /// Insert the prepared layer as one undo step and report the place. Runs on the session's thread. pub(crate) fn apply_place(s: &mut Session, p: Prepared) -> Result { - let Prepared { content, layer_name, label, scale, bounds, smart, frame } = p; + let Prepared { warnings, content, layer_name, label, scale, bounds, smart, frame } = p; let layer = Layer::new(layer_name, content); let id = layer.id; s.edit(label, move |doc, active| { @@ -486,7 +487,7 @@ pub(crate) fn apply_place(s: &mut Session, p: Prepared) -> Result { } Ok(()) })?; - Ok(json!({"layer": id.0, "frame": frame.map(|f| f.0), "scale": scale * 100.0, "bounds": bounds, "smartObject": smart})) + Ok(json!({"layer": id.0, "frame": frame.map(|f| f.0), "scale": scale * 100.0, "bounds": bounds, "smartObject": smart, "warnings": warnings})) } pub(super) fn place(s: &mut Session, p: &Value, linked: bool) -> Result { diff --git a/crates/engine/src/cmd/file_cmds/place_steps.rs b/crates/engine/src/cmd/file_cmds/place_steps.rs index f449eaee8ad..f4e49a67ce0 100644 --- a/crates/engine/src/cmd/file_cmds/place_steps.rs +++ b/crates/engine/src/cmd/file_cmds/place_steps.rs @@ -33,6 +33,7 @@ pub(crate) struct PlaceSteps { stage: Stage, /// Where the placed image lands, known once it is decoded. plan: Plan, + warnings: Vec, } #[derive(Clone, Copy, Default)] @@ -63,7 +64,7 @@ impl PlaceSteps { /// `fine` cuts the work into pieces of a few milliseconds, as a session without worker /// threads needs; without it each stage is one unit of work. pub(crate) fn new(input: PlaceInput, fine: bool) -> Self { - Self { input, bytes: Arc::new(Vec::new()), fine, stage: Stage::Decode, plan: Plan::default() } + Self { input, bytes: Arc::new(Vec::new()), fine, stage: Stage::Decode, plan: Plan::default(), warnings: Vec::new() } } /// An import error as the engine reports it: a cancel stays one and a refused memory budget @@ -157,6 +158,7 @@ impl PlaceSteps { self.input.name ))); } + self.warnings = imported.warnings; let src = imported.document; let (w, h) = (src.size.width as f64, src.size.height as f64); let (cw, ch) = self.input.canvas; @@ -252,7 +254,13 @@ impl PlaceSteps { if let Some(doc) = &input.doc { ctx.progress(0.9, "Rendering"); ctx.check()?; - if let Some(sharp) = crate::smart_cmds::render(doc, &so)? { + let (sharp, warnings) = crate::smart_cmds::render_with_warnings(doc, &so)?; + for warning in warnings { + if !self.warnings.contains(&warning) { + self.warnings.push(warning); + } + } + if let Some(sharp) = sharp { so.cache = Some(sharp); } } @@ -264,7 +272,16 @@ impl PlaceSteps { let px = px.ok_or_else(|| EngineError::Other(format!("{}: a frame's image must be a smart object", input.name)))?; LayerContent::Raster(px) }; - Ok(Prepared { content, layer_name: stem(&input.name), label, scale, bounds, smart, frame: input.frame.as_ref().map(|(id, _)| *id) }) + Ok(Prepared { + warnings: std::mem::take(&mut self.warnings), + content, + layer_name: stem(&input.name), + label, + scale, + bounds, + smart, + frame: input.frame.as_ref().map(|(id, _)| *id), + }) } } diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index 5832fb5df9a..4140b347726 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -198,10 +198,10 @@ pub use placing::{layer_to_smart, layers_to_smart, placement}; #[cfg(test)] pub(crate) use rendering::DISPLAY_NATIVE_HASH_BYTES; use rendering::refresh_or_fail; -pub(crate) use rendering::source_box; #[cfg(test)] use rendering::{NativeDigests, blend_surfaces, place, render_in}; pub use rendering::{apply_smart_filters, purge_stack_cache, refresh, refresh_layer, render, render_below_filter, stack_cache_bytes, stack_image}; +pub(crate) use rendering::{render_with_warnings, source_box}; #[cfg(test)] use source::svg_source_image_in; pub use source::{SourceImage, purge_source_cache, source_bytes, source_cache_bytes, source_decode_count, source_image, svg_source_image}; diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index 5102e728f87..41901ad97f3 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -175,12 +175,16 @@ fn apply_smart_filter(f: &SmartFilter, sm: &SmartObject, cur: &Surface, canvas: /// The source placed in document pixels, before any smart filter. pub(super) fn place(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject) -> Result { + place_with_svg(name, bytes, doc, sm, &mut |bytes, scale| svg_source_image_in(bytes, doc, scale)) +} + +fn place_with_svg(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject, svg: &mut impl FnMut(&[u8], f64) -> Result) -> Result { let fmt = doc.pixel_format(); // A vector source is rendered at the placement's scale, and the placement is divided by // that scale so the rendered pixels land where the source units would. if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::svg::is_svg(bytes) { let k = vector_scale(sm); - let img = svg_source_image_in(bytes, doc, k)?; + let img = svg(bytes, k)?; return Ok(match &sm.perspective { Some(p) => { let [h0, h1, h2, h3, h4, h5, h6, h7, h8] = *p; @@ -198,7 +202,7 @@ pub(super) fn place(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject) } let img = match sm.stack_mode { Some(mode) if photocraft_io::svg::is_svg(bytes) => convert_svg_source(stack_image(name, bytes, PixelFormat::RGBA32F, mode)?, doc)?, - None if photocraft_io::svg::is_svg(bytes) => svg_source_image_in(bytes, doc, 1.0)?, + None if photocraft_io::svg::is_svg(bytes) => svg(bytes, 1.0)?, Some(mode) => stack_image(name, bytes, fmt, mode)?, None => source_image(name, bytes, fmt)?, }; @@ -319,6 +323,33 @@ pub fn render(doc: &Document, sm: &SmartObject) -> Result> { render_in(doc, sm, &JobCtx::new()) } +/// Command-only rendering that retains usable SVG artwork and reports omitted embedded images. +/// It deliberately bypasses both source and filter-stage caches: a later warningless render +/// must not accidentally reuse an incomplete surface. Native previews remain strict. +pub(crate) fn render_with_warnings(doc: &Document, sm: &SmartObject) -> Result<(Option, Vec)> { + let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok((None, Vec::new())) }; + if !photocraft_io::svg::is_svg(&bytes) || sm.vector_preview.is_some() || sm.stack_mode.is_some() { + return render(doc, sm).map(|surface| (surface, Vec::new())); + } + if !unapplied_filters(sm).is_empty() { + return Err(other("the smart object has unsupported visible filters")); + } + let mut warnings = Vec::new(); + let placed = place_with_svg(&name, &bytes, doc, sm, &mut |bytes, scale| { + let (buf, omitted) = photocraft_io::svg::rasterize_bounded_with_warnings(bytes, scale as f32, 24_000_000) + .map_err(|e| other(format!("can't render the SVG smart object: {e}")))?; + warnings.extend(omitted); + // Preserve the normal renderer's exact built-in sRGB fast path. + let profile = crate::color_cmds::document_profile(doc); + if doc.mode == photocraft_color::ColorMode::Rgb && profile.to_bytes().as_ref() == craft_cms::Builtin::Srgb.profile().to_bytes().as_ref() { + return Ok(SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, doc.pixel_format())), bounds: buf.rect }); + } + let source = SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, PixelFormat::RGBA32F)), bounds: buf.rect }; + convert_svg_source(source, doc) + })?; + Ok((Some(apply_smart_filters(&placed, sm, doc.bounds())?), warnings)) +} + /// [`render`], reporting progress per smart filter to `ctx` and stopping between filters once it /// is cancelled. Gives the same pixels as [`apply_smart_filters`] on the placed source, but /// starts from the deepest stage of the stack already rendered (see [`stack_cache`]). diff --git a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs index ada335953fa..3ca0dce9ca6 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs @@ -96,9 +96,12 @@ fn svg_with_an_unreadable_embedded_image_still_places() { let mut s = Session::new(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); let placed = crate::file_cmds::place_bytes(&mut s, "Logo.svg", svg.as_bytes().to_vec(), None, &json!({"smartObject": true})).unwrap(); + assert!(placed["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("embedded image was omitted"))); let doc = &s.active().unwrap().doc; let LayerContent::Smart(sm) = &doc.layer(LayerId(placed["layer"].as_u64().unwrap())).unwrap().content else { panic!("smart") }; assert_eq!(sm.cache.as_ref().unwrap().rgba(6, 4), [1.0, 0.0, 0.0, 1.0]); + // A warning-bearing command must not poison the strict source/filter caches. + assert!(render(doc, sm).is_err()); } /// Warp setup needs only the source frame, found with the bounded parse and the exact canvas @@ -142,7 +145,13 @@ fn svg_smart_render_cache_tracks_destination_profile_and_transform() { linear.icc_profile = Some(Builtin::LinearSrgb.profile().to_bytes()); let mut smart = SmartObject::new(SmartSource::Embedded { file_name: "clipboard.svg".into(), bytes: Arc::new(SVG.to_vec()) }, Affine::IDENTITY, None); let original = render(&srgb, &smart).unwrap().unwrap(); + let (reported, warnings) = render_with_warnings(&srgb, &smart).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(reported.unwrap(), original, "warning-bearing sRGB parity"); let corrected = render(&linear, &smart).unwrap().unwrap(); + let (reported, warnings) = render_with_warnings(&linear, &smart).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(reported.unwrap(), corrected, "warning-bearing ICC parity"); assert!((original.pixel(3, 3)[0] - 128.0 / 255.0).abs() < 0.01); assert!((corrected.pixel(3, 3)[0] - 0.216).abs() < 0.01, "linear profile at {depth}-bit"); assert_eq!(render(&srgb, &smart).unwrap().unwrap(), original, "profile-specific placed cache"); @@ -153,6 +162,9 @@ fn svg_smart_render_cache_tracks_destination_profile_and_transform() { let bounds = [0.0, 0.0, 8.0, 8.0]; smart.warp = Some(photocraft_geom::warp::Warp::custom(photocraft_geom::warp::BezierMesh::identity(bounds, 1, 1), bounds)); let warped = render(&linear, &smart).unwrap().unwrap(); + let (reported, warnings) = render_with_warnings(&linear, &smart).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(reported.unwrap(), warped, "warning-bearing warp parity"); assert!((warped.pixel(10, 8)[0] - corrected.pixel(3, 3)[0]).abs() < 0.01, "warp must keep corrected colours"); linear.layers = vec![Layer::new("Saved SVG", LayerContent::Smart(smart.clone()))]; let saved = encode_source(&linear).unwrap(); diff --git a/crates/engine/src/cmd/smart_svg_cmds.rs b/crates/engine/src/cmd/smart_svg_cmds.rs index f84c16d5ab6..ca42123a08a 100644 --- a/crates/engine/src/cmd/smart_svg_cmds.rs +++ b/crates/engine/src/cmd/smart_svg_cmds.rs @@ -327,6 +327,7 @@ fn update_contents_with_frame_budget(s: &mut Session, p: &Value, native: bool, f let import = if native { photocraft_io::svg::import_svg_preview_with_work } else { photocraft_io::svg::import_svg_bounded_with_work }; let (imported, _) = import(&name, svg.as_bytes(), 4 * MAX_PIXELS).map_err(|error| bad(UPDATE, format!("can't import edited SVG contents: {error}")))?; let size = imported.document.size; + let mut warnings = imported.warnings; if native { // Shared instances normally borrow one immutable source and preview allocation. The // check is pure in those bytes and the claimed hash, so run it once per identity while @@ -399,8 +400,15 @@ fn update_contents_with_frame_budget(s: &mut Session, p: &Value, native: bool, f let LayerContent::Smart(rendered) = display.content else { return Err(EngineError::NoLayer(display.id)) }; let LayerContent::Smart(sm) = &mut replacement.content else { return Err(EngineError::NoLayer(replacement.id)) }; sm.cache = rendered.cache; - } else if !crate::smart_cmds::refresh_layer(doc, replacement)? { - return Err(bad(UPDATE, "SVG contents could not be rendered")); + } else { + let LayerContent::Smart(sm) = &mut replacement.content else { return Err(EngineError::NoLayer(replacement.id)) }; + let (surface, omitted) = crate::smart_cmds::render_with_warnings(doc, sm)?; + sm.cache = Some(surface.ok_or_else(|| bad(UPDATE, "SVG contents could not be rendered"))?); + for warning in omitted { + if !warnings.contains(&warning) { + warnings.push(warning); + } + } } crate::smart_cmds::detach_psd(replacement); } @@ -411,7 +419,7 @@ fn update_contents_with_frame_budget(s: &mut Session, p: &Value, native: bool, f } Ok(()) })?; - Ok(json!({"layer":id.0,"contentsId":contents.0,"fingerprint":blake3::hash(&replacement_bytes).to_hex().to_string(),"updated":true})) + Ok(json!({"layer":id.0,"contentsId":contents.0,"fingerprint":blake3::hash(&replacement_bytes).to_hex().to_string(),"updated":true,"warnings":warnings})) } /// Menu-less export/update commands the shell uses for external editor save-back; none is diff --git a/crates/engine/src/cmd/smart_svg_cmds/tests.rs b/crates/engine/src/cmd/smart_svg_cmds/tests.rs index 18963ce374f..5945470a0ff 100644 --- a/crates/engine/src/cmd/smart_svg_cmds/tests.rs +++ b/crates/engine/src/cmd/smart_svg_cmds/tests.rs @@ -422,7 +422,9 @@ fn saved_svg_with_an_unreadable_embedded_image_still_updates() { let (mut s, id) = session(8); let edited = r#""#; let params = request(&mut s, id, edited); - assert_eq!(s.execute(UPDATE, params).unwrap()["updated"], true); + let result = s.execute(UPDATE, params).unwrap(); + assert_eq!(result["updated"], true); + assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("embedded image was omitted"))); assert_eq!(source(&s, id), edited.as_bytes()); } diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 9b2d311de47..46aefc99ac1 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -1081,9 +1081,21 @@ pub fn rasterize(bytes: &[u8], scale: f32) -> Result Result { + rasterize_bounded_mode(bytes, scale, max_decoded_pixels, true).map(|(pixels, _)| pixels) +} + +/// Bounded rendering for commands that report omissions to the user. Unlike the warningless +/// APIs, this preserves the readable drawing and returns a bounded, count-only warning. +/// Callers must surface the warnings and must not cache these pixels in strict render caches. +pub fn rasterize_bounded_with_warnings(bytes: &[u8], scale: f32, max_decoded_pixels: u64) -> Result<(photocraft_compose::Buffer, Vec), IoError> { + rasterize_bounded_mode(bytes, scale, max_decoded_pixels, false) +} + +fn rasterize_bounded_mode(bytes: &[u8], scale: f32, max_decoded_pixels: u64, strict: bool) -> Result<(photocraft_compose::Buffer, Vec), IoError> { on_svg_stack(|| { let (parsed, chain) = parse_bounded_inner(bytes, max_decoded_pixels)?; - let tree = complete_raster_tree(parsed)?; + let warnings = omitted_image_warning(parsed.image_usage).into_iter().collect(); + let tree = if strict { complete_raster_tree(parsed)? } else { parsed.tree }; if chain != 0 { let cv = canvas(&tree, &mut Vec::new()); let k = cv.scale * scale.clamp(1.0 / 64.0, 64.0); @@ -1092,7 +1104,7 @@ pub fn rasterize_bounded(bytes: &[u8], scale: f32, max_decoded_pixels: u64) -> R check_scratch_surfaces(u64::from(width) * u64::from(height), chain, max_decoded_pixels) .map_err(|_| IoError::Svg("embedded SVG intermediate images exceed the rendered pixel budget".into()))?; } - rasterize_tree(&tree, scale) + Ok((rasterize_tree(&tree, scale)?, warnings)) }) } diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index 5e0f2f3ee4e..e8e8e90a710 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -814,3 +814,14 @@ fn image_hrefs_to_local_files_are_never_read() { LayerContent::Raster(_) )); } + +#[test] +fn warning_bearing_raster_preserves_readable_artwork_without_relaxing_strict_api() { + let bytes = br##""##; + let (pixels, warnings) = svg::rasterize_bounded_with_warnings(bytes, 1.0, 24_000_000).unwrap(); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("embedded image was omitted")); + assert_eq!(pixels.px[4 * 8 + 6], [1.0, 0.0, 0.0, 1.0]); + assert!(svg::rasterize_bounded(bytes, 1.0, 24_000_000).is_err()); + assert!(svg::rasterize(bytes, 1.0).is_err()); +} From 5d5b584814bf594c1a5e9b5ca822905647a41f33 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 04:13:18 -0500 Subject: [PATCH 06/14] test(svg): cover filtered warning path and strict cache isolation --- .../src/cmd/smart_cmds/tests/svg_profile.rs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs index 3ca0dce9ca6..e43f51a4f23 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs @@ -176,3 +176,28 @@ fn svg_smart_render_cache_tracks_destination_profile_and_transform() { assert!((rerendered.pixel(10, 8)[0] - corrected.pixel(3, 3)[0]).abs() < 0.01, "saved source keeps ICC and warp"); } } + +#[test] +fn warning_bearing_svg_render_keeps_visible_filters_without_poisoning_strict_cache() { + let clean = br##""##; + let omitted = br##""##; + let s = session(8); + let doc = &s.active().unwrap().doc; + let mut smart = SmartObject::new(SmartSource::Embedded { file_name: "Artwork.svg".into(), bytes: Arc::new(clean.to_vec()) }, Affine::IDENTITY, None); + let unfiltered = render(doc, &smart).unwrap().unwrap(); + smart.smart_filters.push(SmartFilter { + command: "filter.blur.gaussianBlur".into(), + params: json!({"radius": 2}), + blend: BlendMode::Normal, + opacity: 1.0, + visible: true, + }); + let expected = render(doc, &smart).unwrap().unwrap(); + assert_ne!(expected, unfiltered, "the visible filter must actually change pixels"); + smart.source = SmartSource::Embedded { file_name: "Artwork.svg".into(), bytes: Arc::new(omitted.to_vec()) }; + let (actual, warnings) = render_with_warnings(doc, &smart).unwrap(); + assert_eq!(actual.unwrap(), expected); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("embedded image was omitted")); + assert!(render(doc, &smart).is_err(), "warning-bearing filter results must not enter strict caches"); +} From 19aec5eb44131de44361189d64910e7b3e19e57c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 05:52:29 -0500 Subject: [PATCH 07/14] fix(svg): surface omission warnings and keep cached renders strict --- crates/engine/src/cmd/smart_cmds.rs | 4 +++- .../src/cmd/smart_cmds/tests/svg_profile.rs | 24 +++++++++++++++++++ crates/io/src/svg.rs | 17 ++++++++++++- .../io/src/svg/optional_image_review_tests.rs | 22 +++++++++++++++++ crates/ui-egui/src/file_open.rs | 1 + crates/ui-egui/src/file_open/tests.rs | 11 +++++++++ crates/ui-egui/src/jobs_ui.rs | 1 + crates/ui-egui/src/jobs_ui/tests.rs | 12 ++++++++++ crates/ui-egui/src/notices.rs | 5 ++++ crates/ui-egui/src/smart_svg_ui.rs | 1 + crates/ui-egui/src/smart_svg_ui/tests.rs | 12 ++++++++++ 11 files changed, 108 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index 4140b347726..7b51d641843 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -71,7 +71,9 @@ pub fn encode_source(doc: &Document) -> Result> { /// Decodes smart-object contents (a `.pcraft` bundle, PSD/PSB, or any flat image format). pub fn decode_source(file_name: &str, bytes: &[u8]) -> Result { if photocraft_io::svg::is_svg(bytes) { - return photocraft_io::svg::import_svg_bounded_images(file_name, bytes, 24_000_000) + // This API has no warning channel. Stack/source caches and contents edits must not + // turn a partial SVG import into silently complete smart-object contents. + return photocraft_io::svg::import_svg_bounded_images_strict(file_name, bytes, 24_000_000) .map(|imported| imported.document) .map_err(|e| other(format!("can't read SVG smart object contents: {e}"))); } diff --git a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs index e43f51a4f23..c7bb5eb22a8 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs @@ -201,3 +201,27 @@ fn warning_bearing_svg_render_keeps_visible_filters_without_poisoning_strict_cac assert!(warnings[0].contains("embedded image was omitted")); assert!(render(doc, &smart).is_err(), "warning-bearing filter results must not enter strict caches"); } + +/// Warningless layered decoding must not cache the partial pixels that warning-bearing File +/// Open is allowed to expose. Repeated calls exercise both source and Stack Mode cache paths. +#[test] +fn svg_stack_and_source_caches_refuse_omitted_images() { + for href in ["data:image/x-foo,abc", "data:image/png;base64,not-base64", "data:image/png;base64"] { + let svg = format!( + r##""## + ); + let imported = photocraft_io::svg::import_svg_bounded_images("Omitted.svg", svg.as_bytes(), 24_000_000).unwrap(); + assert!(imported.warnings.iter().any(|w| w.contains("embedded image was omitted"))); + for _ in 0..2 { + assert!(decode_source("Omitted.svg", svg.as_bytes()).is_err()); + assert!(source_image("Omitted.svg", svg.as_bytes(), PixelFormat::RGBA32F).is_err()); + assert!(stack_image("Omitted.svg", svg.as_bytes(), PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).is_err()); + } + let s = session(8); + let mut smart = SmartObject::new(SmartSource::Embedded { file_name: "Omitted.svg".into(), bytes: Arc::new(svg.into_bytes()) }, Affine::IDENTITY, None); + smart.stack_mode = Some(photocraft_doc::StackMode::Mean); + assert!(render(&s.active().unwrap().doc, &smart).is_err()); + assert!(render_with_warnings(&s.active().unwrap().doc, &smart).is_err(), "Stack Mode must not suppress layered import omissions"); + } + assert!(stack_image("Complete.svg", SVG, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).is_ok()); +} diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 46aefc99ac1..e28779baef4 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -452,6 +452,7 @@ fn parse_with_image_limit(bytes: &[u8], fonts: fn() -> Arc Result { + on_svg_stack(|| { + let parsed = parse_bounded(bytes, max_decoded_pixels)?; + if omitted_image_count(parsed.image_usage) != 0 { + return Err(IoError::Svg("embedded images were unreadable or exceeded image limits; cannot import incomplete smart object contents".into())); + } + import_parsed(name, parsed, MAX_GROUP_DEPTH, None, false) + }) +} + /// The pixel bounds [`import_svg_bounded`] gives the drawing, found without rendering any layer /// cache. It applies the same bounded parse (decoded-image and nested-SVG budgets) and the same /// canvas limit, so a canvas of exactly `max_cached_pixels` (at most 24 MP) fits and one more diff --git a/crates/io/src/svg/optional_image_review_tests.rs b/crates/io/src/svg/optional_image_review_tests.rs index 51a63a0f996..d670ec28459 100644 --- a/crates/io/src/svg/optional_image_review_tests.rs +++ b/crates/io/src/svg/optional_image_review_tests.rs @@ -193,3 +193,25 @@ fn raster_only_public_apis_preserve_complete_embedded_image_pixels() { assert_eq!(pixels, [0, 255, 0, 255].repeat(4)); } } + +#[test] +fn malformed_data_urls_and_broken_pixel_payloads_are_disclosed_before_rendering() { + let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![0, 255, 0]).unwrap(); + let mut png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + // Keep a valid signature and IHDR, but remove IDAT/IEND: dimensions alone are not a decode. + png.truncate(33); + for source in ["data:image/png;base64,A".to_string(), "data:image/png;base64".to_string(), url("image/png", &png)] { + let text = drawing(&source); + let imported = crate::import("omitted.svg", text.as_bytes()).unwrap(); + assert_omission_warning(&imported, 1); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); + let (pixels, warnings) = rasterize_bounded_with_warnings(text.as_bytes(), 1., MAX_RASTER_PIXELS).unwrap(); + assert_eq!(pixels.get(1, 1), [1., 0., 0., 1.]); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].starts_with("SVG: 1 embedded ")); + assert!(rasterize(text.as_bytes(), 1.).is_err()); + assert!(rasterize_rgba8(text.as_bytes()).is_err()); + assert!(rasterize_bounded(text.as_bytes(), 1., MAX_RASTER_PIXELS).is_err()); + assert!(import_svg_preview_with_work("strict.svg", text.as_bytes(), MAX_RASTER_PIXELS).is_err()); + } +} diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index a4f89c416ba..69bd329dd12 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -526,6 +526,7 @@ impl PhotocraftApp { // Running in the background: Free Transform starts when the layer has landed. Ok(started) if crate::jobs_ui::track_place(self, &name, &started) => return, Ok(result) => { + crate::notices::io_result_warnings(self, &result, &name); if result.get("frame").and_then(serde_json::Value::as_u64).is_some() { continue; } diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index ebf20800c1c..6f015aad0bf 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -2022,3 +2022,14 @@ fn open_as_smart_object_opens_in_the_background_in_name_order() { assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn synchronous_svg_place_displays_omitted_image_warning() { + let mut app = app_with_canvas(); + app.background_jobs = false; + let doc = app.session.active().unwrap().doc.id; + let svg = br##""##; + app.drop_places.push_back((doc, crate::file_open::DropPlace::Bytes("omitted.svg".into(), svg.to_vec()))); + app.place_next_dropped(&egui::Context::default()); + assert!(app.ui.notices.iter().any(|notice| notice.lines.iter().any(|line| line.contains("embedded") && line.contains("omitted")))); +} diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index b0c4a6569c1..4479860b0fa 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -248,6 +248,7 @@ fn finish_place(app: &mut PhotocraftApp, ctx: &egui::Context, place: PlaceJob, o app.sync_views(); match outcome { JobOutcome::Done(result) => { + notices::io_result_warnings(app, &result, &place.name); // The tab can change while the file is placed: the box opens only on the document it // was placed in, and never over another one. An image placed into a frame has none. if app.ui.transform.is_none() diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index c8639d1b6e5..8cc19bdcf8a 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -1284,3 +1284,15 @@ fn open_identity_keeps_same_poll_results_in_the_profile_queue() { assert!(app.held_opens.is_empty()); control.assert_untouched(&app); } + +#[test] +fn asynchronous_place_completion_displays_result_warnings() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width":2,"height":2})).unwrap(); + let doc = app.session.active().unwrap().doc.id; + let warning = "SVG: 1 embedded image was omitted"; + let place = super::PlaceJob { job: JobId(1), name: "omitted.svg".into(), doc }; + // A frame placement bypasses transform startup but must still display its warnings. + super::finish_place(&mut app, &egui::Context::default(), place, photocraft_engine::jobs::JobOutcome::Done(json!({"frame":1,"warnings":[warning]}))); + assert!(app.ui.notices.iter().any(|notice| notice.lines.iter().any(|line| line == warning))); +} diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs index 373e5c54b9d..a46dfc01811 100644 --- a/crates/ui-egui/src/notices.rs +++ b/crates/ui-egui/src/notices.rs @@ -182,6 +182,11 @@ pub fn error(app: &mut PhotocraftApp, message: String) { /// `warnings`, which must reach the user like any other import warning. Nothing happens when /// every frame came through. pub fn footage_warnings(app: &mut PhotocraftApp, result: &serde_json::Value, what: &str) { + io_result_warnings(app, result, what); +} + +/// Surface import or update warnings returned by a successful command. +pub fn io_result_warnings(app: &mut PhotocraftApp, result: &serde_json::Value, what: &str) { let warnings: Vec = result["warnings"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str).map(str::to_owned).collect(); io_warnings(app, what, &warnings); } diff --git a/crates/ui-egui/src/smart_svg_ui.rs b/crates/ui-egui/src/smart_svg_ui.rs index fc619449060..611e6938319 100644 --- a/crates/ui-egui/src/smart_svg_ui.rs +++ b/crates/ui-egui/src/smart_svg_ui.rs @@ -469,6 +469,7 @@ pub(crate) fn poll(app: &mut PhotocraftApp, ctx: &egui::Context) { Ok(result) => { if let Some(fingerprint) = result.get("fingerprint").filter(|v| !v.is_null()) { edit.target.fingerprint = fingerprint.clone(); + crate::notices::io_result_warnings(app, &result, "SVG"); } else { report(app, "The SVG update did not return its fingerprint; syncing stopped".into()); continue; diff --git a/crates/ui-egui/src/smart_svg_ui/tests.rs b/crates/ui-egui/src/smart_svg_ui/tests.rs index bce275addbd..91f480d4c3f 100644 --- a/crates/ui-egui/src/smart_svg_ui/tests.rs +++ b/crates/ui-egui/src/smart_svg_ui/tests.rs @@ -767,3 +767,15 @@ fn finished_session_retains_final_save_until_target_is_safe() { poll(&mut app, &ctx); assert!(app.smart_svg.editing.is_empty()); } + +#[test] +fn svg_save_back_displays_omitted_image_warning() { + let (mut app, saves, _) = fixture(); + open(&mut app); + confirm(&mut app).unwrap(); + let omitted = SVG.replace("", r#""#); + saves.borrow_mut().push_back(Ok(omitted.into_bytes())); + poll(&mut app, &egui::Context::default()); + assert!(app.smart_svg.editing.first().unwrap().saved.is_none()); + assert!(app.ui.notices.iter().any(|notice| notice.lines.iter().any(|line| line.contains("embedded") && line.contains("omitted")))); +} From e82d037eb4fb385fd322dea7986f17f90b9c02d2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 06:40:39 -0500 Subject: [PATCH 08/14] build: adopt reviewed shared SVG omission accounting --- Cargo.lock | 76 ++++++++++++++++++++++++++++-------------------------- Cargo.toml | 60 +++++++++++++++++++++--------------------- 2 files changed, 69 insertions(+), 67 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0d73f35c7ff..54cc8089fd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1323,7 +1323,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "crc32fast", "flate2", @@ -1344,7 +1344,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "rustix 1.1.5", ] @@ -1352,7 +1352,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "md-5", "rayon", @@ -1361,7 +1361,7 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-metadata", "craft-xml", @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "thiserror 2.0.21", ] @@ -1379,17 +1379,17 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-eps", "craft-idml", @@ -1407,7 +1407,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-atomic", "dirs", @@ -1417,12 +1417,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "heic-rs", "rayon", @@ -1431,7 +1431,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1454,7 +1454,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-xml", "craft-zip", @@ -1464,11 +1464,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-heif", "craft-jpeg", "craft-metadata", + "crc32fast", "exr", "flate2", "half", @@ -1489,7 +1490,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "thiserror 2.0.21", ] @@ -1497,7 +1498,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-xml", "craft-zip", @@ -1507,7 +1508,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "brotli-decompressor 6.3.1", "chrono", @@ -1519,7 +1520,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-xml", "craft-zip", @@ -1529,7 +1530,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "blake3", "craft-atomic", @@ -1542,7 +1543,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "serde", "serde_json", @@ -1552,7 +1553,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "bytemuck", "flate2", @@ -1566,7 +1567,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1575,7 +1576,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-winprint-gdi", "log", @@ -1589,7 +1590,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "encoding_rs", "flate2", @@ -1600,7 +1601,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "chrono", "craft-crw", @@ -1618,10 +1619,11 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-image-codecs", "craft-xml", + "data-url", "flate2", "kurbo 0.13.1", "resvg 0.48.1", @@ -1635,7 +1637,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "serde", "thiserror 2.0.21", @@ -1644,7 +1646,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1665,7 +1667,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "chrono", "dunce", @@ -1700,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1709,7 +1711,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1719,7 +1721,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3146,7 +3148,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "bytemuck", "hayro-interpret", @@ -3176,7 +3178,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3194,7 +3196,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3218,7 +3220,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=c29336211a7f807729e97053257b69dddc8b1738#c29336211a7f807729e97053257b69dddc8b1738" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "flate2", "hayro-ccitt", @@ -9518,7 +9520,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=72951d7455ebcab569fbd9386c513d3d9f53fb02#72951d7455ebcab569fbd9386c513d3d9f53fb02" +source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57" dependencies = [ "flate2", "fmt-derive", diff --git a/Cargo.toml b/Cargo.toml index 56c71b1ac0d..06138f9e282 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,9 +10,9 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["serde"] } # Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119). -craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } # The ArtCraft Launcher's agents switch and app list, shared with the launcher, the MCP gateway and # every Craft app (storytold/craft-ai-integrations#195). Pinned to the head of # storytold/craft-ai-integrations#197 until it merges. @@ -23,11 +23,11 @@ photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -46,31 +46,31 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft-ui. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c29336211a7f807729e97053257b69dddc8b1738", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["egui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -229,7 +229,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7 egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README). -hayro = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c29336211a7f807729e97053257b69dddc8b1738" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } From 8e5ace3e049836055b163c2e973602d143ee8e6f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 06:48:28 -0500 Subject: [PATCH 09/14] test(io): use bounded fallible pixel conversion in banded fixtures --- crates/io/tests/it/banded.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/io/tests/it/banded.rs b/crates/io/tests/it/banded.rs index c2c4a5de0a3..9cda780fbb8 100644 --- a/crates/io/tests/it/banded.rs +++ b/crates/io/tests/it/banded.rs @@ -43,7 +43,12 @@ fn layered_png_export_spans_bands() { let r = export(&d, "x.png", &ExportOptions::default()).unwrap(); let img = photocraft_codecs::decode(&r.bytes).unwrap(); assert_eq!(img.layout().has_alpha(), alpha < 1.0, "{depth:?} alpha {alpha}"); - let got: Vec = img.to_rgba_f32().iter().map(|v| (v * scale).round()).collect(); + let got: Vec = img + .to_rgba_f32(&photocraft_codecs::Limits::default()) + .expect("the fixture fits the default decoded-image limits") + .iter() + .map(|v| (v * scale).round()) + .collect(); assert!(got == composite_q(&d, scale), "{depth:?} alpha {alpha}: pixels differ"); } } @@ -70,7 +75,12 @@ fn single_layer_native_export_strips_opaque_alpha() { let img = photocraft_codecs::decode(&r.bytes).unwrap(); assert_eq!(img.sample_type(), photocraft_codecs::SampleType::U16); assert!(img.layout().has_alpha()); - let got: Vec = img.to_rgba_f32().iter().map(|v| (v * 65535.0).round()).collect(); + let got: Vec = img + .to_rgba_f32(&photocraft_codecs::Limits::default()) + .expect("the fixture fits the default decoded-image limits") + .iter() + .map(|v| (v * 65535.0).round()) + .collect(); assert_eq!(got, composite_q(&d, 65535.0), "active vector mask: pixels differ"); } From dcbe68e7186ad9a6e6dce8e2c3982cb6ab0d73fc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 07:47:16 -0500 Subject: [PATCH 10/14] Preserve RAW assertions and bound SVG text expansion after damaged children --- crates/io/src/svg.rs | 9 +++++++-- crates/io/src/svg/tests.rs | 6 ++++++ crates/raw/tests/it/dng.rs | 4 ++-- crates/raw/tests/it/hasselblad.rs | 2 +- crates/raw/tests/it/vendor_codecs.rs | 3 +-- 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 3c3bc3fd860..4516495165b 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -634,8 +634,13 @@ fn note_byte_refusal(data: &[u8], used: usize, refusals: &SvgRefusals) { // Every unpack is charged at least what it unpacked, so together they stay within one // budget; plain data is only measured. let (unpacked, too_large) = match craft_svg::svgz::inflate(data, limit) { - Ok(std::borrow::Cow::Borrowed(_)) => (0, false), - Ok(std::borrow::Cow::Owned(xml)) => (xml.len(), false), + Ok(xml) => { + // Encoding expansion is part of the text budget too: a Latin-1 child + // after corrupt data must not evade the normal decoded-text limit. + let decoded = craft_svg::svgz::decode(&xml).map_or(xml.len(), |text| text.len()); + let work = if compressed { xml.len().max(decoded).min(limit) } else { 0 }; + (work, decoded > limit) + } Err(craft_svg::svgz::Error::Nested(len)) => (len, false), Err(craft_svg::svgz::Error::TooLarge(_)) => (if compressed { limit } else { 0 }, true), Err(_) => (limit, false), diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 1cf2f6cc6fb..28146b8ae8c 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -1169,6 +1169,12 @@ fn a_latin1_embedded_svg_that_decodes_past_the_budget_is_refused() { assert!(error.to_string().contains("byte or nesting budget"), "{error}"); let error = parse_bounded(image_svg(&format!("{wide}{small}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); assert!(error.to_string().contains("byte or nesting budget"), "{error}"); + // A damaged predecessor may consume the accounting budget, but must not hide + // the next child's own decoded-text overrun during refusal reclassification. + let compressed = gzip(b""); + let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); + let error = parse_bounded(image_svg(&format!("{damaged}{wide}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); } /// After a damaged image spent the budget, images refused for bytes are unpacked again to tell diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index b3343ef266f..1369ec643b4 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -994,7 +994,7 @@ fn jpeg_xl_mismatches_are_errors() { #[test] fn profile_gain_table_map_is_reported() { - let gain_table = |s: &Sensor| s.warnings.iter().any(|w| w.contains("gain table map")); + let gain_table = |s: &Sensor| s.warnings.iter().any(|w| w.contains("ProfileGainTableMap") || w.contains("gain table map")); let mut spec = DngSpec::cfa(8, 8, vec![500; 64]); assert!(!gain_table(&sensor(&spec.build()))); // A well-formed ProfileGainTableMap (version 1, little-endian): one table of one gain. craft-raw @@ -1014,7 +1014,7 @@ fn profile_gain_table_map_is_reported() { assert!(gain_table(&s)); let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); for warnings in [&s.warnings, &d.warnings] { - assert!(warnings.iter().any(|w| w.contains("gain table map") && w.contains("not applied")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("ProfileGainTableMap") && w.contains("not applied")), "{warnings:?}"); assert!(!warnings.iter().any(|w| w.contains("gain table map") && w.contains("omitted")), "{warnings:?}"); } } diff --git a/crates/raw/tests/it/hasselblad.rs b/crates/raw/tests/it/hasselblad.rs index 0c96dff7df7..e4b09d64565 100644 --- a/crates/raw/tests/it/hasselblad.rs +++ b/crates/raw/tests/it/hasselblad.rs @@ -48,7 +48,7 @@ fn metadata() { // craft-raw reads AsShotNeutral as the DNG colour tag; development turns it into multipliers. let neutral = sensor.color.as_shot_neutral.unwrap(); assert!((neutral[0] - 0.375).abs() < 1e-9 && (neutral[2] - 0.617).abs() < 1e-9, "{neutral:?}"); - assert_eq!((sensor.make.as_deref(), sensor.model.as_deref()), (Some("Hasselblad"), Some("Hasselblad X2D II 100C"))); + assert_eq!((sensor.make.as_deref(), sensor.model.as_deref()), (Some("Hasselblad"), Some("X2D II 100C"))); assert_eq!(sensor.orientation, 1); // This real-layout fixture deliberately has no CFAPattern tag. All source // metadata is retained, while the decoder discloses its assumed RGGB phase. diff --git a/crates/raw/tests/it/vendor_codecs.rs b/crates/raw/tests/it/vendor_codecs.rs index f8a441477a6..6bbff143626 100644 --- a/crates/raw/tests/it/vendor_codecs.rs +++ b/crates/raw/tests/it/vendor_codecs.rs @@ -155,8 +155,7 @@ fn rw2_round_trip_12_and_14_bit() { assert_eq!(s.data, data, "{bits}-bit"); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]); assert_eq!(s.black.values, vec![128.0, 129.0, 129.0, 130.0]); - // craft-raw takes the white level from the data: the saturation plateau of the scene, else the full range. - assert!(s.white[0] > 0.0 && s.white[0] <= f32::from(max), "{:?}", s.white); + assert_eq!(s.white, [f32::from(max); 3]); assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5])); assert_eq!(s.crop, Rect::new(2, 2, w - 4, h - 4)); let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); From cbecb5cc718ccbb6611cce380f6a05e0ca89e6bf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 07:47:55 -0500 Subject: [PATCH 11/14] Charge legacy text conversion to SVG refusal recheck budget --- crates/io/src/svg.rs | 15 +++++++++------ crates/io/src/svg/tests.rs | 3 +++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 4516495165b..421c9ea8455 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -628,17 +628,20 @@ fn note_byte_refusal(data: &[u8], used: usize, refusals: &SvgRefusals) { Err(craft_svg::svgz::Error::TooLarge(_)) if unread == 0 => refusals.over_budget.store(true, Ordering::Relaxed), Err(craft_svg::svgz::Error::TooLarge(_)) => { let content_left = budget.saturating_sub(used.saturating_sub(unread)); - // Plain data is only measured; compressed data is unpacked again. + // Rechecks may inflate or allocate text for a legacy encoding. let compressed = data.starts_with(&[0x1f, 0x8b]); - let limit = if compressed { content_left.min(budget.saturating_sub(refusals.rechecked.load(Ordering::Relaxed))) } else { content_left }; - // Every unpack is charged at least what it unpacked, so together they stay within one - // budget; plain data is only measured. + let limit = content_left.min(budget.saturating_sub(refusals.rechecked.load(Ordering::Relaxed))); + // Charge inflation and allocated decoded text against the same recheck budget. let (unpacked, too_large) = match craft_svg::svgz::inflate(data, limit) { Ok(xml) => { // Encoding expansion is part of the text budget too: a Latin-1 child // after corrupt data must not evade the normal decoded-text limit. - let decoded = craft_svg::svgz::decode(&xml).map_or(xml.len(), |text| text.len()); - let work = if compressed { xml.len().max(decoded).min(limit) } else { 0 }; + let (decoded, converted) = match craft_svg::svgz::decode(&xml) { + Ok(std::borrow::Cow::Owned(text)) => (text.len(), text.len()), + Ok(text) => (text.len(), 0), + Err(_) => (xml.len(), xml.len()), + }; + let work = (if compressed { xml.len().max(converted) } else { converted }).min(limit); (work, decoded > limit) } Err(craft_svg::svgz::Error::Nested(len)) => (len, false), diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 28146b8ae8c..b14bd811e9d 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -1175,6 +1175,9 @@ fn a_latin1_embedded_svg_that_decodes_past_the_budget_is_refused() { let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); let error = parse_bounded(image_svg(&format!("{damaged}{wide}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); assert!(error.to_string().contains("byte or nesting budget"), "{error}"); + let plain = embedded_image("image/svg+xml", &latin1); + let error = parse_bounded(image_svg(&format!("{damaged}{plain}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); } /// After a damaged image spent the budget, images refused for bytes are unpacked again to tell From daf040eace0b71e3af7d5768324822c4ad4273e5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 07:51:10 -0500 Subject: [PATCH 12/14] test(raw): retain Hasselblad white-balance fixture coverage --- crates/raw/tests/it/hasselblad.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/raw/tests/it/hasselblad.rs b/crates/raw/tests/it/hasselblad.rs index e4b09d64565..3e3846994ce 100644 --- a/crates/raw/tests/it/hasselblad.rs +++ b/crates/raw/tests/it/hasselblad.rs @@ -45,6 +45,9 @@ fn metadata() { assert_eq!(sensor.active, Rect::new(0, 0, 16, 12)); assert_eq!(sensor.black, BlackLevels::uniform(4096.0)); assert_eq!(sensor.white, [64763.0; 3]); + let wb = sensor.camera_wb.unwrap(); + assert!((wb[0] - 1.0 / 0.375).abs() < 1e-9, "{wb:?}"); + assert!((wb[2] - 1.0 / 0.617).abs() < 1e-9, "{wb:?}"); // craft-raw reads AsShotNeutral as the DNG colour tag; development turns it into multipliers. let neutral = sensor.color.as_shot_neutral.unwrap(); assert!((neutral[0] - 0.375).abs() < 1e-9 && (neutral[2] - 0.617).abs() < 1e-9, "{neutral:?}"); From cff119582b0b1f3e727873ec0cf617db2e94b128 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 08:41:58 -0500 Subject: [PATCH 13/14] test: target SVG child budget and synchronize JPEG estimate --- crates/io/src/svg/tests.rs | 3 ++- .../jpeg_options_ui/size_readout/tests.rs | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index b14bd811e9d..7fcabe4fcdd 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -1175,7 +1175,8 @@ fn a_latin1_embedded_svg_that_decodes_past_the_budget_is_refused() { let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); let error = parse_bounded(image_svg(&format!("{damaged}{wide}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); assert!(error.to_string().contains("byte or nesting budget"), "{error}"); - let plain = embedded_image("image/svg+xml", &latin1); + let plain = format!("", base64(&latin1)); + assert!(image_svg(&format!("{damaged}{plain}")).len() < budget, "exercise child decoding, not the outer source cap"); let error = parse_bounded(image_svg(&format!("{damaged}{plain}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); assert!(error.to_string().contains("byte or nesting budget"), "{error}"); } diff --git a/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout/tests.rs b/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout/tests.rs index f5cce74ce9f..86eb09a50e2 100644 --- a/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout/tests.rs +++ b/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout/tests.rs @@ -118,7 +118,22 @@ fn unchanged_settings_are_not_encoded_again() { assert_eq!(encodes.load(Ordering::SeqCst), 3); let edited = Key { revision: 4, ..key }; - assert_eq!(readout.update(edited, || || None, || {}), Estimate::Pending(None), "an edited document shows no size of the old one"); + // Hold the new encode pending: an immediate None may complete before update returns. + let (gate, wait) = std::sync::mpsc::channel::<()>(); + let pending = readout.update( + edited, + || { + move || { + let _ = wait.recv(); + None + } + }, + || {}, + ); + // Release even if the assertion fails, so no worker is left waiting. + gate.send(()).unwrap(); + assert_eq!(pending, Estimate::Pending(None), "an edited document shows no size of the old one"); + assert_eq!(answer(&mut readout, edited, || None), None, "the completed edit never reuses the old size"); } /// Going back to settings already worked out shows their size at once, without encoding again; From 3a28b6a25ef18657411db2ebb55413612e4e0689 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:57:19 +0100 Subject: [PATCH 14/14] raw: keep the U16 develop sample loop to one range comparison The per-sample normalization in fill_samples called a helper that tested range.is_finite() and range <= 0.0 for every sample, which made 24 MP monochrome U16 develops ~30% slower than main. A single range > 0.0 test gives the same results (NaN, zero, negative and infinite ranges all end at 0) and restores main's speed; output hashes are unchanged. --- crates/raw/src/develop.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index d55009b3233..be15a735b68 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -191,11 +191,15 @@ fn fill_samples(row: &mut [f32], raw: impl Iterator, table: &[[ phase = if phase + 1 == table.len() { 0 } else { phase + 1 }; for k in 0..3 { let (black, range) = t[k]; - let n = if !range.is_finite() || range <= 0.0 { - 0.0 - } else { + // One comparison keeps this per-sample loop as cheap as before. It gives the same + // result as the `!range.is_finite() || range <= 0.0` test of `Scale::value`: NaN and + // nonpositive ranges fail it, and a +inf range divides a finite numerator to 0 (or to + // NaN for an infinite one, which the finiteness check maps to 0). + let n = if range > 0.0 { let n = (lin(raw[k]) - black) / range; if n.is_finite() { n } else { 0.0 } + } else { + 0.0 }; px[k] = (n * mult[k]).clamp(0.0, 1.0); }