PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Formats: deep .pcraft groups reopen; zero-size PSD rejected; JPEG mattes over white; no-ICC formats get sRGB (#517, #519, #521, #522) (#555)
BFlat28682200326e
diff --git a/book/src/formats/pcraft.md b/book/src/formats/pcraft.mdindex 3d0d99f56..39385877a 100644--- a/book/src/formats/pcraft.md+++ b/book/src/formats/pcraft.md@@ -22,6 +22,8 @@ Default `LoadOptions` apply these maximums:| One decompressed blob | 1 GiB || Total decompressed tiles and blobs | 16 GiB |+Layer groups may nest at most 100 levels (`MAX_GROUP_DEPTH`). Saving a deeper document fails with an error instead of writing a bundle that can't be opened, and a manifest whose JSON nesting goes beyond what that depth needs is rejected before it is parsed, so a hostile file can't exhaust the stack.+The ZIP reader bounds decompression by the caller-supplied maximum, rejects encrypted entries and unsupported compression methods, validates offsets with checked arithmetic, and rejects CRC or declared-size mismatches. Corruption and property tests cover truncation, byte mutation, missing content, invalid manifests, excessive sizes, and random bytes.These defaults are intentionally finite but can still be expensive on constrained systems. Future hardening should add context-sensitive budgets and explicit limits for entry count, document complexity, and cumulative work, then test directory bundles against symlink and replacement races.diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.mdindex 693764d33..a2ee5ced0 100644--- a/book/src/formats/raster-formats.md+++ b/book/src/formats/raster-formats.md@@ -4,6 +4,13 @@Capability details such as sample depth, channel layout, alpha, ICC, EXIF, XMP, DPI, and animation behavior are defined by `crates/codecs/src/format.rs`. Do not infer fidelity from the filename extension alone.+## Exporting documents++Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_export`, Layers to Files, Layer › Export As) flattens it the same way:++- Formats without transparency (JPEG, Radiance HDR) get the image composited over white, as Export As and Quick Export do; in CMYK, white is no ink.+- Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead.+## Implemented decode limits`DecodeOptions::default()` applies `Limits` before decoded pixel allocation:diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.tomlindex a3108b40c..8198032ea 100644--- a/crates/format/Cargo.toml+++ b/crates/format/Cargo.toml@@ -16,7 +16,7 @@ photocraft-raster = { workspace = true }photocraft-doc = { workspace = true }photocraft-codecs = { workspace = true }serde = { workspace = true }-serde_json = { workspace = true }+serde_json = { workspace = true, features = ["unbounded_depth"] }thiserror = { workspace = true }flate2 = { workspace = true }blake3 = { version = "1.8", default-features = false, features = ["pure"] }diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rsindex 12381df09..13dace95b 100644--- a/crates/format/src/convert.rs+++ b/crates/format/src/convert.rs@@ -14,6 +14,25 @@ use photocraft_raster::{Surface, Tile, decode_pixel, encode_pixel};use crate::manifest::*;use crate::{FormatError, Result};+/// Deepest group nesting a bundle may hold (a layer inside this many nested groups is the deepest).+/// Saving and loading recurse once per level; at this depth both stay within a few hundred KiB of+/// stack, well inside the 1 MiB main-thread stacks of Windows and wasm.+pub const MAX_GROUP_DEPTH: usize = 100;++fn too_deep() -> FormatError {+ FormatError::LimitExceeded(format!("layer groups nested deeper than {MAX_GROUP_DEPTH}"))+}++/// Refuses to save a document the loader would reject for its group nesting.+pub(crate) fn check_nesting(layers: &[Layer]) -> Result<()> {+ // Bounded recursion: it stops at the first layer past the limit.+ fn too_deep_at(layers: &[Layer], depth: usize) -> bool {+ (depth > MAX_GROUP_DEPTH && !layers.is_empty())+ || layers.iter().any(|l| matches!(&l.content, LayerContent::Group(g) if too_deep_at(&g.children, depth + 1)))+ }+ if too_deep_at(layers, 0) { Err(too_deep()) } else { Ok(()) }+}+pub(crate) trait Sink {/// Register a tile, returning its hash.fn tile(&mut self, format: PixelFormat, tile: &Arc<Tile>) -> Hash;@@ -355,16 +374,27 @@ impl Loader<'_> {}fn layer(&mut self, m: &LayerM, depth: usize) -> Result<Layer> {- if depth > 256 {- return Err(FormatError::LimitExceeded("layer groups nested deeper than 256".into()));+ if depth > MAX_GROUP_DEPTH {+ return Err(too_deep());}+ // Children first, from this small frame: the conversion's large locals stay off the stack+ // that grows with each nesting level.+ let mut children = Vec::new();+ if let ContentM::Group { children: kids, .. } = &m.content {+ children.reserve(kids.len());+ for c in kids {+ children.push(self.layer(c, depth + 1)?);+ }+ }+ self.layer_with(m, children)+ }++ /// One layer, given its already converted group children.+ #[inline(never)]+ fn layer_with(&mut self, m: &LayerM, children: Vec<Layer>) -> Result<Layer> {let content = match &m.content {ContentM::Raster { surface } => LayerContent::Raster(self.surface(surface)?),- ContentM::Group { children, expanded, artboard } => LayerContent::Group(Group {- artboard: artboard.clone(),- children: children.iter().map(|c| self.layer(c, depth + 1)).collect::<Result<_>>()?,- expanded: *expanded,- }),+ ContentM::Group { expanded, artboard, .. } => LayerContent::Group(Group { artboard: artboard.clone(), children, expanded: *expanded }),ContentM::Adjustment { adjustment } => LayerContent::Adjustment(adjustment.clone()),ContentM::Fill { fill } => LayerContent::Fill(fill.clone()),ContentM::Text { text, font_family, size_pt, color, transform, cache, psd_raw, runs, paragraphs, shape, orientation, antialias, warp } => {diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rsindex 815851b0f..4b54457e9 100644--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@ -37,6 +37,7 @@ pub use atomic::atomic_write;#[cfg(not(target_arch = "wasm32"))]pub use autosave::RecoveryStore;pub use autosave::{Autosaver, RecoveryEntry, discard_recovery, list_recovery, recover};+pub use convert::MAX_GROUP_DEPTH;pub use manifest::{FORMAT_VERSION, Manifest};pub use store::{PcraftWriter, SaveStats};diff --git a/crates/format/src/store.rs b/crates/format/src/store.rsindex 22b9e4b82..ae4c74f4f 100644--- a/crates/format/src/store.rs+++ b/crates/format/src/store.rs@@ -10,7 +10,7 @@ use photocraft_doc::Document;use photocraft_raster::{Rgba8Image, Tile};use crate::convert::{self, Fetch, Loader, Sink, is_valid_hash, swap_to_le};-use crate::manifest::{FORMAT_VERSION, Hash, Manifest};+use crate::manifest::{ContentM, FORMAT_VERSION, Hash, LayerM, Manifest};use crate::zip::{ZipReader, ZipWriter};use crate::{FormatError, LoadOptions, Result, SaveOptions};@@ -92,11 +92,82 @@ impl Source for DirSource {// Loading// ---------------------------------------------------------------------------+/// Deepest JSON nesting a manifest may have: each group level adds three (the layer object, its+/// content object and the `children` array), with headroom for the document and leaf layer fields.+/// The saver checks the same bound, so every bundle it writes loads again.+const MAX_MANIFEST_DEPTH: usize = 3 * (convert::MAX_GROUP_DEPTH + 1) + 64;++/// Rejects JSON nested deeper than [`MAX_MANIFEST_DEPTH`] with a linear scan (no recursion), so+/// parsing with serde_json's recursion limit disabled can't exhaust the stack on hostile input.+fn check_manifest_depth(json: &[u8]) -> Result<()> {+ let (mut depth, mut in_str, mut escaped) = (0usize, false, false);+ for &b in json {+ if in_str {+ match b {+ _ if escaped => escaped = false,+ b'\\' => escaped = true,+ b'"' => in_str = false,+ _ => {}+ }+ continue;+ }+ match b {+ b'"' => in_str = true,+ b'[' | b'{' => {+ depth += 1;+ if depth > MAX_MANIFEST_DEPTH {+ return Err(FormatError::LimitExceeded(format!("manifest JSON nested deeper than {MAX_MANIFEST_DEPTH} levels")));+ }+ }+ b']' | b'}' => depth = depth.saturating_sub(1),+ _ => {}+ }+ }+ Ok(())+}+pub(crate) fn read_manifest(src: &dyn Source, opts: &LoadOptions) -> Result<Manifest> {let raw = src.get(MANIFEST, opts.max_manifest_bytes)?;- let mut v: serde_json::Value = serde_json::from_slice(&raw)?;+ // serde_json stops at 128 levels (about 40 nested groups); the bounded check replaces that limit.+ check_manifest_depth(&raw)?;+ let mut de = serde_json::Deserializer::from_slice(&raw);+ de.disable_recursion_limit();+ let mut v = <serde_json::Value as serde::Deserialize>::deserialize(&mut de)?;+ de.end()?;crate::migrate::migrate(&mut v)?;- Ok(serde_json::from_value(v)?)+ let layers = take_array(&mut v, "/document/layers");+ let mut m: Manifest = serde_json::from_value(v)?;+ m.document.layers = layers_from_json(layers)?;+ Ok(m)+}++/// Decodes layers one at a time, group children first. Decoding the whole tree in one go costs+/// kilobytes of stack per nesting level; here each level only holds a few pointers.+fn layers_from_json(values: Vec<serde_json::Value>) -> Result<Vec<LayerM>> {+ let mut out = Vec::with_capacity(values.len());+ for mut v in values {+ let children = layers_from_json(take_array(&mut v, "/content/children"))?;+ out.push(layer_from_json(v, children)?);+ }+ Ok(out)+}++/// One layer without its children (kept out of line so its large locals stay off the recursion).+#[inline(never)]+fn layer_from_json(v: serde_json::Value, children: Vec<LayerM>) -> Result<LayerM> {+ let mut layer: LayerM = serde_json::from_value(v)?;+ if let ContentM::Group { children: c, .. } = &mut layer.content {+ *c = children;+ }+ Ok(layer)+}++/// Takes the array at JSON `pointer` out of `v`, leaving an empty one (nothing if absent).+fn take_array(v: &mut serde_json::Value, pointer: &str) -> Vec<serde_json::Value> {+ match v.pointer_mut(pointer) {+ Some(serde_json::Value::Array(a)) => std::mem::take(a),+ _ => Vec::new(),+ }}struct LoadFetch<'a> {@@ -314,6 +385,7 @@ impl PcraftWriter {fn prepare(&mut self, doc: &Document, opts: &SaveOptions) -> Result<Prepared> {self.hash_cache.retain(|_, (w, _)| w.strong_count() > 0);+ convert::check_nesting(&doc.layers)?;let mut c = Collect { hash_cache: Some(&mut self.hash_cache), ..Default::default() };let document = convert::doc_m(doc, &mut c);let mut previews = Vec::new();@@ -331,6 +403,7 @@ impl PcraftWriter {composite: opts.composite.as_ref().map(|_| COMPOSITE.to_owned()),};let manifest = serde_json::to_vec_pretty(&manifest)?;+ check_manifest_depth(&manifest)?;let stats = SaveStats { tiles_total: c.tiles.len(), blobs_total: c.blobs.len(), manifest_bytes: manifest.len(), ..Default::default() };let mut objects = BTreeMap::new();for (h, (t, s)) in c.tiles {diff --git a/crates/format/tests/corruption.rs b/crates/format/tests/corruption.rsindex 92bb8a1e6..658c70d08 100644--- a/crates/format/tests/corruption.rs+++ b/crates/format/tests/corruption.rs@@ -77,6 +77,22 @@ fn bad_manifest_json() {assert!(matches!(load_from_bytes(&b), Err(FormatError::Json(_))));}+/// Hostile nesting fails with an error instead of overflowing the stack; nesting as deep as the+/// deepest groups a bundle may hold (three JSON levels each) parses, and is then rejected for+/// lacking a format version.+#[test]+fn over_deep_manifest_fails_cleanly() {+ let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n)).into_bytes();+ let with_manifest = |m: Vec<u8>| rebuild(&sample(), |n, d| Some(if n == "manifest.json" { m.clone() } else { d }));+ let e = load_from_bytes(&with_manifest(nested(100_000))).unwrap_err();+ assert!(matches!(e, FormatError::LimitExceeded(_)), "{e}");+ let e = load_from_bytes(&with_manifest(nested(3 * MAX_GROUP_DEPTH))).unwrap_err();+ assert!(matches!(e, FormatError::Corrupt(_)), "{e}");+ // Brackets inside strings (escaped quotes included) don't count.+ let e = load_from_bytes(&with_manifest(format!(r#"{{"x":"{}\"{}"}}"#, "[".repeat(100_000), "{".repeat(10)).into_bytes())).unwrap_err();+ assert!(matches!(e, FormatError::Corrupt(_)), "{e}");+}+#[test]fn too_new_version_rejected() {let b = rebuild(&sample(), |n, d| {diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rsindex 998bf3348..4a19ab3fa 100644--- a/crates/format/tests/roundtrip.rs+++ b/crates/format/tests/roundtrip.rs@@ -58,6 +58,44 @@ fn save_path_zip_file() {std::fs::remove_dir_all(dir).unwrap();}+/// Deepest group nesting in `layers` (0 when there are no groups).+fn group_depth(layers: &[Layer]) -> usize {+ layers.iter().map(|l| if let photocraft_doc::LayerContent::Group(g) = &l.content { 1 + group_depth(&g.children) } else { 0 }).max().unwrap_or(0)+}++/// [`rich_doc`] with its layers wrapped in groups until they are nested `levels` deep.+fn nested_doc(levels: usize, depth: SampleType) -> Document {+ let mut doc = rich_doc(ColorMode::Rgb, depth);+ let mut layers = std::mem::take(&mut doc.layers);+ for i in group_depth(&layers)..levels {+ layers = vec![Layer::group(format!("Level {i}"), layers)];+ }+ doc.layers = layers;+ assert_eq!(group_depth(&doc.layers), levels);+ doc+}++/// serde_json's default limit (128 levels) used to make bundles with 40+ nested groups unreadable.+/// Runs on a 1 MiB stack, the smallest main-thread stack we ship on (Windows, wasm).+#[test]+fn deeply_nested_groups_roundtrip() {+ let run = || {+ for (levels, depth) in [(40, SampleType::U8), (MAX_GROUP_DEPTH, SampleType::U16), (MAX_GROUP_DEPTH, SampleType::F32)] {+ let doc = nested_doc(levels, depth);+ let back = load_from_bytes(&save_to_bytes(&doc, &SaveOptions::default()).unwrap()).unwrap();+ assert_eq!(back, doc, "{levels} levels at {depth:?}");+ }+ };+ std::thread::Builder::new().stack_size(1 << 20).spawn(run).unwrap().join().unwrap();+}++/// A save never writes a bundle the loader would reject for its nesting.+#[test]+fn nesting_beyond_the_load_limit_is_refused_at_save() {+ let e = save_to_bytes(&nested_doc(MAX_GROUP_DEPTH + 1, SampleType::U8), &SaveOptions::default()).unwrap_err();+ assert!(matches!(e, FormatError::LimitExceeded(_)), "{e}");+}+#[test]fn empty_document_roundtrips() {let doc = Document::new("empty", photocraft_doc::Size::new(1, 1), ColorMode::Rgb, SampleType::U8);diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rsindex 9eecad5b1..b6c07a7e2 100644--- a/crates/io/src/flat.rs+++ b/crates/io/src/flat.rs@@ -255,17 +255,33 @@ fn opaque_surface(s: &Surface, r: Rect) -> bool {/// Flattens and encodes as `format`.pub fn export_flat(doc: &Document, format: Format, opts: &ExportOptions) -> Result<ExportResult, IoError> {+ use photocraft_cms::{Builtin, Intent};if let Some(r) = export_mode_specific(doc, format, opts)? {return Ok(r);}let mut warnings = Vec::new();let mut img = document_to_image(doc, &mut warnings)?;+ if img.layout().has_alpha() && !format.caps().alpha {+ // Flattened over white, as saving a transparent document without transparency does.+ img = matte_over_white(&img)?;+ warnings.push(format!("transparency composited over white for {format:?}"));+ }if img.layout().is_cmyk() && !format.caps().layouts.iter().any(|l| l.is_cmyk()) {img = cmyk_image_to_srgb(&img)?;warnings.push(format!("CMYK converted to sRGB for {format:?} through the document's colour profile"));}if matches!(format, Format::OpenExr | Format::Hdr) {- img = rgb_image_to_linear(img)?;+ // OpenEXR and Radiance HDR store linear light (read back as linear sRGB, see [`import_flat`]).+ if let Some(linear) = convert_rgb(&img, Builtin::LinearSrgb.profile(), Intent::RelativeColorimetric, false, CSample::F32)? {+ img = linear;+ }+ } else if !format.caps().icc {+ // Untagged files read back as sRGB: convert to it (as Quick Export does) rather than+ // write values that only mean something under the dropped profile.+ if let Some(srgb) = convert_rgb(&img, Builtin::Srgb.profile(), Intent::Perceptual, true, img.sample_type())? {+ img = srgb;+ warnings.push(format!("colours converted to sRGB; {format:?} can't embed the document's colour profile"));+ }}for w in codecs::fidelity_warnings_with(&img, format, &opts.encode) {if w.is_fatal() {@@ -277,6 +293,59 @@ pub fn export_flat(doc: &Document, format: Format, opts: &ExportOptions) -> ResuOk(ExportResult { bytes, warnings })}+/// `img` with every band of rows mapped by `f` (normalized samples in, normalized `layout`+/// samples out) and stored as `sample`, so no full-size float copy is made. Profile and metadata+/// are kept.+fn map_bands(img: &Image, layout: ChannelLayout, sample: CSample, f: impl Fn(Vec<f32>) -> Vec<f32>) -> Result<Image, IoError> {+ let (w, h) = img.dimensions();+ let row = img.data().len() / (h.max(1) as usize);+ let band = row.max(1) * (BAND_BYTES / row.max(1)).max(1);+ let mut data = try_buffer(img.pixel_count(), layout.channels() * sample.bytes())?;+ for rows in img.data().chunks(band) {+ let n = (rows.len() / row.max(1)) as u32;+ let vals = f(Image::from_raw(w, n, img.layout(), img.sample_type(), rows.to_vec())?.to_normalized());+ data.extend_from_slice(Image::from_normalized(w, n, layout, sample, &vals)?.data());+ }+ Ok(Image::from_raw(w, h, layout, sample, data)?.with_icc(img.icc.clone()).with_meta(img.meta.clone()))+}++/// Straight-alpha pixels composited over white (no ink for CMYK), without the alpha channel.+fn matte_over_white(img: &Image) -> Result<Image, IoError> {+ let layout = img.layout();+ let white = if layout.is_cmyk() { 0.0 } else { 1.0 };+ map_bands(img, layout.without_alpha(), img.sample_type(), |vals| {+ let mut out = Vec::with_capacity(vals.len() / layout.channels() * layout.color_channels());+ for px in vals.chunks_exact(layout.channels()) {+ if let Some((&a, color)) = px.split_last() {+ let a = a.clamp(0.0, 1.0);+ out.extend(color.iter().map(|&c| c * a + white * (1.0 - a)));+ }+ }+ out+ })+}++/// RGB pixels converted from their profile (sRGB when untagged) to `dst`, unclamped, untagged and+/// stored as `sample`. `None` when the image isn't RGB or already holds `dst`'s colours.+fn convert_rgb(img: &Image, dst: &photocraft_cms::Profile, intent: photocraft_cms::Intent, bpc: bool, sample: CSample) -> Result<Option<Image>, IoError> {+ use photocraft_cms::{Builtin, ColorSpace, Profile, Transform};+ if !img.layout().is_rgb() {+ return Ok(None);+ }+ let src =+ img.icc.as_ref().and_then(|b| Profile::parse(b).ok()).filter(|p| p.color_space == ColorSpace::Rgb).unwrap_or_else(|| Builtin::Srgb.profile().clone());+ if src.same_colors(dst) {+ return Ok(None);+ }+ let t = Transform::new(&src, dst, intent, bpc).map_err(|e| IoError::Unsupported(e.to_string()))?;+ let stride = img.layout().channels();+ let out = map_bands(img, img.layout(), sample, |mut vals| {+ t.apply(&mut vals, stride);+ vals+ })?;+ Ok(Some(out.with_icc(None)))+}+/// Colour-managed CMYK → sRGB for formats that cannot store CMYK (the document's embedded/// CMYK profile when it parses, else the built-in coated CMYK; relative colorimetric + BPC).fn cmyk_image_to_srgb(img: &Image) -> Result<Image, IoError> {@@ -303,27 +372,6 @@ fn cmyk_image_to_srgb(img: &Image) -> Result<Image, IoError> {Ok(Image::from_normalized(w, h, layout, sample, &out)?.with_icc(Some(dst.to_bytes().to_vec())).with_meta(img.meta.clone()))}-/// OpenEXR and Radiance HDR store linear light (read back as linear sRGB, see [`import_flat`]):-/// RGB pixels in another profile (sRGB when untagged) are converted to linear sRGB, unclamped.-fn rgb_image_to_linear(img: Image) -> Result<Image, IoError> {- use photocraft_cms::{Builtin, ColorSpace, Intent, Profile, Transform};- if !matches!(img.layout(), ChannelLayout::Rgb | ChannelLayout::Rgba) {- return Ok(img);- }- let linear = Builtin::LinearSrgb.profile();- let src =- img.icc.as_ref().and_then(|b| Profile::parse(b).ok()).filter(|p| p.color_space == ColorSpace::Rgb).unwrap_or_else(|| Builtin::Srgb.profile().clone());- if src.content_hash() == linear.content_hash() {- return Ok(img);- }- let t = Transform::new(&src, linear, Intent::RelativeColorimetric, false).map_err(|e| IoError::Unsupported(e.to_string()))?;- let stride = img.layout().channels();- let mut vals = img.to_normalized();- t.apply(&mut vals, stride);- let (w, h) = img.dimensions();- Ok(Image::from_normalized(w, h, img.layout(), CSample::F32, &vals)?.with_icc(None).with_meta(img.meta.clone()))-}-/// Indexed Color → PNG-8 with its colour table; Duotone → the inks rendered as RGB.fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> Result<Option<ExportResult>, IoError> {match doc.mode {diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex be7d50bc5..766373cc5 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -166,6 +166,8 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Resultif ext == "psd" || ext == "psb" {let o = PsdExportOptions { force_psb: opts.force_psb || ext == "psb" };let (file, warnings) = document_to_psd_with(doc, &o);+ // Never write a header the reader would refuse (e.g. a zero-sized canvas).+ file.header.validate()?;let bytes = file.to_bytes()?;return Ok(ExportResult { bytes, warnings });}diff --git a/crates/io/tests/flat.rs b/crates/io/tests/flat.rsindex b70b39155..0d3b3862d 100644--- a/crates/io/tests/flat.rs+++ b/crates/io/tests/flat.rs@@ -225,3 +225,111 @@ fn psd_to_png_to_psd_chain() {let psd2 = export(&d3, "b.psd", &ExportOptions::default()).unwrap();assert!(photocraft_psd::PsdFile::from_bytes(&psd2.bytes).is_ok());}++/// A one-layer document of 16-pixel-wide columns, each one straight colour (colour channels, then alpha).+fn columns(mode: ColorMode, depth: SampleType, cols: &[&[f32]]) -> photocraft_doc::Document {+ let mut d = photocraft_doc::Document::new("c", photocraft_geom::Size::new(16 * cols.len() as u32, 16), mode, depth);+ let mut s = photocraft_raster::Surface::new(d.pixel_format());+ for (i, px) in cols.iter().enumerate() {+ let x = 16 * i as i32;+ s.fill_rect(photocraft_geom::Rect::new(x, 0, x + 16, 16), px);+ }+ d.layers.push(photocraft_doc::Layer::new("Layer", photocraft_doc::LayerContent::Raster(s)));+ d+}++/// The pixel at the centre of each column of `doc`.+fn column_pixels(doc: &photocraft_doc::Document, n: usize) -> Vec<Vec<f32>> {+ let s = doc.layers[0].surface().unwrap();+ (0..n).map(|i| s.pixel(16 * i as i32 + 8, 8)).collect()+}++/// Asserts the leading (colour) channels of `got` are within `tol` of `want`.+fn assert_colors(got: &[Vec<f32>], want: &[Vec<f32>], tol: f32, what: &str) {+ for (g, w) in got.iter().zip(want) {+ assert!(w.iter().zip(g).all(|(a, b)| (a - b).abs() <= tol), "{what}: got {got:?}, want {want:?}");+ }+}++/// Formats without alpha get the document composited over white, as flattening does, instead of+/// its alpha dropped (which shows the colours stored under transparent pixels).+#[test]+fn transparency_is_composited_over_white_for_formats_without_alpha() {+ let rgb: [&[f32]; 3] = [&[0.0, 0.0, 0.0, 0.0], &[0.0, 0.0, 1.0, 0.5], &[0.0, 0.63, 0.0, 1.0]];+ let over_white = vec![vec![1.0, 1.0, 1.0], vec![0.5, 0.5, 1.0], vec![0.0, 0.63, 0.0]];+ let gray: [&[f32]; 2] = [&[0.0, 0.0], &[0.0, 0.5]];+ // CMYK white is no ink.+ let cmyk: [&[f32]; 2] = [&[1.0, 1.0, 1.0, 1.0, 0.0], &[0.0, 0.0, 0.0, 1.0, 0.5]];+ let cases = [+ (ColorMode::Rgb, SampleType::U8, &rgb[..], over_white.clone()),+ (ColorMode::Rgb, SampleType::U16, &rgb[..], over_white.clone()),+ (ColorMode::Rgb, SampleType::F32, &rgb[..], over_white),+ (ColorMode::Grayscale, SampleType::U8, &gray[..], vec![vec![1.0], vec![0.5]]),+ (ColorMode::Cmyk, SampleType::U8, &cmyk[..], vec![vec![0.0; 4], vec![0.0, 0.0, 0.0, 0.5]]),+ ];+ for (mode, depth, cols, want) in cases {+ let what = format!("{mode:?} {depth:?}");+ let d = columns(mode, depth, cols);+ let r = export(&d, "a.jpg", &ExportOptions::default()).unwrap();+ assert!(r.warnings.iter().any(|w| w.contains("composited over white")), "{what}: {:?}", r.warnings);+ assert!(!r.warnings.iter().any(|w| w.contains("alpha will be discarded")), "{what}: {:?}", r.warnings);+ let back = import("a.jpg", &r.bytes).unwrap().document;+ assert_eq!(back.mode, mode, "{what}");+ assert_colors(&column_pixels(&back, cols.len()), &want, 0.03, &what);+ // PNG keeps the transparency itself.+ let r = export(&d, "a.png", &ExportOptions::default()).unwrap();+ assert!(!r.warnings.iter().any(|w| w.contains("composited")), "{what}: {:?}", r.warnings);+ let back = import("a.png", &r.bytes).unwrap().document;+ let alpha = column_pixels(&back, cols.len())[1].last().copied().unwrap();+ assert!((alpha - 0.5).abs() <= 1.0 / 255.0, "{what}: alpha {alpha}");+ }+ // Opaque documents are written as before.+ let r = export(&columns(ColorMode::Rgb, SampleType::U8, &[&[0.2, 0.4, 0.6, 1.0]]), "a.jpg", &ExportOptions::default()).unwrap();+ assert!(!r.warnings.iter().any(|w| w.contains("composited")), "{:?}", r.warnings);+}++/// Formats that can't embed a profile get sRGB values (what an untagged file means), converted+/// through the colour engine, instead of values that only mean something under the dropped profile.+#[test]+fn non_srgb_rgb_is_converted_to_srgb_for_formats_without_a_profile() {+ use photocraft_cms::{Builtin, Intent, Transform};+ let cols: [&[f32]; 3] = [&[0.0, 0.05, 0.0, 1.0], &[0.2, 0.5, 0.8, 1.0], &[1.0, 0.25, 0.0, 1.0]];+ for (profile, depth) in [(Builtin::LinearSrgb, SampleType::F32), (Builtin::LinearSrgb, SampleType::U16), (Builtin::DisplayP3, SampleType::U8)] {+ let mut d = columns(ColorMode::Rgb, depth, &cols);+ d.icc_profile = Some(profile.profile().to_bytes());+ let stored = column_pixels(&d, cols.len());+ let t = Transform::new(profile.profile(), Builtin::Srgb.profile(), Intent::Perceptual, true).unwrap();+ let want: Vec<Vec<f32>> = stored+ .iter()+ .map(|p| {+ let mut v = p.clone();+ t.apply(&mut v, 4);+ // The formats hold 8-bit sRGB: out-of-gamut colours clip.+ v.iter().map(|c| c.clamp(0.0, 1.0)).collect()+ })+ .collect();+ for ext in ["bmp", "gif", "qoi", "tga"] {+ let what = format!("{profile:?} {depth:?} {ext}");+ let r = export(&d, ext, &ExportOptions::default()).unwrap();+ assert!(r.warnings.iter().any(|w| w.contains("converted to sRGB")), "{what}: {:?}", r.warnings);+ assert!(!r.warnings.iter().any(|w| w.contains("ICC profile")), "{what}: {:?}", r.warnings);+ let back = import(&format!("a.{ext}"), &r.bytes).unwrap().document;+ assert_eq!(back.icc_profile, None, "{what}");+ assert_colors(&column_pixels(&back, cols.len()), &want, 1.5 / 255.0, &what);+ }+ // Formats that embed the profile keep it and the values.+ let r = export(&d, "a.png", &ExportOptions::default()).unwrap();+ let back = import("a.png", &r.bytes).unwrap().document;+ assert_eq!(back.icc_profile, d.icc_profile, "{profile:?} {depth:?}");+ assert_colors(&column_pixels(&back, cols.len()), &stored, 1e-4, &format!("{profile:?} {depth:?} png"));+ }+ // sRGB (tagged or not) is written unchanged.+ for icc in [None, Some(Builtin::Srgb.profile().to_bytes())] {+ let mut d = columns(ColorMode::Rgb, SampleType::U8, &cols);+ d.icc_profile = icc;+ let r = export(&d, "a.bmp", &ExportOptions::default()).unwrap();+ assert!(!r.warnings.iter().any(|w| w.contains("converted to sRGB")), "{:?}", r.warnings);+ let back = import("a.bmp", &r.bytes).unwrap().document;+ assert_colors(&column_pixels(&back, cols.len()), &column_pixels(&d, cols.len()), 0.0, "sRGB bmp");+ }+}diff --git a/crates/io/tests/roundtrip.rs b/crates/io/tests/roundtrip.rsindex 82e6e5cc5..81e00e4f2 100644--- a/crates/io/tests/roundtrip.rs+++ b/crates/io/tests/roundtrip.rs@@ -73,6 +73,22 @@ fn empty_document() {assert_eq!(back.size, d.size);}+/// A header declaring a zero width or height is corrupt (the spec range starts at 1): opening it+/// fails instead of producing an empty document, and a zero-sized document is never written.+#[test]+fn zero_sized_psd_is_rejected() {+ let d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS);+ let good = export(&d, "x.psd", &ExportOptions::default()).unwrap().bytes;+ for range in [14..18, 18..22, 14..22] {+ let mut b = good.clone();+ b[range.clone()].fill(0);+ let err = import("z.psd", &b).expect_err("zero-sized header must not open");+ assert!(err.to_string().contains("at least 1x1"), "{range:?}: {err}");+ }+ let empty = photocraft_doc::Document::new("e", photocraft_geom::Size::new(0, 3), ColorMode::Rgb, SampleType::U8);+ assert!(export(&empty, "x.psd", &ExportOptions::default()).is_err());+}+#[test]fn round_trip_reaches_a_fixed_point() {// The first export renders fill layers ourselves; after import they carrydiff --git a/crates/psd/src/header.rs b/crates/psd/src/header.rsindex 229a0c7dc..d99555be2 100644--- a/crates/psd/src/header.rs+++ b/crates/psd/src/header.rs@@ -153,6 +153,9 @@ impl Header {if self.channels == 0 || self.channels > MAX_CHANNELS {return Err(PsdError::invalid(format!("channel count {} out of range 1..=56", self.channels)));}+ if self.width == 0 || self.height == 0 {+ return Err(PsdError::invalid(format!("image dimensions {}x{} must be at least 1x1", self.width, self.height)));+ }if self.width > MAX_DIMENSION || self.height > MAX_DIMENSION {return Err(PsdError::LimitExceeded("image dimensions exceed 300000"));}@@ -218,6 +221,9 @@ mod tests {fn limits() {for h in [Header::new(Version::Psd, 300_001, 1, 1, 8, ColorMode::Rgb),+ Header::new(Version::Psd, 0, 1, 1, 8, ColorMode::Rgb),+ Header::new(Version::Psd, 1, 0, 1, 8, ColorMode::Rgb),+ Header::new(Version::Psb, 0, 0, 1, 8, ColorMode::Rgb),Header::new(Version::Psd, 1, 1, 0, 8, ColorMode::Rgb),Header::new(Version::Psd, 1, 1, 57, 8, ColorMode::Rgb),Header::new(Version::Psd, 1, 1, 3, 12, ColorMode::Rgb),diff --git a/crates/psd/src/testgen.rs b/crates/psd/src/testgen.rsindex 5d4762846..d2d4784cb 100644--- a/crates/psd/src/testgen.rs+++ b/crates/psd/src/testgen.rs@@ -375,7 +375,7 @@ pub fn all_cases() -> Vec<Case> {for c in Compression::ALL {v.push(Case { name: format!("small {version:?} {c:?}"), file: small(version, c) });}- v.push(Case { name: format!("empty canvas {version:?}"), file: merged_only(version, ColorMode::Rgb, 8, Compression::Rle, 0, 0) });+ v.push(Case { name: format!("1x1 canvas {version:?}"), file: merged_only(version, ColorMode::Rgb, 8, Compression::Rle, 1, 1) });}v}diff --git a/crates/psd/tests/malformed.rs b/crates/psd/tests/malformed.rsindex 68ee87013..85968e72c 100644--- a/crates/psd/tests/malformed.rs+++ b/crates/psd/tests/malformed.rs@@ -91,6 +91,21 @@ fn oversized_dimensions_rejected() {assert!(matches!(PsdFile::from_bytes(&b), Err(PsdError::LimitExceeded(_))));}+#[test]+fn zero_dimensions_rejected() {+ // Height is bytes 14..18 and width 18..22; the spec range starts at 1.+ let good = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap();+ for range in [14..18, 18..22, 14..22] {+ let mut b = good.clone();+ b[range.clone()].fill(0);+ let err = PsdFile::from_bytes(&b).unwrap_err();+ assert!(err.to_string().contains("at least 1x1"), "{range:?}: {err}");+ }+ let mut f = testgen::small(Version::Psd, Compression::Raw);+ f.header.width = 0;+ assert!(f.validate().is_err(), "a zero-sized header must not pass the writer's validation");+}+#[test]fn huge_declared_dimensions_small_data() {// 300000² RLE image with 16 bytes of data must fail fast, not allocate.diff --git a/crates/psd/tests/proptests.rs b/crates/psd/tests/proptests.rsindex 58a02de4f..264633980 100644--- a/crates/psd/tests/proptests.rs+++ b/crates/psd/tests/proptests.rs@@ -71,7 +71,7 @@ proptest! {#[test]fn merged_only_random_sizes_roundtrip(- w in 0u32..30, h in 0u32..10, v in version(), c in compression(), mode_ix in 0usize..8, depth_ix in 0usize..3,+ w in 1u32..30, h in 1u32..10, v in version(), c in compression(), mode_ix in 0usize..8, depth_ix in 0usize..3,) {let mode = testgen::MODES[mode_ix];let depths = testgen::mode_depths(mode);