diff --git a/Cargo.lock b/Cargo.lock index d7a34e3b908..c405a5ed8d9 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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "rustix 1.1.5", ] @@ -1361,9 +1361,9 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-xml", "thiserror 2.0.21", ] @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-heif", "craft-jpeg", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", + "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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-xml", "craft-zip", @@ -1519,11 +1520,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "brotli-decompressor 6.3.1", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "quick-xml 0.41.0", "serde", ] @@ -1531,7 +1532,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-xml", "craft-zip", @@ -1541,11 +1542,11 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "blake3", "craft-atomic", - "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", + "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-zip", "ruzstd", "thiserror 2.0.21", @@ -1565,7 +1566,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "serde", "serde_json", @@ -1575,7 +1576,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "bytemuck", "flate2", @@ -1589,7 +1590,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1606,7 +1607,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-winprint-gdi", "log", @@ -1686,12 +1687,12 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "chrono", "craft-crw", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "jxl-oxide", "miniz_oxide 0.9.1", "rayon", @@ -1704,10 +1705,11 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +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", @@ -1730,7 +1732,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "serde", "thiserror 2.0.21", @@ -1739,7 +1741,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1760,7 +1762,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "chrono", "dunce", @@ -1795,7 +1797,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1804,7 +1806,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1814,7 +1816,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3243,7 +3245,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "bytemuck", "hayro-interpret", @@ -3273,7 +3275,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3291,7 +3293,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3315,7 +3317,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "flate2", "hayro-ccitt", @@ -5722,7 +5724,7 @@ dependencies = [ "craft-file-formats", "craft-image-codecs", "craft-pcraft-bundle", - "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", + "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-zip", "crc32fast", "exacl", @@ -5791,7 +5793,7 @@ dependencies = [ "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5e2bc54a48c9f03e7ce4eca42775ce5cc051f5d6)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b9c22554ce0fd2caccdb53b417082a2ff2ef178f)", "craft-svg", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-xcf", "craft-xml", "crc32fast", @@ -9627,7 +9629,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 2e2e96b3564..5476228fe85 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 = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6", 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 = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } +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. @@ -25,10 +25,10 @@ photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "e2e3b4213afb2b5e7651bc1b1a1cf72a8bb6313d" } craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +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 = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } +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" } @@ -48,32 +48,32 @@ 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 = "c6eb84d427d81b6d64207654c8ee0516cd3d7324" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } +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 = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } +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" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "163f1b20315ffacaf8a6e085f4ae7fc568c08ff2" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } +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 = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } +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 = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6", 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" @@ -232,7 +232,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 = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } +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" } 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..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}"))); } @@ -198,10 +200,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..c7bb5eb22a8 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(); @@ -164,3 +176,52 @@ 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"); +} + +/// 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/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/format/src/store.rs b/crates/format/src/store.rs index f31467cf7cc..f42e2d49b84 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -155,14 +155,58 @@ 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")), - // A ZIP member past its read bound arrives as a craft-zip error, not as `LimitExceeded`. craft_pcraft_bundle::Error::Zip(error) => crate::zip::map_read_error(error), other => FormatError::corrupt(other.to_string()), } } -/// [`bundle_error`] for a directory save. A save decodes nothing, so craft-pcraft-bundle's `Io` -/// there is a real I/O failure (a locked or read-only file, a full disk), not a damaged bundle. +#[cfg(test)] +mod bundle_error_tests { + use super::*; + + #[test] + fn shared_save_io_errors_keep_the_native_io_type_and_message() { + let error = save_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 = format!("zip: {error}"); + 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::Io("invalid compressed frame".into()), + 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 = match &error { + craft_pcraft_bundle::Error::Zip(e) => format!("zip: {e}"), + _ => error.to_string(), + }; + assert!(matches!(bundle_error(error), FormatError::Corrupt(found) if found == message)); + } + } +} + +/// Save failures are I/O errors; read-time decompression errors remain corrupt data. fn save_error(error: craft_pcraft_bundle::Error) -> FormatError { match error { craft_pcraft_bundle::Error::Io(message) => FormatError::Io(std::io::Error::other(message)), diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index ab74971342a..a311a17671f 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(); diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 87dc0ebcfa3..4d94295064d 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -402,6 +402,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 @@ -431,6 +434,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 { @@ -443,16 +450,17 @@ 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| { + image_resolver.check_document(text).map_err(svg_parse_error)?; 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)?; - // An embedded image over a budget was refused by the resolver and is left out of the - // tree, so the rest of the drawing still opens (as before the craft-svg migration). - // Only the bounded smart-object path refuses the whole drawing for it. - 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) } @@ -541,10 +549,11 @@ fn parse_image_bounded_with( budget.lock().unwrap_or_else(PoisonError::into_inner).fontless_text = true; } let resolver = Arc::clone(&budget.lock().unwrap_or_else(PoisonError::into_inner).resolver); + let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; + resolver.check_document(text).map_err(svg_parse_error)?; let refusals = Arc::new(SvgRefusals::default()); let mut opt = options_with_isolation(fontdb, xml_left, isolated, Arc::clone(&resolver)); opt.image_href_resolver = noting_refusals(opt.image_href_resolver, resolver, Arc::clone(&refusals)); - let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; let limits = tree_limits(xml_left, MAX_RASTER_PIXELS); let tree = guarded_parse(|| craft_svg::tree::parse_text(text, &limits, &opt))?; let tree = tree.map_err(svg_parse_error)?; @@ -554,6 +563,8 @@ 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 usage.svg_limit_images > 0 && (counter.strict || refusals.over_budget.load(Ordering::Relaxed)) { @@ -599,6 +610,8 @@ struct SvgRefusals { unread_charges: AtomicUsize, /// Bytes unpacked again to tell those images apart, at most one byte budget per drawing. rechecked: AtomicUsize, + /// Source bytes decoded during refusal rechecks, at most one byte budget per drawing. + text_rechecked: AtomicUsize, } /// Note in `refusals` what craft-svg will do with an embedded SVG's `data` when its images have @@ -617,17 +630,25 @@ 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. + // Bound inflation and text-conversion work independently from content size. let (unpacked, too_large) = match craft_svg::svgz::inflate(data, limit) { - Ok(bytes) => { - let charged = if compressed { bytes.len() } else { 0 }; - // Inflation and text decoding use different units: Latin-1 expands in UTF-8. - let decoded_too_large = craft_svg::svgz::decode(&bytes).is_ok_and(|text| text.len() > content_left); - (charged, decoded_too_large) + Ok(xml) => { + // Inflation and text conversion have separate work allowances: a fitting + // Latin-1 document must not spend its UTF-8 size against inflation bytes. + // Charge source bytes before decoding, including invalid encodings. The + // supported encodings expand by at most 2x, so conversion work stays bounded + // even for plain children that do not require inflation. + let text_left = budget.saturating_sub(refusals.text_rechecked.load(Ordering::Relaxed)); + let too_large = if xml.len() > text_left { + true + } else { + refusals.text_rechecked.fetch_add(xml.len(), Ordering::Relaxed); + craft_svg::svgz::decode(&xml).is_ok_and(|text| text.len() > content_left) + }; + (if compressed { xml.len() } else { 0 }, too_large) } Err(craft_svg::svgz::Error::Nested(len)) => (len, false), Err(craft_svg::svgz::Error::TooLarge(_)) => (if compressed { limit } else { 0 }, true), @@ -789,7 +810,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, @@ -1023,6 +1044,19 @@ pub fn import_svg_bounded_images(name: &str, bytes: &[u8], max_decoded_pixels: u on_svg_stack(|| import_parsed(name, parse_bounded(bytes, max_decoded_pixels)?, MAX_GROUP_DEPTH, None, false)) } +/// The bounded layered import for callers without an omission-warning channel. Reject missing +/// embedded images before rendering or caching any layers; keep the same decode and retained- +/// pixel budgets as [`import_svg_bounded_images`]. +pub fn import_svg_bounded_images_strict(name: &str, bytes: &[u8], max_decoded_pixels: u64) -> 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 @@ -1083,8 +1117,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()); } @@ -1139,20 +1176,54 @@ 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) }) } /// Render untrusted embedded SVG with intrinsic raster-image and aggregate decode budgets. pub fn rasterize_bounded(bytes: &[u8], scale: f32, max_decoded_pixels: u64) -> 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 = parsed.tree; + 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); @@ -1161,7 +1232,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)) }) } @@ -1180,7 +1251,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 @@ -1826,3 +1897,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..d670ec28459 --- /dev/null +++ b/crates/io/src/svg/optional_image_review_tests.rs @@ -0,0 +1,217 @@ +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"))); + 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.]); + } +} + +#[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("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)); + } +} + +#[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/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 2f5b44ad103..0d4dfd18385 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -943,27 +943,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"))); } } @@ -1012,8 +1027,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"); @@ -1154,12 +1169,16 @@ 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}"); - // An unreadable image charges the entire budget before the Latin-1 child is retried. - // The retry must measure decoded text too, not only its smaller inflated byte stream. - let compressed = gzip(b""); + // 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}"); + 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}"); } /// The retry allowance counts inflated bytes, not their possibly longer decoded UTF-8 text. @@ -1590,3 +1609,17 @@ fn every_raster_refusal_reason_is_reported_once() { assert_eq!(dropped("rasterising limit"), 1, "{:?}", result.warnings); assert_eq!(dropped("too much memory"), 1, "{:?}", result.warnings); } + +#[test] +fn plain_legacy_encoding_rechecks_have_a_separate_bounded_work_allowance() { + let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap(); + let xml = b""; + let refusals = SvgRefusals { unread_charges: AtomicUsize::new(budget), text_rechecked: AtomicUsize::new(budget - xml.len()), ..SvgRefusals::default() }; + note_byte_refusal(xml, budget, &refusals); + assert!(!refusals.over_budget.load(Ordering::Relaxed)); + assert_eq!(refusals.text_rechecked.load(Ordering::Relaxed), budget); + assert_eq!(refusals.rechecked.load(Ordering::Relaxed), 0); + note_byte_refusal(xml, budget, &refusals); + assert!(refusals.over_budget.load(Ordering::Relaxed)); + assert_eq!(refusals.text_rechecked.load(Ordering::Relaxed), budget); +} 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"); } 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()); +} diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index 6254c2f8776..be15a735b68 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,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_nan() || range < 1.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); } @@ -399,8 +405,16 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result = (0..period) .map(|p| { let x = c.x + p; @@ -408,33 +422,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 +1198,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(); - // Preserve decoder uncertainty: a fallback phase is not metadata supplied by the file. - if image.notices.assumed_cfa { - out.push("the raw colour filter phase was assumed".to_string()); - } if image.notices.default_crop_adjusted { - out.push("the raw default crop was adjusted to the active image".to_string()); + 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()); + } } if image.notices.gain_table_omitted { out.push("the raw camera profile's invalid gain table map was omitted".to_string()); @@ -99,8 +108,8 @@ fn warnings(image: &craft_raw::RawImage) -> Vec { 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 } @@ -140,6 +149,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)), @@ -147,7 +165,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, @@ -160,7 +178,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, @@ -170,10 +188,90 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { warnings, }; crate::cameras::apply(&mut sensor, image.bits); - // Only DNG writers state a white level the sensor never reaches (saturation.rs); the other formats' - // levels come from the camera's own tags or the data, and their samples stay as decoded. + // 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/raf.rs b/crates/raw/src/testgen/raf.rs index e81e4f6caf1..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]), @@ -201,8 +201,13 @@ impl RafSpec { ] .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(); + // 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/cr3.rs b/crates/raw/tests/it/cr3.rs index 8a029361668..8ed2c9c62cb 100644 --- a/crates/raw/tests/it/cr3.rs +++ b/crates/raw/tests/it/cr3.rs @@ -43,22 +43,20 @@ fn variable_sizes_and_32_bit_chunk_offsets_work() { #[test] fn broken_tables_and_raw_codec_tracks_are_not_used() { let good = cr3_preview(&jpeg(), 1); - // (A broken stsc is tolerated: craft-raw falls back to one sample per chunk, which finds the same JPEG.) - for marker in [b"stsz", b"co64", b"JPEG"] { + for marker in [b"stsz", b"co64", b"stsc", b"JPEG"] { let mut b = good.clone(); let at = position(&b, marker); b[at..at + 4].copy_from_slice(b"xxxx"); - assert!(embedded_jpeg_preview(&b).is_none()); + assert!(embedded_preview(&b).is_none()); } let mut b = good.clone(); let at = position(&b, b"co64") + 12; b[at..at + 8].copy_from_slice(&u64::MAX.to_be_bytes()); - assert!(embedded_jpeg_preview(&b).is_none()); - // Refuse an impossible sample count rather than trusting just its first entry. + assert!(embedded_preview(&b).is_none()); let mut b = good; let at = position(&b, b"stsz") + 12; b[at..at + 4].copy_from_slice(&u32::MAX.to_be_bytes()); - assert!(embedded_jpeg_preview(&b).is_none()); + assert!(embedded_preview(&b).is_none()); } #[test] diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index 8ffe6952153..1369ec643b4 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -8,8 +8,7 @@ fn sensor(bytes: &[u8]) -> Sensor { decode(bytes, &Limits::default()).unwrap() } -/// The floating-point samples of `s`: craft-raw keeps float DNG data as `f32`, in the unit of its white level, -/// instead of scaling it to 16 bits. +/// 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") } @@ -202,9 +201,8 @@ fn broken_monochrome_linear_raw_errors() { } let first: Vec = spec.data[..4].iter().flat_map(|v| v.to_le_bytes()).collect(); let strip = b.windows(first.len()).position(|win| win == first.as_slice()).expect("strip data"); - // Uncompressed rows missing from a cut strip are zero-filled (craft-raw's choice); a strip holding - // under 1/64 of its samples is no picture. - assert!(decode(&b[..strip + 2], &Limits::default()).is_err(), "truncated strip"); + assert!(decode(&b[..strip + w], &Limits::default()).is_err(), "truncated strip"); + assert!(decode(&b[..strip + 2], &Limits::default()).is_err(), "short truncated strip"); // Two samples per pixel is no LinearRaw layout. let two = DngSpec { samples: 2, data: ramp(2 * w, h, 100, 4000), ..spec.clone() }; let err = decode(&two.build(), &Limits::default()).unwrap_err().to_string(); @@ -261,9 +259,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); - // craft-raw applies the table to the samples at decode. - assert!(s.linearization.is_none()); - assert_eq!(s.data[0], 3000); + 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)); @@ -274,40 +271,49 @@ fn metadata_is_read() { /// An unrepresentable DefaultCropOrigin is refused; the whole active area is kept with a notice. #[test] -fn enormous_double_crop_origin_leaves_the_active_area() { +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]); - - let s = sensor(&spec.build()); - assert_eq!(s.crop, s.active); + 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); + } } /// craft-raw clips a crop that reaches past the active area and reports the adjustment. #[test] -fn out_of_range_default_crop_is_clipped_to_the_active_area() { +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()); - // The 5 × 4 crop at (10, 0) keeps the 4 columns left in the 14-wide active area at x 3. - assert_eq!(s.crop, Rect::new(13, 2, 1, 4)); + 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 active area, which is clipped 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_is_clipped_to_the_active_area() { +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, Rect::new(s.active.x + 1, s.active.y + 1, s.active.width - 1, s.active.height - 1)); + 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); } /// #950: DefaultCropOrigin defaults to (0, 0), so a size-only crop starts at the active area's @@ -530,12 +536,20 @@ 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 - let s = sensor(&spec.build()); - assert!(!s.cfa.as_ref().unwrap().is_bayer()); - // 17-bit integer samples are no TIFF raw layout this reader knows. - let mut spec = DngSpec::cfa(8, 8, vec![0; 64]); + // 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(_)))); } @@ -558,8 +572,8 @@ fn deflate_strips_round_trip() { for (name, bits, storage, be) in [ ("deflate 16-bit", 16, DngStorage::DeflateStrips { rows: 16, predictor: 1 }, false), ("deflate 16-bit predictor 2", 16, DngStorage::DeflateStrips { rows: 16, predictor: 2 }, false), - // (No 12-bit predictor 2: libtiff applies the predictor to 8, 16, 32 and 64-bit samples only.) ("deflate 12-bit", 12, DngStorage::DeflateStrips { rows: 12, predictor: 1 }, false), + ("deflate 12-bit predictor 2", 12, DngStorage::DeflateStrips { rows: 12, predictor: 2 }, false), ("deflate 16-bit predictor 2 BE", 16, DngStorage::DeflateStrips { rows: 16, predictor: 2 }, true), ("deflate LinearRaw predictor 2", 16, DngStorage::DeflateStrips { rows: 40, predictor: 2 }, false), ] { @@ -597,6 +611,12 @@ fn deflate_hostile_fails_cleanly() { /// stream (not in 16-bit containers), as the testgen writes them. #[test] fn deflate_8_bit_predictor_and_packed_12_bit() { + use std::io::Write as _; + let zlib = |bytes: &[u8]| { + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + e.write_all(bytes).unwrap(); + e.finish().unwrap() + }; let (w, h) = (16usize, 4usize); // 8-bit, predictor 2: a row falling from 250 to 10 has deltas that wrap mod 256. let data8: Vec = (0..w * h).map(|i| if i % w < w / 2 { 250 } else { 10 }).collect(); @@ -605,13 +625,19 @@ 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. + // 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 }; - assert_eq!(sensor(&spec.build()).data, data12, "12-bit packed"); + 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 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"); } // ---------------------------------------------------------------- JPEG XL (DNG 1.7) @@ -740,13 +766,18 @@ fn floating_point_jpeg_xl_linear_raw_decodes() { /// Uncompressed floating-point strips (16-bit half floats here) decode too: craft-raw reads them as floats. #[test] -fn uncompressed_floating_point_raw_data_decodes_as_floats() { +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 }; let s = sensor(&spec.build()); assert_eq!((s.width, s.height, s.samples), (w, h, 3)); - assert_eq!(floats(&s).len(), 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, kept per plane next to the unscaled floats. @@ -767,6 +798,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. craft-raw leaves the samples as stored and hands the polynomials on; development maps each /// plane through its own, on the linear reference values. @@ -782,7 +831,9 @@ fn map_polynomial_maps_each_plane_of_floating_point_data() { )); let bytes = spec.build(); let s = sensor(&bytes); - assert!(near(floats(&s), &unit(&data))); + 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_eq!(s.polynomials.len(), planes.len()); for (p, c) in s.polynomials.iter().zip(&planes) { assert_eq!(&p.coefficients, c); @@ -808,8 +859,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 at decode"); - assert_eq!(s.data, data.iter().map(|&v| table[usize::from(v)]).collect::>()); + 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); assert_eq!(s.polynomials.len(), 1); } @@ -825,7 +878,7 @@ fn floating_point_raw_data_ignores_a_linearization_table() { 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() { @@ -930,9 +983,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!(decode(&spec.build(), &Limits::default()).is_err()); + 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(_)))); @@ -940,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 @@ -960,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:?}"); } } @@ -1092,7 +1146,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!(s.linearization.is_none(), "applied at decode"); + 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()) }; @@ -1111,28 +1166,55 @@ 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("16 x 16") && err.contains("32 x 32"), "{err}"); - // A tile JPEG is tolerated when it covers the part of the tile inside the image (edge tiles are - // often coded smaller or larger than nominal); one that leaves part of that uncovered 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 [(12, 16), (16, 10), (10, 10)] { + 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, 10), (10, 10), (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}"); } + // 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(_)))); +} + +/// A tile with the wrong number of JPEG components (a colour JPEG in a CFA DNG, a gray one in a +/// 3-sample LinearRaw DNG) is rejected rather than silently converted. +#[test] +fn lossy_jpeg_component_count_mismatch_errors() { + let (w, h) = (16, 16); + let mut cfa = lossy_spec(w, h, vec![90; w * h], DngStorage::LossyJpegTiles { width: 16, height: 16 }); + cfa.lossy_segments = vec![baseline_jpeg(&vec![90u8; w * h * 3], w, h, 3)]; + let err = decode(&cfa.build(), &Limits::default()).unwrap_err(); + assert!(matches!(&err, RawError::Malformed(m) if m.contains("3 components")), "{err}"); + + let mut rgb = lossy_spec(w, h, vec![90; w * h * 3], DngStorage::LossyJpegTiles { width: 16, height: 16 }); + rgb.samples = 3; + rgb.lossy_segments = vec![baseline_jpeg(&vec![90u8; w * h], w, h, 1)]; + let err = decode(&rgb.build(), &Limits::default()).unwrap_err(); + assert!(matches!(&err, RawError::Malformed(m) if m.contains("1 components")), "{err}"); } /// A SOF claiming a 65535x65535 frame inside a 16x16 tile is refused at the header, under the diff --git a/crates/raw/tests/it/hasselblad.rs b/crates/raw/tests/it/hasselblad.rs index f7c2a73bf56..3e3846994ce 100644 --- a/crates/raw/tests/it/hasselblad.rs +++ b/crates/raw/tests/it/hasselblad.rs @@ -45,13 +45,18 @@ 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:?}"); - 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 fixture deliberately omits CFA tags; the RGGB fallback must remain visible to callers. - assert_eq!(sensor.warnings, ["the raw colour filter phase was assumed"]); + // 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] @@ -84,8 +89,12 @@ fn missing_levels_fall_back() { s.white = None; let sensor = decode(&s.build(), &Limits::default()).unwrap(); assert_eq!(sensor.black, BlackLevels::uniform(0.0)); - // craft-raw falls back to the full scale of the sample depth. + assert!(sensor.warnings.iter().any(|w| w.contains("black level")), "{:?}", sensor.warnings); + // 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] @@ -132,5 +141,13 @@ fn truncated_strip_is_refused() { fn zero_dimensions_are_malformed() { let mut s = spec(); s.width = 0; - assert!(decode(&s.build(), &Limits::default()).is_err()); + assert!(matches!(decode(&s.build(), &Limits::default()), Err(RawError::Malformed(_)))); +} + +#[test] +fn unknown_body_warns_about_the_assumed_phase() { + let mut s = spec(); + s.model = "X2D 100C".into(); + let sensor = decode(&s.build(), &Limits::default()).unwrap(); + assert!(sensor.warnings.iter().any(|w| w.contains("Bayer phase")), "{:?}", sensor.warnings); } diff --git a/crates/raw/tests/it/nef_packed.rs b/crates/raw/tests/it/nef_packed.rs index 5e757a417a3..f050681857c 100644 --- a/crates/raw/tests/it/nef_packed.rs +++ b/crates/raw/tests/it/nef_packed.rs @@ -27,8 +27,7 @@ fn packed(values: &[u16], w: usize, bits: u32, padded: bool) -> Vec { #[test] fn packed_nef_uses_maker_mode_not_the_shared_tiff_compression() { - // craft-raw reads the measured layouts only: 12-bit rows of an even width, 14-bit rows of a multiple of 4. - let (w, h) = (24, 5); + let (w, h) = (22, 5); for (bits, mode) in [(12u32, 6u16), (14, 10)] { let values: Vec = (0..w * h).map(|i| ((i * 83 + 11) % (1 << bits)) as u16).collect(); for padded in [false, true] { @@ -71,14 +70,14 @@ fn packed_nef_rejects_truncation_wrong_depth_and_unknown_modes() { #[test] fn nikon_crop_area_uses_sensor_coordinates_and_ignores_invalid_rectangles() { - let strip = packed(&[1000; 24 * 10], 24, 14, true); + let strip = packed(&[1000; 22 * 10], 22, 14, true); for (rect, expected) in [ ([2, 2, 18, 6], photocraft_raw::Rect::new(2, 2, 18, 6)), - ([2, 2, 22, 10], photocraft_raw::Rect::new(0, 0, 24, 10)), - ([2, 2, 0, 6], photocraft_raw::Rect::new(0, 0, 24, 10)), - ([u32::MAX, 2, 18, 6], photocraft_raw::Rect::new(0, 0, 24, 10)), + ([2, 2, 22, 10], photocraft_raw::Rect::new(0, 0, 22, 10)), + ([2, 2, 0, 6], photocraft_raw::Rect::new(0, 0, 22, 10)), + ([u32::MAX, 2, 18, 6], photocraft_raw::Rect::new(0, 0, 22, 10)), ] { - let bytes = nef_compressed(24, 10, 14, strip.clone(), [0, 1, 1, 2], false, vec![(0x93, Val::Short(vec![10])), (0x45, Val::Long(rect.to_vec()))]); + let bytes = nef_compressed(22, 10, 14, strip.clone(), [0, 1, 1, 2], false, vec![(0x93, Val::Short(vec![10])), (0x45, Val::Long(rect.to_vec()))]); let sensor = photocraft_raw::decode(&bytes, &Limits::default()).unwrap(); assert_eq!(sensor.crop, expected); let developed = photocraft_raw::develop_sensor(&sensor, &Default::default()).unwrap(); diff --git a/crates/raw/tests/it/raf.rs b/crates/raw/tests/it/raf.rs index 8ccf4c4aad7..7ef82b8704d 100644 --- a/crates/raw/tests/it/raf.rs +++ b/crates/raw/tests/it/raf.rs @@ -6,32 +6,99 @@ use photocraft_raw::*; const RGGB: [u8; 4] = [0, 1, 1, 2]; -/// A 32×18 X-Trans RAF with a 2-pixel masked border. (Rows of 14-bit samples end on a 32-bit word -/// only when the width is a multiple of 16, which craft-raw's row slicing relies on.) +/// A 30×18 X-Trans RAF with a 2-pixel masked border, exercising padded rows. fn xtrans(packing: RafPacking, bits: u32) -> RafSpec { - let (w, h) = (32, 18); + let (w, h) = (30, 18); let white = ((1u32 << bits) - 1) as u16; let mut s = RafSpec::new(w, h, mosaic_cfa(&scene(w, h), w, &XTRANS, 6, 256, white), XTRANS.to_vec()); s.bits = bits; s.packing = packing; s.black = vec![256; 36]; - s.crop = Some([2, 2, 14, 28]); + s.crop = Some([2, 2, 14, 26]); s } #[test] fn every_storage_decodes_exactly() { - // (Big-endian 16-bit words are no RAF layout: the raw block is a little-endian TIFF.) - for (packing, bits) in [(RafPacking::U16 { le: true }, 14), (RafPacking::U16 { le: true }, 16), (RafPacking::Lsb12, 12), (RafPacking::Words14, 14)] { + for (packing, bits) in [(RafPacking::U16 { le: true }, 14), (RafPacking::U16 { le: false }, 16), (RafPacking::Lsb12, 12), (RafPacking::Words14, 14)] { let spec = xtrans(packing, bits); let b = spec.build(); assert_eq!(identify(&b), Some(RawFormat::Raf)); let s = decode(&b, &Limits::default()).unwrap_or_else(|e| panic!("{packing:?}: {e}")); - assert_eq!((s.width, s.height), (32, 18)); + assert_eq!((s.width, s.height), (30, 18)); assert_eq!(s.data, spec.data, "{packing:?}"); } } +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 + // 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); @@ -44,12 +111,17 @@ fn xtrans_metadata() { assert_eq!(cfa.color(i % 6, i / 6), c, "position {i}"); } assert!(!cfa.is_bayer()); - assert_eq!(s.crop, Rect::new(2, 2, 28, 14)); + assert_eq!(s.crop, Rect::new(2, 2, 26, 14)); assert_eq!(s.black, BlackLevels::uniform(256.0)); assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5])); + 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] @@ -59,8 +131,8 @@ fn xtrans_develops() { let b = spec.build(); for m in [Demosaic::Bilinear, Demosaic::Mhc, Demosaic::Ahd] { let d = develop(&b, &DevelopOptions { demosaic: m, ..Default::default() }).unwrap(); - // Cropped to 28×14, then rotated. - assert_eq!((d.width, d.height), (14, 28)); + // Cropped to 26×14, then rotated. + assert_eq!((d.width, d.height), (14, 26)); assert_eq!(d.info.format, RawFormat::Raf); // The repeat seen from the crop origin (2, 2). assert_eq!(d.info.cfa.as_deref(), Some("GRBGBR/BGGRGG/RGGBGG/GBRGRB/RGGBGG/BGGRGG")); @@ -84,9 +156,8 @@ fn xtrans_white_balance_is_per_site() { #[test] fn bayer_layouts() { - let (w, h) = (32, 16); - // craft-raw takes every Bayer RAF as RGGB at the data origin; only X-Trans files carry a layout record. - for cfa in [RGGB] { + let (w, h) = (24, 16); + for cfa in [RGGB, [2, 1, 1, 0]] { for (packing, bits) in [(RafPacking::Lsb12, 12), (RafPacking::Words14, 14), (RafPacking::U16 { le: true }, 14)] { let white = ((1u32 << bits) - 1) as u16; let data = mosaic_cfa(&scene(w, h), w, &cfa, 2, 64, white); @@ -95,7 +166,7 @@ fn bayer_layouts() { assert_eq!(s.data, spec.data); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), cfa, "{packing:?}"); let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); - assert_eq!(d.info.cfa.as_deref(), Some("RGGB")); + assert_eq!(d.info.cfa.as_deref(), Some(if cfa == RGGB { "RGGB" } else { "BGGR" })); } } } @@ -151,16 +222,18 @@ fn compressed_variants_that_cannot_be_decoded_fail_cleanly() { // The stream assumes a fixed CFA arrangement. let mut other = XTRANS; other.swap(0, 2); - let b = compressed(&other, 14, false).build(); - match decode(&b, &Limits::default()) { - Err(RawError::Unsupported(m)) => assert!(m.contains("unsupported CFA layout"), "{m}"), - other => panic!("expected unsupported, got {other:?}"), + 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("layout"), "{m}"), + other => panic!("expected unsupported, got {other:?}"), + } } // A short strip without the IS signature. let mut b = compressed(&XTRANS, 14, false).build(); let at = b.windows(5).position(|w| w == b"IS\x01\x10\x0e").unwrap(); b[at..at + 2].copy_from_slice(b"XX"); - assert!(decode(&b, &Limits::default()).is_err()); + assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_)))); // A damaged entropy stream (sizes intact, a run of zero bits inside the first stripe that // overruns the residual escape) is malformed, never a panic. let mut b = compressed(&XTRANS, 14, false).build(); @@ -188,6 +261,9 @@ fn unsupported_variants_report_and_keep_the_preview() { #[test] fn bad_layouts_and_sizes_fail_cleanly() { + // A Bayer FujiLayout that is not a Bayer pattern. + let spec = RafSpec::new(8, 4, vec![100; 32], vec![0, 0, 2, 2]); + assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Unsupported(_)))); // Dimensions beyond the limits are rejected before allocating. let spec = xtrans(RafPacking::U16 { le: true }, 14); let limits = Limits { max_pixels: 100, ..Limits::default() }; 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 4cfa9758070..6bbff143626 100644 --- a/crates/raw/tests/it/vendor_codecs.rs +++ b/crates/raw/tests/it/vendor_codecs.rs @@ -93,6 +93,9 @@ fn craw_unusual_variants_are_unsupported() { let codes32 = vec![300u16; 32 * h]; let ok = sony_craw(32, h, &codes32, CURVE); assert!(decode(&ok, &Limits::default()).is_ok()); + // A non-increasing tone curve is not guessed at. + let bad_curve = sony_craw(32, h, &codes32, [9000, 8000, 12000, 13000]); + assert!(matches!(decode(&bad_curve, &Limits::default()), Err(RawError::Unsupported(_)))); // Truncated strip. let cut = &ok[..ok.len() - 20]; assert!(decode(cut, &Limits::default()).is_err()); @@ -141,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)); @@ -150,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(); @@ -194,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)); } @@ -216,12 +223,14 @@ fn rw2_format4_crosses_pages() { /// A width that is not whole 14-pixel blocks never panics (craft-raw decodes the partial last block). #[test] -fn rw2_format4_odd_block_widths_do_not_panic() { +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); - let _ = decode(&b, &Limits::default()); + let s = decode(&b, &Limits::default()).unwrap(); + assert_eq!((s.width, s.height), (41, h)); + assert_eq!(s.data, data[..41 * h]); } #[test] @@ -229,15 +238,20 @@ 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()); - // Format 6 is decoded by craft-raw, and an unknown format number does not panic. + // Format 6 is supported by the shared reader. patch_ifd0_short(&mut b, 0x002D, 6); assert!(decode(&b, &Limits::default()).is_ok()); - patch_ifd0_short(&mut b, 0x002D, 99); - let _ = decode(&b, &Limits::default()); - // Width not made of whole blocks. + patch_ifd0_short(&mut b, 0x002D, 9); + match decode(&b, &Limits::default()) { + Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 9"), "{m}"), + other => panic!("expected unsupported, got {other:?}"), + } + // 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); - let _ = decode(&b, &Limits::default()); + 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); @@ -258,7 +272,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 05a4ec35e64..0167322b53b 100644 --- a/crates/raw/tests/it/vendors.rs +++ b/crates/raw/tests/it/vendors.rs @@ -76,6 +76,7 @@ fn nef_like_with_maker_tags() { let s = decode(&b, &Limits::default()).unwrap(); assert_eq!(s.data, data); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [2, 1, 1, 0]); + assert!(s.warnings.iter().any(|w| w.contains("black level"))); assert!(develop_sensor(&s, &DevelopOptions::default()).is_ok()); } @@ -109,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!(decode(&raf, &Limits::default()).is_err()); + assert!(matches!(decode(&raf, &Limits::default()), Err(RawError::Malformed(_)))); assert_eq!(decode(b"not a raw file", &Limits::default()).unwrap_err(), RawError::NotRaw); } @@ -181,6 +182,72 @@ fn assert_cr2_neutral(sensor: &Sensor) -> Developed { d } +#[test] +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. + // 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, 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})"); + // 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). + assert!((r / g - 1.0).abs() < 0.02 && (bl / g - 1.0).abs() < 0.02, "cfa {cfa:?} borders ({l}, {t}): grey patch {r:.0} {g:.0} {bl:.0}"); + } + } +} + +#[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. + let flat = |model_id| { + let mut spec = cr2_phase_spec([0, 1, 1, 2], 16, 4, model_id); + spec.data.iter_mut().for_each(|v| *v = 512); + decode(&spec.build(), &Limits::default()).unwrap() + }; + // 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); + // 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); +} + #[test] fn cr2_explicit_cfa_keeps_neutral_colour_across_phases_and_border_parity() { for (code, cfa) in [(1, [0, 1, 1, 2]), (2, [2, 1, 1, 0]), (3, [1, 2, 0, 1]), (4, [1, 0, 2, 1])] { @@ -210,3 +277,51 @@ fn cr2_missing_or_unknown_cfa_discloses_model_and_default_fallback_through_devel } } } + +fn cr2_phase_spec(cfa: [u8; 4], l: usize, t: usize, model_id: Option) -> Cr2Spec { + let (w, h) = (192usize, 96usize); + let wb = [2.0f32, 1.0, 1.5]; + let colourful = scene(w, h); + let rgb: Vec<[f32; 3]> = (0..w * h) + .map(|i| { + let p = if i % w >= w / 2 { [0.4; 3] } else { colourful[i] }; + [p[0] / wb[0], p[1] / wb[1], p[2] / wb[2]] + }) + .collect(); + let mut data = mosaic(&rgb, w, cfa, 512, 13000); + // Masked border: black. + for y in 0..h { + for x in 0..w { + if x < l || y < t { + data[y * w + x] = 512; + } + } + } + Cr2Spec { + width: w, + height: h, + data, + precision: 14, + components: 2, + slices: vec![96, 96], + borders: Some([l as u16, t as u16, w as u16 - 1, h as u16 - 1]), + wb_rggb: Some([2048, 1024, 1024, 1536]), + orientation: 1, + model_id, + } +} + +fn grey_patch(d: &Developed, x0: usize) -> [f64; 3] { + let (w, h) = (d.width as usize, d.height as usize); + let mut sum = [0f64; 3]; + let mut n = 0.0; + for y in 8..h - 8 { + for x in x0 + 8..w - 8 { + for (c, s) in sum.iter_mut().enumerate() { + *s += f64::from(d.rgb[(y * w + x) * 3 + c]); + } + n += 1.0; + } + } + sum.map(|s| s / n) +} 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; diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 488bfa3a910..1ae2be20035 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -533,6 +533,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 c8c598ea770..5bced96c17c 100644 --- a/crates/ui-egui/src/smart_svg_ui/tests.rs +++ b/crates/ui-egui/src/smart_svg_ui/tests.rs @@ -769,3 +769,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")))); +}