diff --git a/Cargo.lock b/Cargo.lock index 860de3aae0..a17c944f80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -334,7 +334,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -1453,6 +1453,26 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-kra" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55d120f201771acbb32b2cf122d4a6dc82593a57#55d120f201771acbb32b2cf122d4a6dc82593a57" +dependencies = [ + "craft-xml", + "craft-zip", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-ora" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55d120f201771acbb32b2cf122d4a6dc82593a57#55d120f201771acbb32b2cf122d4a6dc82593a57" +dependencies = [ + "craft-xml", + "craft-zip", + "thiserror 2.0.21", +] + [[package]] name = "craft-pcraft-format" version = "0.1.0" @@ -1475,6 +1495,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pdn" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55d120f201771acbb32b2cf122d4a6dc82593a57#55d120f201771acbb32b2cf122d4a6dc82593a57" +dependencies = [ + "flate2", + "thiserror 2.0.21", +] + [[package]] name = "craft-print" version = "0.1.0" @@ -1545,6 +1574,34 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "craft-xcf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55d120f201771acbb32b2cf122d4a6dc82593a57#55d120f201771acbb32b2cf122d4a6dc82593a57" +dependencies = [ + "flate2", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55d120f201771acbb32b2cf122d4a6dc82593a57#55d120f201771acbb32b2cf122d4a6dc82593a57" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55d120f201771acbb32b2cf122d4a6dc82593a57#55d120f201771acbb32b2cf122d4a6dc82593a57" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -2196,7 +2253,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5095,7 +5152,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5629,7 +5686,11 @@ version = "0.23.1" dependencies = [ "blake3", "craft-docpath", + "craft-kra", + "craft-ora", "craft-pdf", + "craft-pdn", + "craft-xcf", "crc32fast", "flate2", "imagesize", @@ -6312,7 +6373,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6874,7 +6935,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6943,7 +7004,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -7877,10 +7938,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -9205,7 +9266,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e54a0c59c7..622fbe9b16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,13 @@ photocraft-tablet = { path = "crates/tablet" } photocraft-ipp = { path = "crates/ipp" } # external +# Krita, OpenRaster and GIMP XCF: the format code (archives, node trees, tiles); the mapping onto +# documents stays in crates/io (craft-libs#928, #935, #960). +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "55d120f201771acbb32b2cf122d4a6dc82593a57" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "55d120f201771acbb32b2cf122d4a6dc82593a57" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "55d120f201771acbb32b2cf122d4a6dc82593a57" } +# Paint.NET PDN3 and its MS-NRBF serialization (craft-libs#968). +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "55d120f201771acbb32b2cf122d4a6dc82593a57" } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "081078bb1b44aeedfa5bef3d4f13d978dc77510a" } diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 2090bdb00f..2cbf8ec0d6 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -37,6 +37,10 @@ photocraft-paint = { workspace = true } photocraft-vector = { workspace = true } photocraft-format = { path = "../format" } craft-docpath = { workspace = true } +craft-kra = { workspace = true } +craft-ora = { workspace = true } +craft-xcf = { workspace = true } +craft-pdn = { workspace = true } thiserror = { workspace = true } ttf-parser = "0.25.1" serde_json = { workspace = true } @@ -44,7 +48,7 @@ blake3 = { version = "1.8", default-features = false, features = ["pure"] } # svg.rs inflates `.svgz` itself (with a size cap) so the XML can be checked before it is parsed; # pdn.rs inflates Paint.NET's gzip pixel chunks. flate2 = { workspace = true } -# ora.rs reads OpenRaster's stack.xml (already in the tree through usvg). +# xml.rs parses XML behind a depth guard (already in the tree through usvg). roxmltree = "0.21" # Reuse usvg's locked header reader to bound embedded SVG raster data before decoding. imagesize = "0.13" diff --git a/crates/io/src/kra.rs b/crates/io/src/kra.rs index d8b3f9a36d..a69c422ddd 100644 --- a/crates/io/src/kra.rs +++ b/crates/io/src/kra.rs @@ -20,66 +20,36 @@ mod tests; mod tiles; +use craft_kra::tiles::{Space, TileFile}; +use craft_kra::{Archive, Node}; use photocraft_color::{BlendMode, PixelFormat}; use photocraft_doc::{Document, Layer, LayerContent, LayerMask}; -use photocraft_format::zip::ZipReader; use photocraft_geom::Size; use photocraft_raster::{Interrupt, Surface}; -use crate::ora::{MAX_NODES, MAX_PIXEL_BYTES, MAX_SIDE, Warnings, krita_blend}; +use crate::ora::{MAX_PIXEL_BYTES, Warnings, krita_blend}; use crate::{ImportResult, IoError}; -use tiles::{Space, TileFile}; +use tiles::SpaceExt; + +pub(crate) use craft_kra::{EXTENSIONS, is_kra}; type Result = std::result::Result; -/// The `mimetype` entry of a Krita archive. -pub(crate) const MIMETYPE: &[u8] = b"application/x-krita"; -pub(crate) const EXTENSIONS: [&str; 2] = ["kra", "krz"]; -const MAX_MAINDOC: usize = 32 << 20; -const MAX_LAYER_FILE: usize = 1 << 30; - fn invalid(message: impl Into) -> IoError { IoError::Kra(message.into()) } -/// `true` for a Krita archive (by its `mimetype` entry). -pub(crate) fn is_kra(bytes: &[u8]) -> bool { - crate::ora::zip_mimetype(bytes).is_some_and(|mime| mime.trim_ascii() == MIMETYPE) -} - -fn attr<'a>(node: roxmltree::Node<'a, '_>, name: &str) -> Option<&'a str> { - node.attribute(name).map(str::trim) -} - -fn number(node: roxmltree::Node<'_, '_>, name: &str, default: f64) -> Result { - match attr(node, name) { - None | Some("") => Ok(default), - Some(v) => v.parse::().ok().filter(|v| v.is_finite()).ok_or_else(|| invalid(format!("invalid {name} attribute `{v}`"))), +/// The format crate's error as this crate's. +fn kra_err(e: craft_kra::Error) -> IoError { + match e { + craft_kra::Error::Invalid(m) => invalid(m), + craft_kra::Error::Unsupported(m) => IoError::Unsupported(m), } } -fn offset(node: roxmltree::Node<'_, '_>, name: &str) -> Result { - let v = number(node, name, 0.0)?.round(); - if v.abs() > f64::from(MAX_SIDE) * 4.0 { - return Err(invalid(format!("{name} offset {v} is out of range"))); - } - Ok(v as i32) -} - -fn truthy(node: roxmltree::Node<'_, '_>, name: &str) -> bool { - matches!(attr(node, name), Some("1" | "true")) -} - -/// Child elements named `tag` inside the node's `` element (`layers` or `masks`). -fn children<'a, 'i>(node: roxmltree::Node<'a, 'i>, container: &str, tag: &'static str) -> impl Iterator> { - node.children().filter(move |c| c.has_tag_name(container)).flat_map(move |c| c.children().filter(move |n| n.has_tag_name(tag))) -} - struct Reader<'a, 'c> { - zip: ZipReader<'a>, + archive: Archive<'a>, ctl: &'c Interrupt<'c>, - /// `/layers/`. - dir: String, /// The document's pixel format (layers in another supported space are converted to it). fmt: PixelFormat, nodes: usize, @@ -88,49 +58,32 @@ struct Reader<'a, 'c> { } impl Reader<'_, '_> { - fn file(&self, name: &str) -> Result>> { - let path = format!("{}{name}", self.dir); - match self.zip.find(&path) { - None => Ok(None), - Some(e) => self.zip.read(e, MAX_LAYER_FILE).map(Some).map_err(|err| invalid(format!("{path}: {err}"))), - } - } - - /// The default pixel Krita stores next to a tiled file, decoded to `space` samples. - fn default_pixel(&self, name: &str, space: Space) -> Result>> { - let Some(bytes) = self.file(&format!("{name}.defaultpixel"))? else { return Ok(None) }; - if bytes.len() != space.pixel_size() { - return Err(invalid(format!("{name}.defaultpixel has {} bytes, expected {}", bytes.len(), space.pixel_size()))); - } - Ok(Some(space.normalised(&bytes))) - } - /// A tiled pixel file in `space` as a surface in `fmt`, offset by (`dx`, `dy`). fn surface(&mut self, name: &str, space: Space, fmt: PixelFormat, dx: i32, dy: i32) -> Result> { - let Some(bytes) = self.file(name)? else { return Ok(None) }; - let file = TileFile::parse(&bytes)?; + let Some(bytes) = self.archive.layer_file(name).map_err(kra_err)? else { return Ok(None) }; + let file = TileFile::parse(&bytes).map_err(kra_err)?; if file.pixel_size != space.pixel_size() { return Err(invalid(format!("{name}: pixel size {} does not match its colour space", file.pixel_size))); } - let cost = file.decoded_bytes(fmt.bytes_per_pixel(), dx, dy)?; + let cost = tiles::decoded_bytes(&file, fmt.bytes_per_pixel(), dx, dy)?; self.budget = self.budget.checked_sub(cost).ok_or_else(|| invalid("decoded layers exceed the 1 GiB limit"))?; - let mut surface = match self.default_pixel(name, space)? { + let mut surface = match self.archive.default_pixel(name, space).map_err(kra_err)? { Some(px) if px.iter().any(|v| *v != 0.0) => Surface::with_default(fmt, &space.to_format(&px, fmt)), _ => Surface::new(fmt), }; - file.decode_into(&mut surface, space, dx, dy, self.ctl)?; + tiles::decode_into(&file, &mut surface, space, dx, dy, self.ctl)?; surface.prune(); Ok(Some(surface)) } - fn props(&mut self, node: roxmltree::Node<'_, '_>, layer: &mut Layer) -> Result<()> { - layer.name = attr(node, "name").filter(|n| !n.is_empty()).map_or_else(|| format!("Layer {}", self.nodes), str::to_string); - layer.visible = attr(node, "visible") != Some("0"); - layer.opacity = (number(node, "opacity", 255.0)? / 255.0).clamp(0.0, 1.0) as f32; - if truthy(node, "locked") { + fn props(&mut self, node: &Node, layer: &mut Layer) { + layer.name = node.name.as_deref().filter(|n| !n.is_empty()).map_or_else(|| format!("Layer {}", self.nodes), str::to_string); + layer.visible = node.visible; + layer.opacity = (node.opacity / 255.0).clamp(0.0, 1.0) as f32; + if node.locked { layer.locks.all = true; } - let op = attr(node, "compositeop").unwrap_or("normal"); + let op = node.composite_op.as_deref().unwrap_or("normal"); layer.blend = match krita_blend(op) { Some((mode, approx)) => { if approx { @@ -143,24 +96,22 @@ impl Reader<'_, '_> { BlendMode::Normal } }; - if attr(node, "channelflags").is_some_and(|f| f.contains('0')) { + if node.channel_flags.as_deref().is_some_and(|f| f.contains('0')) { self.warnings.layer(&layer.name, "channel locks (Krita's per-channel blending) are ignored"); } - if truthy(node, "inheritalpha") { + if node.inherit_alpha { self.warnings.layer(&layer.name, "Inherit Alpha is not supported; these layers blend normally"); } - if attr(node, "keyframes").is_some_and(|k| !k.is_empty()) { + if node.keyframes.as_deref().is_some_and(|k| !k.is_empty()) { self.warnings.layer(&layer.name, "animated layers open with the frame Krita saved in the layer"); } - Ok(()) } /// The node's transparency masks, combined into one layer mask. - fn masks(&mut self, node: roxmltree::Node<'_, '_>, layer: &mut Layer, dx: i32, dy: i32) -> Result<()> { - for mask in children(node, "masks", "mask") { + fn masks(&mut self, node: &Node, layer: &mut Layer, dx: i32, dy: i32) -> Result<()> { + for mask in &node.masks { self.ctl.check().map_err(|_| IoError::Cancelled)?; - let kind = attr(mask, "nodetype").unwrap_or(""); - match kind { + match mask.node_type.as_str() { "transparencymask" => {} // A layer's local selection: not part of its look. "selectionmask" => continue, @@ -179,11 +130,11 @@ impl Reader<'_, '_> { self.warnings.layer(&layer.name, "only the first transparency mask of a layer is kept"); continue; } - let Some(file) = attr(mask, "filename") else { continue }; - let (mx, my) = (dx.saturating_add(offset(mask, "x")?), dy.saturating_add(offset(mask, "y")?)); + let Some(file) = mask.filename.as_deref() else { continue }; + let (mx, my) = (dx.saturating_add(mask.x), dy.saturating_add(mask.y)); match self.surface(&format!("{file}.pixelselection"), Space::Alpha8, PixelFormat::GRAY8, mx, my)? { Some(surface) => { - layer.mask = Some(LayerMask { surface, enabled: attr(mask, "visible") != Some("0"), ..LayerMask::reveal_all() }); + layer.mask = Some(LayerMask { surface, enabled: mask.visible, ..LayerMask::reveal_all() }); } None => self.warnings.layer(&layer.name, "a transparency mask's pixels are missing from the file"), } @@ -191,32 +142,28 @@ impl Reader<'_, '_> { Ok(()) } - /// The `` of `node`, bottom-to-top (maindoc.xml lists the topmost first). - fn layers(&mut self, node: roxmltree::Node<'_, '_>, depth: usize, dx: i32, dy: i32) -> Result> { + /// `nodes` (topmost first, as maindoc.xml lists them) as layers, bottom-to-top. + fn layers(&mut self, nodes: &[Node], depth: usize, dx: i32, dy: i32) -> Result> { if depth > photocraft_doc::MAX_GROUP_DEPTH { return Err(IoError::Unsupported(format!("layer groups nested deeper than {}", photocraft_doc::MAX_GROUP_DEPTH))); } let mut out = Vec::new(); - for child in children(node, "layers", "layer") { + for child in nodes { self.ctl.check().map_err(|_| IoError::Cancelled)?; self.nodes += 1; - if self.nodes > MAX_NODES { - return Err(invalid(format!("more than {MAX_NODES} layers"))); - } - let (x, y) = (dx.saturating_add(offset(child, "x")?), dy.saturating_add(offset(child, "y")?)); - let kind = attr(child, "nodetype").unwrap_or(""); - let mut layer = match kind { + let (x, y) = (dx.saturating_add(child.x), dy.saturating_add(child.y)); + let mut layer = match child.node_type.as_str() { "paintlayer" => { let mut layer = Layer::raster("", self.fmt); - self.props(child, &mut layer)?; - let space = attr(child, "colorspacename").and_then(Space::from_name); - match (space, attr(child, "filename")) { + self.props(child, &mut layer); + let space = child.colorspace_name.as_deref().and_then(Space::from_name); + match (space, child.filename.as_deref()) { (Some(space), Some(file)) => match self.surface(file, space, self.fmt, x, y)? { Some(s) => layer.content = LayerContent::Raster(s), None => self.warnings.layer(&layer.name, "the layer's pixels are missing from the file; it opens empty"), }, (None, _) => { - let cs = attr(child, "colorspacename").unwrap_or("?"); + let cs = child.colorspace_name.as_deref().unwrap_or("?"); self.warnings.layer(&layer.name, &format!("layers in Krita's {cs} colour space are not supported and were left out")); continue; } @@ -226,8 +173,8 @@ impl Reader<'_, '_> { } "grouplayer" => { let mut layer = Layer::group("", Vec::new()); - self.props(child, &mut layer)?; - if truthy(child, "passthrough") { + self.props(child, &mut layer); + if child.passthrough { if layer.blend != BlendMode::Normal { self.warnings.layer(&layer.name, "a pass-through group's blend mode is ignored, as in Krita"); } @@ -235,15 +182,15 @@ impl Reader<'_, '_> { } // A group's own x/y is not applied to its children: Krita moves a group by // moving their pixels, and its merged image ignores the group offset. - let kids = self.layers(child, depth + 1, dx, dy)?; + let kids = self.layers(&child.layers, depth + 1, dx, dy)?; if let LayerContent::Group(g) = &mut layer.content { g.children = kids; - g.expanded = !truthy(child, "collapsed"); + g.expanded = !child.collapsed; } layer } other => { - let name = attr(child, "name").unwrap_or(other).to_string(); + let name = child.name.as_deref().unwrap_or(other).to_string(); let what = match other { "shapelayer" => "vector layers", "adjustmentlayer" => "filter layers", @@ -265,8 +212,12 @@ impl Reader<'_, '_> { } /// Krita's merged image as a one-layer stand-in, for documents we can't read layer by layer. -fn preview(name: &str, zip: &ZipReader<'_>, why: String) -> Result { - let png = zip.read_by_name("mergedimage.png", MAX_LAYER_FILE).map_err(|e| invalid(format!("{why}, and the merged image can't be read: {e}")))?; +fn preview(name: &str, archive: &mut Archive<'_>, why: String) -> Result { + let png = match archive.merged_image() { + Ok(Some(png)) => png, + Ok(None) => return Err(invalid(format!("{why}, and the file has no merged image"))), + Err(e) => return Err(invalid(format!("{why}, and the merged image can't be read: {e}"))), + }; let mut r = crate::flat::import_flat(name, &png)?; r.document.name = name.to_string(); r.warnings.insert(0, format!("{why}; the file opens as Krita's merged image, without its layers")); @@ -276,56 +227,21 @@ fn preview(name: &str, zip: &ZipReader<'_>, why: String) -> Result } pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result { - let zip = ZipReader::new(bytes).map_err(|e| invalid(e.to_string()))?; - let mime = zip.read_by_name("mimetype", 256).map_err(|e| invalid(e.to_string()))?; - if mime.trim_ascii() != MIMETYPE { - return Err(invalid("the archive's mimetype is not application/x-krita")); - } - let xml = zip.read_by_name("maindoc.xml", MAX_MAINDOC).map_err(|e| invalid(e.to_string()))?; - let xml = std::str::from_utf8(&xml).map_err(|_| invalid("maindoc.xml is not UTF-8"))?; - // maindoc.xml declares Krita's DTD by public id; Krita writes no internal subset, which - // `xml::parse` refuses (its entities could hide nesting from the depth check). - let opts = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }; - let tree = crate::xml::parse(xml, opts).map_err(|e| invalid(format!("maindoc.xml: {e}")))?; - let image = tree.root_element().children().find(|n| n.has_tag_name("IMAGE")).ok_or_else(|| invalid("maindoc.xml has no IMAGE"))?; - let side = |a: &str| -> Result { - let v = number(image, a, 0.0)?; - if !(1.0..=f64::from(MAX_SIDE)).contains(&v) || v.fract() != 0.0 { - return Err(invalid(format!("image {a} {v} must be a whole number of pixels from 1 to {MAX_SIDE}"))); - } - Ok(v as u32) - }; - let (w, h) = (side("width")?, side("height")?); - if (w as usize).saturating_mul(h as usize).saturating_mul(8) > MAX_PIXEL_BYTES { - return Err(invalid("the canvas exceeds the 1 GiB pixel limit")); - } - let cs = attr(image, "colorspacename").unwrap_or(""); - let Some(space) = Space::from_name(cs) else { - return preview(name, &zip, format!("Krita's {cs} colour space is not supported yet")); + let mut archive = Archive::open(bytes).map_err(kra_err)?; + let image = archive.image().clone(); + let Some(space) = Space::from_name(&image.colorspace_name) else { + return preview(name, &mut archive, format!("Krita's {} colour space is not supported yet", image.colorspace_name)); }; let (mode, depth) = space.model(); - let image_name = attr(image, "name").unwrap_or(""); - let mut reader = Reader { - zip, - ctl, - dir: format!("{image_name}/layers/"), - fmt: PixelFormat::new(mode, depth, true), - nodes: 0, - budget: MAX_PIXEL_BYTES, - warnings: Warnings::default(), - }; - let layers = reader.layers(image, 1, 0, 0)?; + let mut reader = Reader { archive, ctl, fmt: PixelFormat::new(mode, depth, true), nodes: 0, budget: MAX_PIXEL_BYTES, warnings: Warnings::default() }; + let layers = reader.layers(&image.layers, 1, 0, 0)?; ctl.progress(0.9); - let mut document = Document::new(name, Size::new(w, h), mode, depth); + let mut document = Document::new(name, Size::new(image.width, image.height), mode, depth); document.layers = layers; - let icc = format!("{image_name}/annotations/icc"); - if let Some(e) = reader.zip.find(&icc) { - let profile = reader.zip.read(e, 16 << 20).map_err(|err| invalid(format!("{icc}: {err}")))?; - if !profile.is_empty() { - document.icc_profile = Some(std::sync::Arc::new(profile)); - } + if let Some(profile) = reader.archive.icc_profile().map_err(kra_err)? { + document.icc_profile = Some(std::sync::Arc::new(profile)); } - let (xres, yres) = (number(image, "x-res", 72.0)?, number(image, "y-res", 72.0)?); + let (xres, yres) = (image.x_res, image.y_res); if xres > 0.0 && xres < 1.0e6 { document.resolution_dpi = xres as f32; if let Some(w) = crate::unequal_resolution_warning(xres, yres) { @@ -335,7 +251,7 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result]>&e;"); // A quoted `?>` in the XML declaration must not hide the DOCTYPE behind it. let declared = format!("\"?>{entity}"); - for (xml, why) in [(direct, "nested"), (entity, "internal DTD"), (declared, "internal DTD")] { + // The nesting is refused by its depth; an internal subset is refused outright (craft-kra). + for (xml, why) in [(direct, Some("nest")), (entity, None), (declared, None)] { let bytes = archive(&xml, &[]); let e = std::thread::Builder::new().stack_size(512 * 1024).spawn(move || crate::import("deep.kra", &bytes).err()).unwrap().join().unwrap(); - assert!(matches!(&e, Some(IoError::Kra(m)) if m.contains(why)), "{why}: {e:?}"); + assert!(matches!(&e, Some(IoError::Kra(m)) if why.is_none_or(|w| m.contains(w))), "{why:?}: {e:?}"); } } -#[test] -fn lzf_decodes_literals_and_overlapping_references() { - // "abc" then a 6-byte back-reference 3 back: abcabcabc. - assert_eq!(lzf_decompress(&[2, b'a', b'b', b'c', 0x80, 2], 9).unwrap(), b"abcabcabc"); - // A long back-reference (len 7 + extra) over a single byte: run-length. - assert_eq!(lzf_decompress(&[0, b'x', 0xe0, 3, 0], 13).unwrap(), vec![b'x'; 13]); - for bad in [&[0x20, 5][..], &[5, 1, 2], &[0xe0], &[2, 1, 2, 3, 0x20]] { - assert!(lzf_decompress(bad, 64).is_err(), "{bad:?}"); - } - assert!(lzf_decompress(&[2, 1, 2, 3], 2).is_err(), "overrun"); - assert!(lzf_decompress(&[2, 1, 2, 3], 4).is_err(), "short"); -} - #[test] fn malformed_files_fail_cleanly() { let one = |cs: &str, data: Vec| { diff --git a/crates/io/src/kra/tiles.rs b/crates/io/src/kra/tiles.rs index d7330868b7..40f1292c89 100644 --- a/crates/io/src/kra/tiles.rs +++ b/crates/io/src/kra/tiles.rs @@ -1,48 +1,28 @@ -//! Krita's tiled pixel files and the LZF compression inside them. +//! Krita tile files (parsed by craft-kra) onto surfaces: pixel layouts to surface formats, the +//! memory a file's tiles take once placed, and the tiles written into a surface. +use craft_kra::tiles::{Space, TileFile}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_geom::Rect; use photocraft_raster::{Interrupt, Surface}; -use super::{Result, invalid}; +use super::{Result, invalid, kra_err}; use crate::IoError; -/// The pixel layouts we read, by Krita colour-space id. Samples are straight (unpremultiplied). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Space { - /// `RGBA`: B, G, R, A bytes. - Rgba8, - /// `RGBA16`: B, G, R, A as little-endian u16. - Rgba16, - /// `GRAYA`: gray, alpha bytes. - Gray8, - /// `GRAYAU16`: gray, alpha as little-endian u16. - Gray16, - /// Masks and selections: one byte. - Alpha8, +/// What a Krita pixel layout is in this app's terms. +pub(crate) trait SpaceExt { + /// The document colour mode and depth for an image in this space. + fn model(self) -> (ColorMode, SampleType); + /// The surface format whose bytes [`Space::samples`] writes directly. + fn native(self) -> PixelFormat; + /// Straight RGBA samples as `fmt`'s channels. + fn to_format(self, rgba: &[f32; 4], fmt: PixelFormat) -> Vec; + /// Interleaved Krita pixels as encoded `fmt` bytes. + fn convert(self, src: &[u8], fmt: PixelFormat, out: &mut Vec); } -impl Space { - pub(crate) fn from_name(name: &str) -> Option { - Some(match name { - "RGBA" => Space::Rgba8, - "RGBA16" => Space::Rgba16, - "GRAYA" => Space::Gray8, - "GRAYAU16" => Space::Gray16, - _ => return None, - }) - } - pub(crate) fn pixel_size(self) -> usize { - match self { - Space::Rgba8 => 4, - Space::Rgba16 => 8, - Space::Gray8 => 2, - Space::Gray16 => 4, - Space::Alpha8 => 1, - } - } - /// The document colour mode and depth for an image in this space. - pub(crate) fn model(self) -> (ColorMode, SampleType) { +impl SpaceExt for Space { + fn model(self) -> (ColorMode, SampleType) { match self { Space::Rgba8 => (ColorMode::Rgb, SampleType::U8), Space::Rgba16 => (ColorMode::Rgb, SampleType::U16), @@ -50,7 +30,6 @@ impl Space { Space::Gray16 => (ColorMode::Grayscale, SampleType::U16), } } - /// The surface format whose bytes [`Self::convert`] writes directly. fn native(self) -> PixelFormat { match self { Space::Alpha8 => PixelFormat::GRAY8, @@ -60,54 +39,17 @@ impl Space { } } } - /// One interleaved Krita pixel as straight RGBA (0..1). - fn rgba(self, px: &[u8]) -> [f32; 4] { - let b = |i: usize| f32::from(px.get(i).copied().unwrap_or(0)) / 255.0; - let w = |i: usize| f32::from(u16::from_le_bytes([px.get(i).copied().unwrap_or(0), px.get(i + 1).copied().unwrap_or(0)])) / 65535.0; - match self { - Space::Rgba8 => [b(2), b(1), b(0), b(3)], - Space::Rgba16 => [w(4), w(2), w(0), w(6)], - Space::Gray8 => [b(0), b(0), b(0), b(1)], - Space::Gray16 => [w(0), w(0), w(0), w(2)], - Space::Alpha8 => [b(0), b(0), b(0), 1.0], - } + fn to_format(self, rgba: &[f32; 4], fmt: PixelFormat) -> Vec { + photocraft_raster::from_rgba(&fmt, *rgba) } - /// A default pixel's samples (Krita order, 0..1), for [`Self::to_format`]. - pub(crate) fn normalised(self, px: &[u8]) -> Vec { - self.rgba(px).to_vec() - } - /// RGBA samples from [`Self::normalised`] as `fmt`'s channels. - pub(crate) fn to_format(self, rgba: &[f32], fmt: PixelFormat) -> Vec { - let p = [0, 1, 2, 3].map(|i| rgba.get(i).copied().unwrap_or(0.0)); - photocraft_raster::from_rgba(&fmt, p) - } - /// Interleaved Krita pixels as encoded `fmt` bytes. fn convert(self, src: &[u8], fmt: PixelFormat, out: &mut Vec) { - out.clear(); - let ps = self.pixel_size(); if fmt == self.native() { - for px in src.chunks_exact(ps) { - match self { - Space::Rgba8 => out.extend([2, 1, 0, 3].map(|i| px.get(i).copied().unwrap_or(0))), - Space::Rgba16 => { - for i in [4, 2, 0, 6] { - let v = u16::from_le_bytes([px.get(i).copied().unwrap_or(0), px.get(i + 1).copied().unwrap_or(0)]); - out.extend(v.to_ne_bytes()); - } - } - Space::Gray16 => { - for i in [0, 2] { - let v = u16::from_le_bytes([px.get(i).copied().unwrap_or(0), px.get(i + 1).copied().unwrap_or(0)]); - out.extend(v.to_ne_bytes()); - } - } - Space::Gray8 | Space::Alpha8 => out.extend_from_slice(px), - } - } + self.samples(src, out); return; } + out.clear(); let mut enc = vec![0; fmt.bytes_per_pixel()]; - for px in src.chunks_exact(ps) { + for px in src.chunks_exact(self.pixel_size()) { let v = photocraft_raster::from_rgba(&fmt, self.rgba(px)); photocraft_raster::encode_pixel(&fmt, &v, &mut enc); out.extend_from_slice(&enc); @@ -115,194 +57,77 @@ impl Space { } } -/// LZF decompression (the liblzf format) into exactly `expected` bytes. -pub(crate) fn lzf_decompress(src: &[u8], expected: usize) -> Result> { - let bad = || invalid("corrupt LZF tile data"); - let mut out = Vec::with_capacity(expected); - let mut ip = 0; - while ip < src.len() { - let ctrl = usize::from(*src.get(ip).ok_or_else(bad)?); - ip += 1; - if ctrl < 32 { - let len = ctrl + 1; - let lit = src.get(ip..ip + len).ok_or_else(bad)?; - if out.len() + len > expected { - return Err(bad()); - } - out.extend_from_slice(lit); - ip += len; - } else { - let mut len = ctrl >> 5; - if len == 7 { - len += usize::from(*src.get(ip).ok_or_else(bad)?); - ip += 1; - } - len += 2; - let back = ((ctrl & 0x1f) << 8) + usize::from(*src.get(ip).ok_or_else(bad)?) + 1; - ip += 1; - let start = out.len().checked_sub(back).ok_or_else(bad)?; - if out.len() + len > expected { - return Err(bad()); - } - // Back-references may overlap the bytes they produce, so copy one at a time. - for i in start..start + len { - let b = *out.get(i).ok_or_else(bad)?; - out.push(b); - } - } - } - if out.len() != expected { - return Err(invalid(format!("LZF tile data decodes to {} bytes, expected {expected}", out.len()))); - } - Ok(out) +/// Bytes the decoded tiles take at `bpp` bytes per pixel: the larger of their own pixels and +/// the whole 256×256 backing tiles they land in (a surface stores no less than a tile, so +/// sparse tiles at distinct positions retain far more than they hold). +pub(crate) fn decoded_bytes(file: &TileFile<'_>, bpp: usize, dx: i32, dy: i32) -> Result { + tile_cost(file.tiles().iter().map(|t| (t.x, t.y)), file.width, file.height, bpp, dx, dy) } -/// A parsed tiled pixel file (`VERSION 2`), borrowing the tile payloads. -pub(crate) struct TileFile<'a> { - pub(crate) width: usize, - pub(crate) height: usize, - pub(crate) pixel_size: usize, - tiles: Vec<(i32, i32, &'a [u8])>, -} - -fn line<'a>(bytes: &'a [u8], pos: &mut usize) -> Result<&'a str> { - let rest = bytes.get(*pos..).ok_or_else(|| invalid("truncated tile file"))?; - let end = rest.iter().take(256).position(|b| *b == b'\n').ok_or_else(|| invalid("truncated or malformed tile file header"))?; - *pos += end + 1; - std::str::from_utf8(rest.get(..end).unwrap_or_default()).map_err(|_| invalid("tile file header is not text")) -} - -fn header_value(bytes: &[u8], pos: &mut usize, key: &str, max: usize) -> Result { - let l = line(bytes, pos)?; - let v = l.strip_prefix(key).map(str::trim).ok_or_else(|| invalid(format!("tile file: expected {key}, found `{l}`")))?; - v.parse::().ok().filter(|v| (1..=max).contains(v)).ok_or_else(|| invalid(format!("tile file: invalid {key} `{v}`"))) -} - -impl<'a> TileFile<'a> { - pub(crate) fn parse(bytes: &'a [u8]) -> Result> { - let mut pos = 0; - let version = line(bytes, &mut pos)?; - if version.trim() != "VERSION 2" { - return Err(IoError::Unsupported(format!("Krita tile file `{}` (only VERSION 2, Krita 2.0 and later)", version.trim()))); - } - let width = header_value(bytes, &mut pos, "TILEWIDTH", 1024)?; - let height = header_value(bytes, &mut pos, "TILEHEIGHT", 1024)?; - let pixel_size = header_value(bytes, &mut pos, "PIXELSIZE", 64)?; - let l = line(bytes, &mut pos)?; - let count = l - .strip_prefix("DATA") - .map(str::trim) - .and_then(|v| v.parse::().ok()) - .ok_or_else(|| invalid(format!("tile file: invalid DATA line `{l}`")))?; - // Every tile needs at least a header line and a flag byte. - if count > bytes.len() / 8 + 1 { - return Err(invalid("tile count exceeds the file size")); - } - let mut tiles = Vec::with_capacity(count); - for _ in 0..count { - let l = line(bytes, &mut pos)?; - let mut f = l.split(','); - let (x, y, method, len) = (f.next(), f.next(), f.next(), f.next()); - let coord = |v: Option<&str>| v.and_then(|v| v.trim().parse::().ok()).filter(|v| v.unsigned_abs() <= super::MAX_SIDE * 4); - let (Some(x), Some(y), Some("LZF"), Some(len), None) = - (coord(x), coord(y), method.map(str::trim), len.and_then(|v| v.trim().parse::().ok()), f.next()) - else { - return Err(invalid(format!("tile file: malformed tile header `{l}`"))); - }; - let data = bytes.get(pos..pos.checked_add(len).ok_or_else(|| invalid("tile size overflow"))?).ok_or_else(|| invalid("truncated tile data"))?; - pos += len; - tiles.push((x, y, data)); - } - Ok(TileFile { width, height, pixel_size, tiles }) - } - - /// Bytes the decoded tiles take at `bpp` bytes per pixel: the larger of their own pixels and - /// the whole 256×256 backing tiles they land in (a surface stores no less than a tile, so - /// sparse tiles at distinct positions retain far more than they hold). - pub(crate) fn decoded_bytes(&self, bpp: usize, dx: i32, dy: i32) -> Result { - let overflow = || invalid("tile size overflow"); - let logical = self.tiles.len().checked_mul(self.width * self.height).and_then(|n| n.checked_mul(bpp)).ok_or_else(overflow)?; - let side = photocraft_geom::TILE_SIZE; - let (w, h) = (i32::try_from(self.width.max(1)).map_err(|_| overflow())?, i32::try_from(self.height.max(1)).map_err(|_| overflow())?); - let mut backing = std::collections::HashSet::new(); - for &(x, y, _) in &self.tiles { - // The tile lands at its offset position and covers every backing tile its box overlaps. - let (x, y) = (x.checked_add(dx).ok_or_else(overflow)?, y.checked_add(dy).ok_or_else(overflow)?); - let (x1, y1) = (x.checked_add(w - 1).ok_or_else(overflow)?, y.checked_add(h - 1).ok_or_else(overflow)?); - for c in x.div_euclid(side)..=x1.div_euclid(side) { - for r in y.div_euclid(side)..=y1.div_euclid(side) { - backing.insert((c, r)); - } +fn tile_cost(positions: impl ExactSizeIterator, width: usize, height: usize, bpp: usize, dx: i32, dy: i32) -> Result { + let overflow = || invalid("tile size overflow"); + let logical = positions.len().checked_mul(width * height).and_then(|n| n.checked_mul(bpp)).ok_or_else(overflow)?; + let side = photocraft_geom::TILE_SIZE; + let (w, h) = (i32::try_from(width.max(1)).map_err(|_| overflow())?, i32::try_from(height.max(1)).map_err(|_| overflow())?); + let mut backing = std::collections::HashSet::new(); + for (x, y) in positions { + // The tile lands at its offset position and covers every backing tile its box overlaps. + let (x, y) = (x.checked_add(dx).ok_or_else(overflow)?, y.checked_add(dy).ok_or_else(overflow)?); + let (x1, y1) = (x.checked_add(w - 1).ok_or_else(overflow)?, y.checked_add(h - 1).ok_or_else(overflow)?); + for c in x.div_euclid(side)..=x1.div_euclid(side) { + for r in y.div_euclid(side)..=y1.div_euclid(side) { + backing.insert((c, r)); } } - let tile_bytes = (side as usize).checked_mul(side as usize).and_then(|n| n.checked_mul(bpp)).ok_or_else(overflow)?; - Ok(logical.max(backing.len().checked_mul(tile_bytes).ok_or_else(overflow)?)) } + let tile_bytes = (side as usize).checked_mul(side as usize).and_then(|n| n.checked_mul(bpp)).ok_or_else(overflow)?; + Ok(logical.max(backing.len().checked_mul(tile_bytes).ok_or_else(overflow)?)) +} - /// Writes every tile into `surface` (format `surface.format()`), offset by (`dx`, `dy`). - pub(crate) fn decode_into(&self, surface: &mut Surface, space: Space, dx: i32, dy: i32, ctl: &Interrupt<'_>) -> Result<()> { - let fmt = surface.format(); - let n = self.width * self.height; - let expected = n * self.pixel_size; - let mut interleaved = vec![0u8; expected]; - let mut out = Vec::new(); - for &(x, y, data) in &self.tiles { - ctl.check().map_err(|_| IoError::Cancelled)?; - let (flag, payload) = data.split_first().ok_or_else(|| invalid("empty tile"))?; - match flag { - 1 => { - // LZF tiles hold byte planes: byte k of pixel i is at k * n + i. - let planar = lzf_decompress(payload, expected)?; - for (k, plane) in planar.chunks_exact(n).enumerate() { - for (i, b) in plane.iter().enumerate() { - if let Some(slot) = interleaved.get_mut(i * self.pixel_size + k) { - *slot = *b; - } - } - } - } - // Raw tiles (written when LZF doesn't shrink them) are already interleaved. - 0 if payload.len() == expected => interleaved.copy_from_slice(payload), - 0 => return Err(invalid("raw tile has the wrong size")), - f => return Err(invalid(format!("unknown tile compression flag {f}"))), - } - space.convert(&interleaved, fmt, &mut out); - let (x0, y0) = - (x.checked_add(dx).ok_or_else(|| invalid("tile offset overflow"))?, y.checked_add(dy).ok_or_else(|| invalid("tile offset overflow"))?); - let rect = Rect::from_xywh(x0, y0, self.width as u32, self.height as u32); - if rect.width() as usize != self.width || rect.height() as usize != self.height || out.len() != n * fmt.bytes_per_pixel() { - return Err(invalid("tile does not fit its position")); - } - surface.write_interleaved(rect, &out); +/// Writes every tile into `surface` (format `surface.format()`), offset by (`dx`, `dy`). +pub(crate) fn decode_into(file: &TileFile<'_>, surface: &mut Surface, space: Space, dx: i32, dy: i32, ctl: &Interrupt<'_>) -> Result<()> { + let fmt = surface.format(); + let n = file.width * file.height; + let mut interleaved = Vec::new(); + let mut out = Vec::new(); + for tile in file.tiles() { + ctl.check().map_err(|_| IoError::Cancelled)?; + file.decode(tile, &mut interleaved).map_err(kra_err)?; + space.convert(&interleaved, fmt, &mut out); + let (x0, y0) = + (tile.x.checked_add(dx).ok_or_else(|| invalid("tile offset overflow"))?, tile.y.checked_add(dy).ok_or_else(|| invalid("tile offset overflow"))?); + let rect = Rect::from_xywh(x0, y0, file.width as u32, file.height as u32); + if rect.width() as usize != file.width || rect.height() as usize != file.height || out.len() != n * fmt.bytes_per_pixel() { + return Err(invalid("tile does not fit its position")); } - Ok(()) + surface.write_interleaved(rect, &out); } + Ok(()) } #[cfg(test)] mod tests { use super::*; - fn file(positions: &[(i32, i32)]) -> TileFile<'static> { - TileFile { width: 64, height: 64, pixel_size: 4, tiles: positions.iter().map(|&(x, y)| (x, y, &[][..])).collect() } + fn cost(positions: &[(i32, i32)], width: usize, dx: i32, dy: i32) -> usize { + tile_cost(positions.iter().copied(), width, if width == 64 { 64 } else { 1 }, 4, dx, dy).unwrap() } #[test] fn sparse_tiles_are_charged_for_the_backing_tiles_they_land_in() { // Sixteen 64×64 tiles that fill one 256×256 backing tile cost what they hold. let dense: Vec<_> = (0..4).flat_map(|y| (0..4).map(move |x| (x * 64, y * 64))).collect(); - assert_eq!(file(&dense).decoded_bytes(4, 0, 0).unwrap(), 16 * 64 * 64 * 4); + assert_eq!(cost(&dense, 64, 0, 0), 16 * 64 * 64 * 4); // The same number far apart each take a whole backing tile: 16 × 256 × 256 × 4. let sparse: Vec<_> = (0..16).map(|i| (i * 10_240, 0)).collect(); - assert_eq!(file(&sparse).decoded_bytes(4, 0, 0).unwrap(), 16 * 256 * 256 * 4); + assert_eq!(cost(&sparse, 64, 0, 0), 16 * 256 * 256 * 4); } #[test] fn the_placement_offset_and_tile_extent_decide_the_backing_tiles() { // One 64×64 tile straddling a backing-tile corner once offset touches four. - assert_eq!(file(&[(0, 0)]).decoded_bytes(4, 224, 224).unwrap(), 4 * 256 * 256 * 4); + assert_eq!(cost(&[(0, 0)], 64, 224, 224), 4 * 256 * 256 * 4); // A tile wider than a backing tile reaches the ones between its corners. - let wide = TileFile { width: 1024, height: 1, pixel_size: 4, tiles: vec![(0, 0, &[][..])] }; - assert_eq!(wide.decoded_bytes(4, 0, 0).unwrap(), 4 * 256 * 256 * 4); + assert_eq!(cost(&[(0, 0)], 1024, 0, 0), 4 * 256 * 256 * 4); } } diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index 48ea0550f6..c45e4df3b7 100644 --- a/crates/io/src/ora.rs +++ b/crates/io/src/ora.rs @@ -12,54 +12,32 @@ #[cfg(test)] mod tests; +use craft_ora::{Archive, Props}; use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType as CSample}; use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Document, Layer, LayerContent}; -use photocraft_format::zip::{ZipReader, ZipWriter}; use photocraft_geom::{Rect, Size}; use photocraft_raster::{Interrupt, Surface}; use crate::{ExportResult, ImportResult, IoError}; +use craft_ora::{MAX_ENTRY, MAX_SIDE}; +pub(crate) use craft_ora::{MAX_PIXEL_BYTES, is_ora}; + type Result = std::result::Result; -/// The `mimetype` entry of an OpenRaster archive. -pub(crate) const MIMETYPE: &[u8] = b"image/openraster"; -/// Decoded pixels across every layer (and the stack.xml) are capped, as for PDN. -pub(crate) const MAX_PIXEL_BYTES: usize = 1 << 30; -/// Canvas side limit (Photoshop's PSB limit). -pub(crate) const MAX_SIDE: u32 = 300_000; -/// Layers and groups in one document. -pub(crate) const MAX_NODES: usize = 8192; -const MAX_STACK_XML: usize = 16 << 20; -const MAX_ENTRY: usize = 512 << 20; const THUMBNAIL_SIDE: u32 = 256; fn invalid(message: impl Into) -> IoError { IoError::Ora(message.into()) } -/// The payload of a ZIP's first entry when it is a stored file named `mimetype`, which is how -/// OpenRaster and Krita mark their archives (so the type is readable without unzipping). -pub(crate) fn zip_mimetype(bytes: &[u8]) -> Option<&[u8]> { - let u16_at = |o: usize| bytes.get(o..o + 2).and_then(|s| <[u8; 2]>::try_from(s).ok()).map(u16::from_le_bytes); - let u32_at = |o: usize| bytes.get(o..o + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_le_bytes); - if u32_at(0)? != 0x0403_4b50 || u16_at(8)? != 0 { - return None; +/// The format crate's error as this crate's. +fn ora_err(e: craft_ora::Error) -> IoError { + match e { + craft_ora::Error::Invalid(m) => invalid(m), + craft_ora::Error::Write(m) => IoError::Ora(format!("the archive could not be written: {m}")), } - let size = usize::try_from(u32_at(18)?).ok()?; - let name_len = usize::from(u16_at(26)?); - let extra_len = usize::from(u16_at(28)?); - if bytes.get(30..30 + name_len)? != b"mimetype" || size > 256 { - return None; - } - let start = 30 + name_len + extra_len; - bytes.get(start..start.checked_add(size)?) -} - -/// `true` for an OpenRaster archive (by its `mimetype` entry). -pub(crate) fn is_ora(bytes: &[u8]) -> bool { - zip_mimetype(bytes) == Some(MIMETYPE) } /// Blend modes by Krita composite-op id: Krita's `.kra` `compositeop` attribute and the @@ -220,56 +198,22 @@ impl Warnings { } } -/// A number attribute; a missing one is `default`, an unparsable one an error. -fn num(node: roxmltree::Node<'_, '_>, name: &str, default: f64) -> Result { - match node.attribute(name) { - None => Ok(default), - Some(v) => v.trim().parse::().ok().filter(|v| v.is_finite()).ok_or_else(|| invalid(format!("invalid {name} attribute `{v}`"))), - } -} - -fn int(node: roxmltree::Node<'_, '_>, name: &str) -> Result { - let v = num(node, name, 0.0)?.round(); - if v.abs() > f64::from(MAX_SIDE) * 4.0 { - return Err(invalid(format!("{name} offset {v} is out of range"))); - } - Ok(v as i32) -} - -fn flag(node: roxmltree::Node<'_, '_>, name: &str) -> bool { - node.attribute(name).is_some_and(|v| matches!(v.trim(), "true" | "1")) -} - /// Shared node properties: name, visibility, opacity and composite operation. -fn props(node: roxmltree::Node<'_, '_>, layer: &mut Layer, index: usize, warnings: &mut Warnings) -> Result<()> { - layer.name = node.attribute("name").filter(|name| !name.trim().is_empty()).map_or_else(|| format!("Layer {index}"), str::to_string); - layer.visible = node.attribute("visibility").is_none_or(|v| v.trim() != "hidden"); - layer.opacity = num(node, "opacity", 1.0)?.clamp(0.0, 1.0) as f32; - layer.blend = composite_op(node.attribute("composite-op").map_or("svg:src-over", str::trim), &layer.name, warnings); - if flag(node, "edit-locked") { +fn props(p: &Props, layer: &mut Layer, index: usize, warnings: &mut Warnings) { + layer.name = p.name.as_deref().filter(|name| !name.trim().is_empty()).map_or_else(|| format!("Layer {index}"), str::to_string); + layer.visible = p.visible; + layer.opacity = p.opacity.clamp(0.0, 1.0); + layer.blend = composite_op(p.composite_op.as_deref().unwrap_or("svg:src-over"), &layer.name, warnings); + if p.edit_locked { layer.locks.all = true; } - if flag(node, "alpha-preserve") { + if p.alpha_preserve { layer.locks.transparency = true; } - Ok(()) -} - -/// OpenRaster 0.0.6 defaults to isolated groups and makes `auto` explicitly pass-through. -/// Older files used inference from the group's blend mode; keep that behavior when the -/// version is absent or unrecognized, too. Compare the numeric core, not version strings. -fn uses_explicit_group_isolation(version: Option<&str>) -> bool { - let Some(core) = version.and_then(|v| v.trim().split(['-', '+']).next()) else { return false }; - let mut parts = core.split('.'); - let number = |part: Option<&str>| part.and_then(|s| s.parse::().ok()); - match (number(parts.next()), number(parts.next()), number(parts.next()), parts.next()) { - (Some(major), Some(minor), Some(patch), None) => [major, minor, patch] >= [0, 0, 6], - _ => false, - } } struct Reader<'a, 'c> { - zip: ZipReader<'a>, + archive: Archive<'a>, ctl: &'c Interrupt<'c>, explicit_group_isolation: bool, nodes: usize, @@ -287,11 +231,10 @@ enum Node { impl Reader<'_, '_> { fn png(&mut self, src: &str, layer: &str) -> Result> { - let Some(entry) = self.zip.find(src).cloned() else { + let Some(data) = self.archive.entry(src, MAX_ENTRY).map_err(ora_err)? else { self.warnings.layer(layer, "the layer's image is missing from the archive; the layer opens empty"); return Ok(None); }; - let data = self.zip.read(&entry, MAX_ENTRY).map_err(|e| invalid(format!("{src}: {e}")))?; let mut opts = codecs::DecodeOptions::default(); opts.limits.max_width = MAX_SIDE; opts.limits.max_height = MAX_SIDE; @@ -307,36 +250,32 @@ impl Reader<'_, '_> { Ok(Some(self.images.len() - 1)) } - fn stack(&mut self, stack: roxmltree::Node<'_, '_>, depth: usize) -> Result> { + fn stack(&mut self, stack: &[craft_ora::Node], depth: usize) -> Result> { if depth > photocraft_doc::MAX_GROUP_DEPTH { return Err(IoError::Unsupported(format!("layer groups nested deeper than {}", photocraft_doc::MAX_GROUP_DEPTH))); } let mut out = Vec::new(); - for child in stack.children().filter(roxmltree::Node::is_element) { + for child in stack { self.ctl.check().map_err(|_| IoError::Cancelled)?; self.nodes += 1; - if self.nodes > MAX_NODES { - return Err(invalid(format!("more than {MAX_NODES} layers"))); - } let index = self.nodes; - match child.tag_name().name() { - "layer" => { + match child { + craft_ora::Node::Layer(l) => { let mut layer = Layer::raster("", PixelFormat::RGBA8); - props(child, &mut layer, index, &mut self.warnings)?; - let (x, y) = (int(child, "x")?, int(child, "y")?); - let image = match child.attribute("src") { - Some(src) => self.png(src.trim(), &layer.name.clone())?, + props(&l.props, &mut layer, index, &mut self.warnings); + let image = match &l.src { + Some(src) => self.png(src, &layer.name.clone())?, None => { self.warnings.layer(&layer.name, "the layer has no image; it opens empty"); None } }; - out.push(Node::Raster { layer, image, x, y }); + out.push(Node::Raster { layer, image, x: l.x, y: l.y }); } - "stack" => { + craft_ora::Node::Stack(st) => { let mut layer = Layer::group("", Vec::new()); - props(child, &mut layer, index, &mut self.warnings)?; - let isolation = child.attribute("isolation").map(str::trim); + props(&st.props, &mut layer, index, &mut self.warnings); + let isolation = st.isolation.as_deref(); let pass_through = if self.explicit_group_isolation { // Since 0.0.6 only explicit `auto` passes through, ignoring the // group's composite-op. An omitted isolation means `isolate`. @@ -347,12 +286,12 @@ impl Reader<'_, '_> { if pass_through { layer.blend = BlendMode::PassThrough; } - let children = self.stack(child, depth + 1)?; + let children = self.stack(&st.children, depth + 1)?; out.push(Node::Group { layer, children }); } - other => { - let name = child.attribute("name").unwrap_or(other).to_string(); - self.warnings.layer(&name, &format!("OpenRaster <{other}> elements are not supported and were skipped")); + craft_ora::Node::Other { tag, name } => { + let name = name.as_deref().unwrap_or(tag).to_string(); + self.warnings.layer(&name, &format!("OpenRaster <{tag}> elements are not supported and were skipped")); } } } @@ -417,50 +356,27 @@ fn build(nodes: Vec, images: &[Image], fmt: PixelFormat, budget: &mut usiz } pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result { - let zip = ZipReader::new(bytes).map_err(|e| invalid(e.to_string()))?; - let mime = zip.read_by_name("mimetype", 256).map_err(|e| invalid(e.to_string()))?; - if mime.trim_ascii() != MIMETYPE { - return Err(invalid("the archive's mimetype is not image/openraster")); - } - let xml = zip.read_by_name("stack.xml", MAX_STACK_XML).map_err(|e| invalid(e.to_string()))?; - let xml = std::str::from_utf8(&xml).map_err(|_| invalid("stack.xml is not UTF-8"))?; - let tree = crate::xml::parse(xml, roxmltree::ParsingOptions::default()).map_err(|e| invalid(format!("stack.xml: {e}")))?; - let image = tree.root_element(); - if image.tag_name().name() != "image" { - return Err(invalid("stack.xml has no root")); - } - let side = |attr: &str| -> Result { - let v = num(image, attr, 0.0)?; - if !(1.0..=f64::from(MAX_SIDE)).contains(&v) || v.fract() != 0.0 { - return Err(invalid(format!("image {attr} {v} must be a whole number of pixels from 1 to {MAX_SIDE}"))); - } - Ok(v as u32) - }; - let (w, h) = (side("w")?, side("h")?); - if (w as usize).saturating_mul(h as usize).saturating_mul(8) > MAX_PIXEL_BYTES { - return Err(invalid("the canvas exceeds the 1 GiB pixel limit")); - } - let root = image.children().find(|n| n.has_tag_name("stack")).ok_or_else(|| invalid("stack.xml has no root "))?; + let archive = Archive::open(bytes).map_err(ora_err)?; + let image = archive.image().clone(); let mut reader = Reader { - zip, + archive, ctl, - explicit_group_isolation: uses_explicit_group_isolation(image.attribute("version")), + explicit_group_isolation: image.explicit_group_isolation(), nodes: 0, budget: MAX_PIXEL_BYTES, warnings: Warnings::default(), images: Vec::new(), }; - let nodes = reader.stack(root, 1)?; + let nodes = reader.stack(&image.stack, 1)?; ctl.progress(0.8); let depth = document_depth(&reader.images); if depth == SampleType::F32 { reader.warnings.note("float layer images open as a 32-bit float document"); } let fmt = PixelFormat::new(ColorMode::Rgb, depth, true); - let mut document = Document::new(name, Size::new(w, h), ColorMode::Rgb, depth); + let mut document = Document::new(name, Size::new(image.width, image.height), ColorMode::Rgb, depth); document.layers = build(nodes, &reader.images, fmt, &mut reader.budget, ctl)?; - let xres = num(image, "xres", 72.0)?; - let yres = num(image, "yres", xres)?; + let (xres, yres) = (image.xres, image.yres); if xres > 0.0 && xres < 1.0e6 { document.resolution_dpi = xres as f32; reader.warnings.general.extend(crate::unequal_resolution_warning(xres, yres)); @@ -474,25 +390,6 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - '\t' => out.push_str(" "), - '\n' => out.push_str(" "), - c if c.is_control() => {} - c => out.push(c), - } - } - out -} - /// The composite-op attribute for `mode`: the SVG name where the specification has one, else /// Krita's (`krita:`, which Krita reads back and others treat as Normal). fn op_name(mode: BlendMode) -> Option { @@ -505,8 +402,7 @@ fn op_name(mode: BlendMode) -> Option { struct Writer<'a> { doc: &'a Document, - zip: ZipWriter, - xml: String, + zip: craft_ora::Writer, next: usize, sample: CSample, warnings: Warnings, @@ -569,24 +465,28 @@ fn crop(rect: Rect, mut px: Vec<[f32; 4]>) -> (Rect, Vec<[f32; 4]>) { } impl Writer<'_> { - fn common(&mut self, layer: &Layer) -> String { - let mut attrs = format!( - "name=\"{}\" visibility=\"{}\" opacity=\"{}\"", - escape(&layer.name), - if layer.visible { "visible" } else { "hidden" }, - // OpenRaster has only one opacity for groups. For ordinary isolated groups, - // fold fill opacity into that attribute; groups have no pixel payload in which - // to bake it as raster layers do (#3048). - if matches!(&layer.content, LayerContent::Group(_)) { (layer.opacity * layer.fill_opacity).clamp(0.0, 1.0) } else { layer.opacity.clamp(0.0, 1.0) } - ); + fn common(&mut self, layer: &Layer) -> Props { let op = op_name(layer.blend).unwrap_or_else(|| { self.warnings.layer(&layer.name, &format!("the {} blend mode has no OpenRaster equivalent; it was saved as Normal", layer.blend.label())); "svg:src-over".into() }); - attrs.push_str(&format!(" composite-op=\"{op}\"")); - if layer.locks.all || layer.locks.pixels { - attrs.push_str(" edit-locked=\"true\""); - } + let props = Props { + // Control characters other than tab and newline are not kept, as before the + // attribute writer moved to craft-ora. + name: Some(layer.name.chars().filter(|c| matches!(c, '\t' | '\n') || !c.is_control()).collect()), + visible: layer.visible, + // OpenRaster has only one opacity for groups. For ordinary isolated groups, + // fold fill opacity into that attribute; groups have no pixel payload in which + // to bake it as raster layers do (#3048). + opacity: if matches!(&layer.content, LayerContent::Group(_)) { + (layer.opacity * layer.fill_opacity).clamp(0.0, 1.0) + } else { + layer.opacity.clamp(0.0, 1.0) + }, + composite_op: Some(op), + edit_locked: layer.locks.all || layer.locks.pixels, + alpha_preserve: layer.locks.transparency, + }; // OpenRaster's one edit lock reopens as Lock All; it has no position lock (#7018). if layer.locks.pixels && !layer.locks.all { self.warnings.layer(&layer.name, "Lock Image Pixels was saved as OpenRaster's edit lock; it reopens as Lock All"); @@ -596,9 +496,6 @@ impl Writer<'_> { if layer.locks.position && !layer.locks.all && !self.doc.is_background(layer.id) { self.warnings.layer(&layer.name, "Lock Position is not saved to OpenRaster"); } - if layer.locks.transparency { - attrs.push_str(" alpha-preserve=\"true\""); - } if layer.clipped { self.warnings.layer(&layer.name, "OpenRaster has no clipping masks; these layers were saved unclipped"); } @@ -615,7 +512,7 @@ impl Writer<'_> { self.warnings.layer(&layer.name, "fill opacity was applied to the saved layer pixels"); } } - attrs + props } /// What saving a non-group layer's pixels loses: a type, shape, fill or smart object layer @@ -671,28 +568,29 @@ impl Writer<'_> { Ok(crop(rect, buf)) } - fn layers(&mut self, layers: &[Layer], depth: usize) -> Result<()> { + /// `layers` (bottom-to-top) as stack nodes, topmost first as stack.xml lists them; each + /// layer's image is added to the archive as it is written. + fn layers(&mut self, layers: &[Layer], depth: usize) -> Result> { if depth > photocraft_doc::MAX_GROUP_DEPTH { return Err(IoError::Unsupported(format!("layer groups nested deeper than {}", photocraft_doc::MAX_GROUP_DEPTH))); } - // stack.xml lists the topmost layer first. + let mut out = Vec::new(); for layer in layers.iter().rev() { match &layer.content { LayerContent::Group(g) => { - let attrs = self.common(layer); + let props = self.common(layer); let isolation = if layer.blend == BlendMode::PassThrough { "auto" } else { "isolate" }; if layer.mask.as_ref().is_some_and(|m| m.enabled) { self.warnings.layer(&layer.name, "group masks are not saved to OpenRaster"); } - self.xml.push_str(&format!("")); - self.layers(&g.children, depth + 1)?; - self.xml.push_str(""); + let children = self.layers(&g.children, depth + 1)?; + out.push(craft_ora::Node::Stack(craft_ora::Stack { props, isolation: Some(isolation.into()), children })); } LayerContent::Adjustment(_) => { self.warnings.layer(&layer.name, "adjustment layers cannot be saved to OpenRaster and were left out (the merged image keeps their look)"); } _ => { - let attrs = self.common(layer); + let props = self.common(layer); self.content_warnings(layer); if self.dry { continue; @@ -702,12 +600,12 @@ impl Writer<'_> { let src = format!("data/layer{}.png", self.next); self.next += 1; let data = png(rect.width(), rect.height(), &px, self.sample)?; - self.zip.add(&src, &data)?; - self.xml.push_str(&format!("", rect.x0, rect.y0)); + self.zip.add(&src, &data).map_err(ora_err)?; + out.push(craft_ora::Node::Layer(craft_ora::Layer { props, x: rect.x0, y: rect.y0, src: Some(src) })); } } } - Ok(()) + Ok(out) } } @@ -719,28 +617,19 @@ pub(crate) fn export(doc: &Document) -> Result { SampleType::U8 => CSample::U8, _ => CSample::U16, }; - let mut zip = ZipWriter::new(); - // The mimetype must be the first entry, stored, so the type is readable at a fixed offset. - zip.add("mimetype", MIMETYPE)?; - let mut w = Writer { doc, zip, xml: String::new(), next: 0, sample, warnings: Warnings::default(), dry: false }; + let mut w = Writer { doc, zip: craft_ora::Writer::new(), next: 0, sample, warnings: Warnings::default(), dry: false }; document_warnings(doc, &mut w.warnings); - w.xml.push_str(&format!( - "\n", - doc.size.width, - doc.size.height, - doc.resolution_dpi.round().max(1.0), - doc.resolution_dpi.round().max(1.0) - )); - w.layers(&doc.layers, 1)?; - w.xml.push_str("\n"); - let Writer { mut zip, xml, warnings, .. } = w; - zip.add("stack.xml", xml.as_bytes())?; + let stack = w.layers(&doc.layers, 1)?; + let Writer { mut zip, warnings, .. } = w; + let dpi = f64::from(doc.resolution_dpi.round().max(1.0)); + let image = craft_ora::Image { version: None, width: doc.size.width, height: doc.size.height, xres: dpi, yres: dpi, stack }; + zip.add_stack(&image).map_err(ora_err)?; let merged = photocraft_compose::flatten(doc); - zip.add("mergedimage.png", &png(doc.size.width, doc.size.height, &merged.px, sample)?)?; + zip.add("mergedimage.png", &png(doc.size.width, doc.size.height, &merged.px, sample)?).map_err(ora_err)?; let thumb = photocraft_compose::thumbnail(doc, THUMBNAIL_SIDE); let thumb = Image::from_raw(thumb.width, thumb.height, ChannelLayout::Rgba, CSample::U8, thumb.pixels)?; - zip.add("Thumbnails/thumbnail.png", &codecs::encode(&thumb, Format::Png, &codecs::EncodeOptions::default())?)?; - Ok(ExportResult { bytes: zip.finish()?, warnings: warnings.finish() }) + zip.add("Thumbnails/thumbnail.png", &codecs::encode(&thumb, Format::Png, &codecs::EncodeOptions::default())?).map_err(ora_err)?; + Ok(ExportResult { bytes: zip.finish().map_err(ora_err)?, warnings: warnings.finish() }) } /// What saving `doc` to OpenRaster loses that isn't in a layer. @@ -771,7 +660,7 @@ pub fn losses(doc: &Document) -> Vec { if !matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale) { return vec!["OpenRaster holds RGB layers; convert the document to RGB or Grayscale first".into()]; } - let mut w = Writer { doc, zip: ZipWriter::new(), xml: String::new(), next: 0, sample: CSample::U8, warnings: Warnings::default(), dry: true }; + let mut w = Writer { doc, zip: craft_ora::Writer::new(), next: 0, sample: CSample::U8, warnings: Warnings::default(), dry: true }; document_warnings(doc, &mut w.warnings); if let Err(e) = w.layers(&doc.layers, 1) { w.warnings.note(&e.to_string()); diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs index e4797fc52d..4726486708 100644 --- a/crates/io/src/ora/tests.rs +++ b/crates/io/src/ora/tests.rs @@ -1,5 +1,7 @@ use super::*; +use craft_ora::{MAX_NODES, MIMETYPE}; use photocraft_doc::{Adjustment, Color, Fill, LayerMask}; +use photocraft_format::zip::{ZipReader, ZipWriter}; const CANVAS: Size = Size { width: 70, height: 50 }; @@ -202,7 +204,7 @@ fn deeply_nested_stack_xml_is_an_error_not_a_stack_overflow() { let stack = format!("{}{}", "".repeat(20_000), "".repeat(20_000)); let bytes = archive(&stack, &[]); let e = std::thread::Builder::new().stack_size(512 * 1024).spawn(move || crate::import("deep.ora", &bytes).err()).unwrap().join().unwrap(); - assert!(matches!(&e, Some(IoError::Ora(m)) if m.contains("nested")), "{e:?}"); + assert!(matches!(&e, Some(IoError::Ora(m)) if m.contains("nest")), "{e:?}"); } fn solid_png(w: u32, h: u32, rgba: [u8; 4]) -> Vec { @@ -466,17 +468,6 @@ fn truncated_and_corrupted_files_never_panic() { } } -#[test] -fn zip_mimetype_reads_only_a_leading_stored_entry() { - assert_eq!(zip_mimetype(&archive("", &[])), Some(MIMETYPE)); - assert_eq!(zip_mimetype(b"PK\x03\x04"), None); - assert_eq!(zip_mimetype(&[]), None); - let mut z = ZipWriter::new(); - z.add("stack.xml", b"x").unwrap(); - z.add("mimetype", MIMETYPE).unwrap(); - assert_eq!(zip_mimetype(&z.finish().unwrap()), None); -} - #[test] fn export_names_route_through_the_crate_entry_point() { let d = doc(SampleType::U8); diff --git a/crates/io/src/pdn.rs b/crates/io/src/pdn.rs index 796c44f426..5facf3288b 100644 --- a/crates/io/src/pdn.rs +++ b/crates/io/src/pdn.rs @@ -1,263 +1,104 @@ -//! Native, import-only PDN3 reader. Layout reference: addisonElliott/pypdn's reader; -//! NRBF records follow Microsoft's public MS-NRBF specification (see `nrbf`). +//! Paint.NET (`.pdn`) import: the PDN3 reader is craft-libs' `craft-pdn`. This maps its layers +//! and BGRA surfaces onto documents and charges the tiles they are stored in to the budget. -mod nrbf; #[cfg(test)] mod tests; use std::collections::HashMap; -use std::io::Read; +use craft_pdn::{BlendMode as PdnBlend, MAX_PIXEL_BYTES}; use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Document, Layer, LayerContent}; use photocraft_geom::{Rect, Size}; use photocraft_raster::{Interrupt, Surface}; use crate::{ImportResult, IoError}; -use nrbf::{Graph, Reader, Value}; type Result = std::result::Result; -// shortcut: imports cap decoded pixels at 1 GiB, use streamed tile decoding for larger PDNs. -const MAX_PIXEL_BYTES: usize = 1 << 30; -const MAX_LAYERS: usize = 1024; -const MODES: [BlendMode; 14] = [ - BlendMode::Normal, - BlendMode::Multiply, - BlendMode::LinearDodge, - BlendMode::PaintNetColorBurn, - BlendMode::PaintNetColorDodge, - BlendMode::Reflect, - BlendMode::Glow, - BlendMode::Overlay, - BlendMode::Difference, - BlendMode::Negation, - BlendMode::Lighten, - BlendMode::Darken, - BlendMode::Screen, - BlendMode::Xor, -]; -const OLD_MODES: [&str; 14] = - ["Normal", "Multiply", "Additive", "ColorBurn", "ColorDodge", "Reflect", "Glow", "Overlay", "Difference", "Negation", "Lighten", "Darken", "Screen", "Xor"]; - fn invalid(message: impl Into) -> IoError { IoError::Pdn(message.into()) } -fn count(graph: &Graph, object: &Value, field: &str) -> Result { - usize::try_from(graph.integer(graph.field(object, field)?)?).map_err(|_| invalid(format!("invalid {field}"))) +/// The format crate's error as this crate's. +fn pdn_err(e: craft_pdn::Error) -> IoError { + match e { + craft_pdn::Error::Invalid(m) => invalid(m), + craft_pdn::Error::Cancelled => IoError::Cancelled, + } } -fn blend(graph: &Graph, layer: &Value, props: &Value) -> Result { - if let Some(mode) = graph.optional_field(props, "blendMode")? { - let mode = match graph.resolve(mode)? { - Value::Int(n) => *n, - _ => graph.integer(graph.field(mode, "value__")?)?, - }; - let mode = usize::try_from(mode).map_err(|_| invalid("invalid blend mode"))?; - return MODES.get(mode).copied().ok_or_else(|| invalid(format!("unsupported blend mode {mode}"))); +fn blend(mode: PdnBlend) -> BlendMode { + match mode { + PdnBlend::Normal => BlendMode::Normal, + PdnBlend::Multiply => BlendMode::Multiply, + PdnBlend::Additive => BlendMode::LinearDodge, + PdnBlend::ColorBurn => BlendMode::PaintNetColorBurn, + PdnBlend::ColorDodge => BlendMode::PaintNetColorDodge, + PdnBlend::Reflect => BlendMode::Reflect, + PdnBlend::Glow => BlendMode::Glow, + PdnBlend::Overlay => BlendMode::Overlay, + PdnBlend::Difference => BlendMode::Difference, + PdnBlend::Negation => BlendMode::Negation, + PdnBlend::Lighten => BlendMode::Lighten, + PdnBlend::Darken => BlendMode::Darken, + PdnBlend::Screen => BlendMode::Screen, + PdnBlend::Xor => BlendMode::Xor, } - let props = graph.field(layer, "properties")?; - let mode = graph.class_name(graph.field(props, "blendOp")?)?; - let mode = mode - .strip_prefix("PaintDotNet.UserBlendOps+") - .and_then(|s| s.strip_suffix("BlendOp")) - .ok_or_else(|| invalid(format!("unsupported blend operation {mode}")))?; - OLD_MODES.iter().position(|m| *m == mode).and_then(|i| MODES.get(i)).copied().ok_or_else(|| invalid(format!("unsupported blend operation {mode}"))) -} - -/// Reads a memory block's numbered chunks in their on-disk order; each chunk has its own gzip -/// stream and checksum. Inflate directly into the bounded destination, checking its exact size. -fn pixels(reader: &mut Reader<'_>, length: usize, ctl: &Interrupt<'_>) -> Result> { - let version = reader.byte()?; - if version > 1 { - return Err(invalid(format!("unsupported pixel compression {version}"))); - } - let chunk_size = reader.be_u32()?; - if chunk_size == 0 { - return Err(invalid("zero pixel chunk size")); - } - let chunks = length.div_ceil(chunk_size); - if chunks > 1_000_000 { - return Err(invalid("too many pixel chunks")); - } - // Uncompressed chunks hold every pixel byte: a file shorter than that is truncated, and is - // rejected before the buffer is allocated. - if version == 1 && reader.bytes.len().saturating_sub(reader.pos) < length { - return Err(invalid("uncompressed pixel data is truncated")); - } - let mut seen = vec![false; chunks]; - let mut data = vec![0; length]; - for _ in 0..chunks { - ctl.check().map_err(|_| IoError::Cancelled)?; - let index = reader.be_u32()?; - let found = seen.get_mut(index).ok_or_else(|| invalid("pixel chunk index out of bounds"))?; - if *found { - return Err(invalid("duplicate pixel chunk")); - } - *found = true; - let size = reader.be_u32()?; - let raw = reader.take(size)?; - let start = index.checked_mul(chunk_size).ok_or_else(|| invalid("pixel offset overflow"))?; - let end = start.checked_add(chunk_size.min(length.saturating_sub(start))).ok_or_else(|| invalid("pixel offset overflow"))?; - let dst = data.get_mut(start..end).ok_or_else(|| invalid("invalid pixel chunk range"))?; - if version == 0 { - let mut decoder = flate2::bufread::GzDecoder::new(raw); - for band in dst.chunks_mut(1 << 20) { - ctl.check().map_err(|_| IoError::Cancelled)?; - decoder.read_exact(band).map_err(|e| invalid(format!("invalid gzip pixel chunk: {e}")))?; - } - let mut extra = [0]; - if decoder.read(&mut extra).map_err(|e| invalid(format!("invalid gzip pixel checksum: {e}")))? != 0 || !decoder.into_inner().is_empty() { - return Err(invalid("pixel chunk has excess data")); - } - } else { - if raw.len() != dst.len() { - return Err(invalid("incorrect uncompressed pixel chunk size")); - } - dst.copy_from_slice(raw); - } - } - Ok(data) } pub(super) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result { - let mut reader = Reader { bytes, pos: 0 }; - if reader.take(4)? != b"PDN3" { - return Err(invalid("unsupported document signature (expected PDN3)")); - } - let mut header_size = [0; 4]; - header_size.get_mut(..3).ok_or_else(|| invalid("invalid header"))?.copy_from_slice(reader.take(3)?); - reader.take(u32::from_le_bytes(header_size) as usize)?; - if reader.take(2)? != [0, 1] { - return Err(invalid("unsupported PDN3 serialization version")); - } - let graph = nrbf::parse(&mut reader, ctl)?; - let root = &graph.root; - if graph.class_name(root)? != "PaintDotNet.Document" { - return Err(invalid("root object is not a Paint.NET document")); - } - let width = count(&graph, root, "width")?; - let height = count(&graph, root, "height")?; - let row_bytes = width.checked_mul(4).ok_or_else(|| invalid("canvas size overflow"))?; - let canvas_bytes = row_bytes.checked_mul(height).ok_or_else(|| invalid("canvas size overflow"))?; - if width == 0 || height == 0 || width > i32::MAX as usize || height > i32::MAX as usize || canvas_bytes > MAX_PIXEL_BYTES { - return Err(invalid("canvas is empty or exceeds the 1 GiB pixel limit")); - } - let list = graph.field(root, "layers")?; - let layers = graph.array(graph.field(list, "ArrayList+_items")?)?; - let len = count(&graph, list, "ArrayList+_size")?; - if len == 0 || len > MAX_LAYERS { - return Err(invalid("document must have 1..1024 bitmap layers")); - } - let layers = layers.get(..len).ok_or_else(|| invalid("layer list count exceeds its array"))?; - let bounds = Rect::from_xywh(0, 0, width as u32, height as u32); - let mut layouts = HashMap::new(); - let mut output = Vec::with_capacity(len); - // Each output layer owns a copy of its name, but the NRBF graph charges a shared string - // only once when serialized. Repeated references to one large name would multiply into - // gigabytes of retained copies, so cap each name and the aggregate copied bytes. - const MAX_NAME_BYTES: usize = 64 * 1024; - const MAX_TOTAL_NAME_BYTES: usize = 4 * 1024 * 1024; - let mut name_bytes = 0usize; - for layer in layers { - ctl.check().map_err(|_| IoError::Cancelled)?; - if graph.class_name(layer)? != "PaintDotNet.BitmapLayer" { - return Err(invalid("only PDN3 bitmap layers are supported")); - } - if count(&graph, layer, "Layer+width")? != width || count(&graph, layer, "Layer+height")? != height { - return Err(invalid("layer dimensions do not match the canvas")); - } - let surface = graph.field(layer, "surface")?; - if graph.class_name(surface)? != "PaintDotNet.Surface" || count(&graph, surface, "width")? != width || count(&graph, surface, "height")? != height { - return Err(invalid("invalid bitmap surface")); - } - let stride = count(&graph, surface, "stride")?; - if stride < row_bytes { - return Err(invalid("surface stride is too short for BGRA32 pixels")); - } - let memory = graph.field(surface, "scan0")?; - let Value::Ref(id) = memory else { return Err(invalid("missing pixel memory reference")) }; - if let Some(old) = layouts.insert(*id, stride) - && old != stride - { - return Err(invalid("shared pixel memory has inconsistent strides")); - } - let props = graph.field(layer, "Layer+properties")?; - let opacity = count(&graph, props, "opacity")?; - if opacity > 255 { - return Err(invalid("opacity exceeds 255")); - } - let mut l = Layer::raster( - { - let name = graph.string(graph.field(props, "name")?)?; - if name.len() > MAX_NAME_BYTES { - return Err(invalid("layer name is too long")); - } - name_bytes = name_bytes.saturating_add(name.len()); - if name_bytes > MAX_TOTAL_NAME_BYTES { - return Err(invalid("layer names exceed the total metadata budget")); - } - name.to_string() - }, - PixelFormat::RGBA8, - ); - l.visible = graph.boolean(graph.field(props, "visible")?)?; - l.opacity = opacity as f32 / 255.0; - l.blend = blend(&graph, layer, props)?; - output.push((*id, l)); - } - let blocks: Vec<_> = graph.objects_of_class("PaintDotNet.MemoryBlock").collect(); - let mut total = 0usize; - // Validate every allocation before decoding any block. - for (id, block) in &blocks { - let length = count(&graph, block, "length64")?; - let stride = *layouts.get(id).ok_or_else(|| invalid("unreferenced pixel memory block"))?; - if length != stride.checked_mul(height).ok_or_else(|| invalid("pixel length overflow"))? { - return Err(invalid("pixel memory length does not match the surface")); - } - if graph.boolean(graph.field(block, "hasParent")?)? || !graph.boolean(graph.field(block, "deferred")?)? { - return Err(invalid("unsupported non-deferred or parented pixel memory")); - } - total = total.checked_add(length).ok_or_else(|| invalid("pixel length overflow"))?; - // The packed rows plus the whole tiles the surface keeps them in (a narrow canvas - // stores up to 256 times its packed bytes). - let tiles = usize::try_from(photocraft_raster::tile_storage_bytes(bounds, &PixelFormat::RGBA8)).unwrap_or(usize::MAX); - total = total.checked_add(tiles).ok_or_else(|| invalid("pixel length overflow"))?; - if total > MAX_PIXEL_BYTES { - return Err(invalid("decoded pixels exceed the 1 GiB limit")); - } + let keep_going = || ctl.check().is_ok(); + let doc = craft_pdn::Document::parse(bytes, &keep_going).map_err(pdn_err)?; + let (width, height) = (doc.width, doc.height); + let (w, h) = (u32::try_from(width).map_err(|_| invalid("canvas size overflow"))?, u32::try_from(height).map_err(|_| invalid("canvas size overflow"))?); + let bounds = Rect::from_xywh(0, 0, w, h); + // Every allocation is checked before any block is decoded: the packed rows plus the whole + // tiles each surface keeps them in (a narrow canvas stores up to 256 times its packed bytes). + let tiles = usize::try_from(photocraft_raster::tile_storage_bytes(bounds, &PixelFormat::RGBA8)).unwrap_or(usize::MAX); + let total = tiles.checked_mul(doc.surface_count()).and_then(|t| t.checked_add(doc.decoded_bytes())).ok_or_else(|| invalid("pixel length overflow"))?; + if total > MAX_PIXEL_BYTES { + return Err(invalid("decoded pixels exceed the 1 GiB limit")); } + let count = doc.surface_count(); let mut surfaces = HashMap::new(); - for (i, (id, block)) in blocks.iter().enumerate() { - let length = count(&graph, block, "length64")?; - let mut data = pixels(&mut reader, length, ctl)?; - let stride = *layouts.get(id).ok_or_else(|| invalid("missing surface layout"))?; + let mut failed = None; + doc.read_surfaces(&keep_going, &mut |i, s| { + if failed.is_some() { + return; + } let mut surface = Surface::new(PixelFormat::RGBA8); - for (y, row) in data.chunks_exact_mut(stride).enumerate() { - ctl.check().map_err(|_| IoError::Cancelled)?; - let row = row.get_mut(..row_bytes).ok_or_else(|| invalid("invalid pixel row"))?; + let mut row = Vec::with_capacity(width * 4); + for (y, src) in s.rows().enumerate() { + if ctl.check().is_err() { + failed = Some(IoError::Cancelled); + return; + } + row.clear(); + row.extend_from_slice(src); for pixel in row.as_chunks_mut::<4>().0 { pixel.swap(0, 2); } - surface.write_interleaved(Rect::from_xywh(0, y as i32, bounds.width(), 1), row); + surface.write_interleaved(Rect::from_xywh(0, y as i32, w, 1), &row); } - surfaces.insert(*id, surface); - ctl.progress(0.05 + 0.95 * (i + 1) as f32 / blocks.len() as f32); + surfaces.insert(i, surface); + ctl.progress(0.05 + 0.95 * (i + 1) as f32 / count as f32); + }) + .map_err(pdn_err)?; + if let Some(e) = failed { + return Err(e); } - if reader.pos != bytes.len() { - return Err(invalid("unexpected trailing data")); - } - let mut document = Document::new(name, Size::new(width as u32, height as u32), ColorMode::Rgb, SampleType::U8); - for (id, mut layer) in output { - layer.content = LayerContent::Raster(surfaces.get(&id).cloned().ok_or_else(|| invalid("missing pixel memory block"))?); + let mut document = Document::new(name, Size::new(w, h), ColorMode::Rgb, SampleType::U8); + for l in &doc.layers { + let mut layer = Layer::raster(l.name.clone(), PixelFormat::RGBA8); + layer.visible = l.visible; + layer.opacity = f32::from(l.opacity) / 255.0; + layer.blend = blend(l.blend); + layer.content = LayerContent::Raster(surfaces.get(&l.surface).cloned().ok_or_else(|| invalid("missing pixel memory block"))?); document.layers.push(layer); } let mut warnings = Vec::new(); - if let Some(meta) = graph.optional_field(root, "userMetadataItems")? - && !matches!(graph.resolve(meta)?, Value::Null) - && !graph.array(meta)?.is_empty() - { + if doc.has_user_metadata { warnings.push("Paint.NET document metadata was not imported".into()); } Ok(ImportResult { document, warnings, source_read_only: true, preview_only: false }) diff --git a/crates/io/src/pdn/nrbf.rs b/crates/io/src/pdn/nrbf.rs deleted file mode 100644 index 065bf7a7af..0000000000 --- a/crates/io/src/pdn/nrbf.rs +++ /dev/null @@ -1,420 +0,0 @@ -//! Data-only subset of MS-NRBF used by PDN3. References stay as ids; no .NET types are executed. -//! https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nrbf/ - -use std::collections::HashMap; -use std::sync::Arc; - -use photocraft_raster::Interrupt; - -use super::{Result, invalid}; - -const MAX_ITEMS: usize = 1_000_000; -const MAX_STRINGS: usize = 64 << 20; -const MAX_DEPTH: usize = 64; - -pub(super) struct Reader<'a> { - pub bytes: &'a [u8], - pub pos: usize, -} - -impl<'a> Reader<'a> { - pub fn take(&mut self, len: usize) -> Result<&'a [u8]> { - let end = self.pos.checked_add(len).ok_or_else(|| invalid("length overflow"))?; - let b = self.bytes.get(self.pos..end).ok_or_else(|| invalid("truncated document"))?; - self.pos = end; - Ok(b) - } - - pub fn byte(&mut self) -> Result { - Ok(self.take(1)?.first().copied().unwrap_or_default()) - } - - pub fn le_i32(&mut self) -> Result { - Ok(i32::from_le_bytes(self.take(4)?.try_into().map_err(|_| invalid("invalid integer"))?)) - } - - pub fn be_u32(&mut self) -> Result { - usize::try_from(u32::from_be_bytes(self.take(4)?.try_into().map_err(|_| invalid("invalid integer"))?)).map_err(|_| invalid("length overflow")) - } - - fn count(&mut self) -> Result { - let n = usize::try_from(self.le_i32()?).map_err(|_| invalid("negative count"))?; - if n > MAX_ITEMS { - return Err(invalid("serialized array or class is too large")); - } - Ok(n) - } -} - -#[derive(Debug)] -pub(super) struct Class { - name: String, - names: Vec, - primitives: Vec>, -} - -#[derive(Debug)] -pub(super) enum Value { - Null, - Bool(bool), - Int(i64), - String(String), - Ref(i32), - Array(Vec), - Object { class: Arc, members: Vec }, -} - -pub(super) struct Graph { - pub root: Value, - objects: HashMap, - order: Vec, -} - -impl Graph { - pub fn objects_of_class<'a>(&'a self, name: &'a str) -> impl Iterator { - self.order - .iter() - .filter_map(|id| self.objects.get(id).map(|v| (*id, v))) - .filter(move |(_, v)| matches!(v, Value::Object { class, .. } if class.name == name)) - } - pub fn resolve<'a>(&'a self, mut value: &'a Value) -> Result<&'a Value> { - for _ in 0..MAX_DEPTH { - match value { - Value::Ref(id) => value = self.objects.get(id).ok_or_else(|| invalid("missing object reference"))?, - _ => return Ok(value), - } - } - Err(invalid("cyclic or excessively deep object reference")) - } - - pub fn class_name<'a>(&'a self, value: &'a Value) -> Result<&'a str> { - match self.resolve(value)? { - Value::Object { class, .. } => Ok(&class.name), - _ => Err(invalid("expected a serialized object")), - } - } - - pub fn field<'a>(&'a self, value: &'a Value, name: &str) -> Result<&'a Value> { - self.optional_field(value, name)?.ok_or_else(|| invalid(format!("missing field {name}"))) - } - - pub fn optional_field<'a>(&'a self, value: &'a Value, name: &str) -> Result> { - match self.resolve(value)? { - Value::Object { class, members } => Ok(class.names.iter().position(|n| n == name).and_then(|i| members.get(i))), - _ => Err(invalid("expected a serialized object")), - } - } - - pub fn integer(&self, value: &Value) -> Result { - match self.resolve(value)? { - Value::Int(n) => Ok(*n), - _ => Err(invalid("expected an integer")), - } - } - - pub fn boolean(&self, value: &Value) -> Result { - match self.resolve(value)? { - Value::Bool(b) => Ok(*b), - _ => Err(invalid("expected a boolean")), - } - } - - pub fn string<'a>(&'a self, value: &'a Value) -> Result<&'a str> { - match self.resolve(value)? { - Value::String(s) => Ok(s), - _ => Err(invalid("expected a string")), - } - } - - pub fn array<'a>(&'a self, value: &'a Value) -> Result<&'a [Value]> { - match self.resolve(value)? { - Value::Array(a) => Ok(a), - _ => Err(invalid("expected an array")), - } - } -} - -struct Parser<'a, 'b> { - reader: &'b mut Reader<'a>, - ctl: &'b Interrupt<'b>, - graph: Graph, - classes: HashMap>, - items: usize, - strings: usize, -} - -pub(super) fn parse(reader: &mut Reader<'_>, ctl: &Interrupt<'_>) -> Result { - if reader.byte()? != 0 { - return Err(invalid("missing NRBF stream header")); - } - let root = reader.le_i32()?; - let _header = reader.le_i32()?; - if root == 0 || reader.le_i32()? != 1 || reader.le_i32()? != 0 { - return Err(invalid("unsupported NRBF stream version")); - } - let mut parser = Parser { - reader, - ctl, - graph: Graph { root: Value::Ref(root), objects: HashMap::new(), order: Vec::new() }, - classes: HashMap::new(), - items: 0, - strings: 0, - }; - loop { - let tag = parser.reader.byte()?; - if tag == 11 { - break; - } - parser.record(tag, 0)?; - } - parser.graph.resolve(&parser.graph.root)?; - Ok(parser.graph) -} - -impl Parser<'_, '_> { - fn budget(&mut self, n: usize) -> Result<()> { - self.items = self.items.checked_add(n).ok_or_else(|| invalid("object count overflow"))?; - if self.items > MAX_ITEMS { - return Err(invalid("too many serialized objects or members")); - } - Ok(()) - } - - fn string(&mut self) -> Result { - let mut len = 0usize; - for shift in (0..35).step_by(7) { - let b = self.reader.byte()?; - if shift == 28 && b > 7 { - return Err(invalid("invalid string length")); - } - len |= usize::from(b & 127) << shift; - if b & 128 == 0 { - self.strings = self.strings.checked_add(len).ok_or_else(|| invalid("string length overflow"))?; - if self.strings > MAX_STRINGS { - return Err(invalid("serialized strings are too large")); - } - return String::from_utf8(self.reader.take(len)?.to_vec()).map_err(|_| invalid("invalid UTF-8 string")); - } - } - Err(invalid("invalid string length")) - } - - fn primitive(&mut self, tag: u8) -> Result { - macro_rules! number { - ($ty:ty, $variant:ident) => { - Value::$variant(<$ty>::from_le_bytes(self.reader.take(size_of::<$ty>())?.try_into().map_err(|_| invalid("invalid primitive"))?).into()) - }; - } - Ok(match tag { - 1 => match self.reader.byte()? { - 0 => Value::Bool(false), - 1 => Value::Bool(true), - _ => return Err(invalid("invalid boolean")), - }, - 2 => Value::Int(i64::from(self.reader.byte()?)), - 3 => { - let first = self.reader.byte()?; - let len = match first { - 0..=0x7f => 1, - 0xc2..=0xdf => 2, - 0xe0..=0xef => 3, - _ => return Err(invalid("invalid character")), - }; - let mut b = vec![first]; - b.extend_from_slice(self.reader.take(len - 1)?); - Value::String(String::from_utf8(b).map_err(|_| invalid("invalid character"))?) - } - 5 | 18 => Value::String(self.string()?), - 6 => { - self.reader.take(8)?; - Value::Null - } - 7 => number!(i16, Int), - 8 => number!(i32, Int), - 9 | 12 => number!(i64, Int), - 10 => Value::Int(i64::from(self.reader.byte()? as i8)), - 11 => { - self.reader.take(4)?; - Value::Null - } - 13 | 16 => { - let n = u64::from_le_bytes(self.reader.take(8)?.try_into().map_err(|_| invalid("invalid integer"))?); - // Metadata dates may use the high bits; their bit pattern stays intact. - Value::Int(n as i64) - } - 14 => number!(u16, Int), - 15 => number!(u32, Int), - 17 => Value::Null, - _ => return Err(invalid(format!("unsupported primitive type {tag}"))), - }) - } - - fn type_info(&mut self, tag: u8) -> Result> { - match tag { - 0 => Ok(Some(self.reader.byte()?)), - 1 | 2 | 5 | 6 => Ok(None), - 3 => { - self.string()?; - Ok(None) - } - 4 => { - self.string()?; - self.reader.le_i32()?; - Ok(None) - } - 7 => { - self.reader.byte()?; - Ok(None) - } - _ => Err(invalid(format!("unsupported binary type {tag}"))), - } - } - - fn reserve(&mut self, id: i32) -> Result<()> { - if id == 0 || self.graph.objects.insert(id, Value::Null).is_some() { - return Err(invalid("duplicate or zero object id")); - } - self.graph.order.push(id); - Ok(()) - } - - fn value(&mut self, depth: usize) -> Result { - loop { - let tag = self.reader.byte()?; - if tag == 12 { - self.record(tag, depth)?; - } else { - return self.record(tag, depth); - } - } - } - - fn object(&mut self, id: i32, class: Arc, depth: usize) -> Result { - self.reserve(id)?; - self.budget(class.names.len())?; - let mut members = Vec::with_capacity(class.names.len()); - for primitive in &class.primitives { - members.push(match primitive { - Some(p) => self.primitive(*p)?, - None => self.value(depth + 1)?, - }); - } - self.graph.objects.insert(id, Value::Object { class, members }); - Ok(Value::Ref(id)) - } - - fn array(&mut self, id: i32, len: usize, primitive: Option, depth: usize) -> Result { - self.reserve(id)?; - self.budget(len)?; - if primitive == Some(2) { - self.reader.take(len)?; - return Ok(Value::Ref(id)); - } - let mut values = Vec::with_capacity(len); - while values.len() < len { - self.ctl.check().map_err(|_| crate::IoError::Cancelled)?; - if let Some(p) = primitive { - values.push(self.primitive(p)?); - continue; - } - let tag = self.reader.byte()?; - if matches!(tag, 13 | 14) { - let count = if tag == 13 { usize::from(self.reader.byte()?) } else { self.reader.count()? }; - if count == 0 || count > len - values.len() { - return Err(invalid("invalid array null run")); - } - values.resize_with(values.len() + count, || Value::Null); - } else if tag == 12 { - self.record(tag, depth + 1)?; - } else { - values.push(self.record(tag, depth + 1)?); - } - } - self.graph.objects.insert(id, Value::Array(values)); - Ok(Value::Ref(id)) - } - - fn record(&mut self, tag: u8, depth: usize) -> Result { - self.ctl.check().map_err(|_| crate::IoError::Cancelled)?; - self.budget(1)?; - if depth > MAX_DEPTH { - return Err(invalid("serialized objects nested too deeply")); - } - match tag { - 1 => { - let id = self.reader.le_i32()?; - let metadata = self.reader.le_i32()?; - let class = self.classes.get(&metadata).cloned().ok_or_else(|| invalid("missing class metadata"))?; - self.object(id, class, depth) - } - 2..=5 => { - let id = self.reader.le_i32()?; - let name = self.string()?; - let count = self.reader.count()?; - self.budget(count)?; - let names = (0..count).map(|_| self.string()).collect::>>()?; - let primitives = if tag >= 4 { - let types = self.reader.take(count)?.to_vec(); - types.into_iter().map(|t| self.type_info(t)).collect::>>()? - } else { - vec![None; count] - }; - if matches!(tag, 3 | 5) { - self.reader.le_i32()?; - } - let class = Arc::new(Class { name, names, primitives }); - if self.classes.insert(id, class.clone()).is_some() { - return Err(invalid("duplicate class metadata")); - } - self.object(id, class, depth) - } - 6 => { - let id = self.reader.le_i32()?; - self.reserve(id)?; - let value = Value::String(self.string()?); - self.graph.objects.insert(id, value); - Ok(Value::Ref(id)) - } - 7 => { - let id = self.reader.le_i32()?; - let kind = self.reader.byte()?; - let rank = self.reader.count()?; - if kind > 5 || rank == 0 || rank > 32 { - return Err(invalid("invalid array dimensions")); - } - let mut len = 1usize; - for _ in 0..rank { - len = len.checked_mul(self.reader.count()?).ok_or_else(|| invalid("array size overflow"))?; - } - if kind >= 3 { - for _ in 0..rank { - if self.reader.le_i32()? != 0 { - return Err(invalid("nonzero array lower bounds are unsupported")); - } - } - } - let tag = self.reader.byte()?; - let primitive = self.type_info(tag)?; - self.array(id, len, primitive, depth) - } - 8 => { - let primitive = self.reader.byte()?; - self.primitive(primitive) - } - 9 => Ok(Value::Ref(self.reader.le_i32()?)), - 10 => Ok(Value::Null), - 12 => { - self.reader.le_i32()?; - self.string()?; - Ok(Value::Null) - } - 15..=17 => { - let id = self.reader.le_i32()?; - let len = self.reader.count()?; - let primitive = if tag == 15 { Some(self.reader.byte()?) } else { None }; - self.array(id, len, primitive, depth) - } - _ => Err(invalid(format!("unsupported NRBF record {tag}"))), - } - } -} diff --git a/crates/io/src/pdn/tests.rs b/crates/io/src/pdn/tests.rs index 139c87d6ae..14dec2925e 100644 --- a/crates/io/src/pdn/tests.rs +++ b/crates/io/src/pdn/tests.rs @@ -1,4 +1,22 @@ use super::*; + +/// Paint.NET's modes in its numeric order, as they open here. +const MODES: [BlendMode; 14] = [ + BlendMode::Normal, + BlendMode::Multiply, + BlendMode::LinearDodge, + BlendMode::PaintNetColorBurn, + BlendMode::PaintNetColorDodge, + BlendMode::Reflect, + BlendMode::Glow, + BlendMode::Overlay, + BlendMode::Difference, + BlendMode::Negation, + BlendMode::Lighten, + BlendMode::Darken, + BlendMode::Screen, + BlendMode::Xor, +]; use std::io::Write; enum Field { @@ -101,7 +119,7 @@ fn fixture(modes: &[i32], legacy: bool, compressed: bool) -> Vec { w.int(id + 4); w.string(&format!("Läyer {i}")); w.object(id + 5, "PaintDotNet.LayerBlendMode", &[("value__", Int(*mode))]); - w.object(id + 6, &format!("PaintDotNet.UserBlendOps+{}BlendOp", OLD_MODES.get(*mode as usize).unwrap_or(&"Unknown")), &[]); + w.object(id + 6, &format!("PaintDotNet.UserBlendOps+{}BlendOp", craft_pdn::BlendMode::ALL.get(*mode as usize).map_or("Unknown", |m| m.name())), &[]); w.object(id + 7, "PaintDotNet.MemoryBlock", &[("length64", Long(24)), ("hasParent", Bool(false)), ("deferred", Bool(true))]); } w.0.push(11); @@ -240,60 +258,8 @@ fn malformed_pdn_reports_a_format_error() { } } -#[test] -fn serialized_counts_depth_and_references_are_bounded() { - let header = || { - let mut w = Writer(vec![0]); - for n in [1, -1, 1, 0] { - w.int(n); - } - w - }; - let mut oversized = header(); - oversized.0.push(16); - oversized.int(1); - oversized.int(1_000_001); - let mut nested = header(); - for id in 1..=66 { - nested.0.push(16); - nested.int(id); - nested.int(1); - } - nested.0.extend([10, 11]); - let mut duplicate = header(); - for _ in 0..2 { - duplicate.0.push(6); - duplicate.int(1); - duplicate.string("duplicate"); - } - duplicate.0.push(11); - let mut null_run = header(); - null_run.0.push(16); - null_run.int(1); - null_run.int(1); - null_run.0.extend([13, 2, 11]); - let mut missing_class = header(); - missing_class.0.push(1); - missing_class.int(1); - missing_class.int(999); - let mut missing_root = header(); - missing_root.0.push(11); - for w in [oversized, nested, duplicate, null_run, missing_class, missing_root] { - let mut reader = Reader { bytes: &w.0, pos: 0 }; - assert!(nrbf::parse(&mut reader, &Interrupt::NONE).is_err()); - } -} - #[test] fn pdn_export_is_explicitly_unsupported() { let doc = Document::new("x", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); assert!(matches!(crate::export(&doc, "x.pdn", &Default::default()), Err(IoError::Unsupported(_)))); } - -#[test] -fn truncated_uncompressed_pixels_are_rejected_before_allocating() { - // A raw (version 1) block of 256 MiB chunks that declares 1 GiB of pixels but holds a few bytes. - let mut reader = Reader { bytes: &[1, 0x10, 0, 0, 0, 0, 0, 0, 0], pos: 0 }; - let e = pixels(&mut reader, 1 << 30, &Interrupt::NONE).err().map(|e| e.to_string()).unwrap_or_default(); - assert!(e.contains("uncompressed pixel data is truncated"), "{e}"); -} diff --git a/crates/io/src/xcf.rs b/crates/io/src/xcf.rs index 7761415563..1e401dc186 100644 --- a/crates/io/src/xcf.rs +++ b/crates/io/src/xcf.rs @@ -17,506 +17,53 @@ #[cfg(test)] mod tests; -use std::collections::HashMap; -use std::io::Read; use std::sync::Arc; -use photocraft_codecs::f16; +use craft_xcf::{BaseType, Orientation, Pixels, Precision, TreeNode, Xcf}; use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{AlphaChannel, Document, LabelColor, Layer, LayerContent, LayerMask}; +use photocraft_doc::{AlphaChannel, Document, LabelColor, Layer, LayerContent, LayerMask, Locks}; use photocraft_geom::{Rect, Size}; use photocraft_raster::{Interrupt, Surface}; use crate::ora::Warnings; use crate::{ImportResult, IoError}; -type Result = std::result::Result; +#[cfg(test)] +use craft_xcf::{MAX_PIXEL_BYTES, MAX_SIDE}; +pub(crate) use craft_xcf::{is_gzipped_xcf, is_xcf}; -const MAGIC: &[u8] = b"gimp xcf "; -/// Canvas side limit (Photoshop's PSB limit). -pub(crate) const MAX_SIDE: u32 = 300_000; -/// Decoded pixels across every drawable are capped, as for OpenRaster and PDN. -pub(crate) const MAX_PIXEL_BYTES: usize = 1 << 30; -/// Layers and groups in one document. -pub(crate) const MAX_LAYERS: usize = 8192; -/// Extra channels in one document. -const MAX_CHANNELS: usize = 1024; -/// Group nesting. -const MAX_DEPTH: usize = 64; -/// Total copied layer metadata (names and item paths). A single reused record with a large -/// name is bounded by MAX_STRING, but repeated layer offsets referencing it must not multiply -/// into unbounded retained metadata. -const MAX_METADATA_BYTES: usize = 32 << 20; -/// A string field (layer names, parasite names). -const MAX_STRING: usize = 1 << 20; -/// A property payload or a parasite that is read into memory. -const MAX_PAYLOAD: usize = 64 << 20; -/// The largest file a gzipped XCF may inflate to. -const MAX_INFLATED: usize = 1 << 30; -/// Highest version this reader was written against; newer files still open (unknown properties -/// are skipped by their length), with a warning. -const KNOWN_VERSION: u32 = 26; -const TILE: u32 = 64; +type Result = std::result::Result; fn invalid(message: impl Into) -> IoError { IoError::Xcf(message.into()) } -/// `true` for an XCF file (by its signature). -pub(crate) fn is_xcf(bytes: &[u8]) -> bool { - bytes.starts_with(MAGIC) -} - -/// `true` for a gzip stream named `.xcf.gz` / `.xcfgz` (GIMP writes and reads compressed XCF). -pub(crate) fn is_gzipped_xcf(name: &str, bytes: &[u8]) -> bool { - let lower = name.rsplit(['/', '\\']).next().unwrap_or(name).to_ascii_lowercase(); - bytes.starts_with(&[0x1f, 0x8b]) && (lower.ends_with(".xcf.gz") || lower.ends_with(".xcfgz")) +/// The format crate's error as this crate's. +fn xcf_err(e: craft_xcf::Error) -> IoError { + match e { + craft_xcf::Error::Invalid(m) => invalid(m), + craft_xcf::Error::Cancelled => IoError::Cancelled, + } } /// Inflates a gzipped XCF, bounded. pub(crate) fn gunzip(bytes: &[u8]) -> Result> { - let mut out = Vec::new(); - let mut dec = flate2::read::GzDecoder::new(bytes).take(MAX_INFLATED as u64 + 1); - dec.read_to_end(&mut out).map_err(|e| invalid(format!("gzip: {e}")))?; - if out.len() > MAX_INFLATED { - return Err(invalid("the compressed file inflates past the 1 GiB limit")); - } - Ok(out) + craft_xcf::gunzip(bytes).map_err(xcf_err) } -/// How samples are stored: bytes per sample, whether they are floats, and whether the values are -/// linear light (else gamma-encoded, i.e. the profile's own curve). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct Precision { - bytes: usize, - float: bool, - linear: bool, -} - -impl Precision { - const GAMMA8: Precision = Precision { bytes: 1, float: false, linear: false }; - - fn from_header(version: u32, code: u32) -> Result { - let p = |bytes, float, linear| Ok(Precision { bytes, float, linear }); - match version { - 0..=3 => Ok(Self::GAMMA8), - 4 => match code { - 0 => p(1, false, false), - 1 => p(2, false, false), - 2 => p(4, false, true), - 3 => p(2, true, true), - 4 => p(4, true, true), - c => Err(invalid(format!("unknown precision {c} in an XCF version 4 file"))), - }, - 5 | 6 => match code { - 100 => p(1, false, true), - 150 => p(1, false, false), - 200 => p(2, false, true), - 250 => p(2, false, false), - 300 => p(4, false, true), - 350 => p(4, false, false), - 400 => p(2, true, true), - 450 => p(2, true, false), - 500 => p(4, true, true), - 550 => p(4, true, false), - c => Err(invalid(format!("unknown precision {c} in an XCF version {version} file"))), - }, - _ => match code { - 100 => p(1, false, true), - 150 => p(1, false, false), - 200 => p(2, false, true), - 250 => p(2, false, false), - 300 => p(4, false, true), - 350 => p(4, false, false), - 500 => p(2, true, true), - 550 => p(2, true, false), - 600 => p(4, true, true), - 650 => p(4, true, false), - 700 => p(8, true, true), - 750 => p(8, true, false), - c => Err(invalid(format!("unknown precision {c}"))), - }, - } - } - - /// The document depth the samples open at. - fn depth(self) -> SampleType { - match (self.float, self.bytes) { - (false, 1) => SampleType::U8, - (false, _) => SampleType::U16, - (true, _) => SampleType::F32, - } - } - - /// One sample, big-endian, as a normalised float. - fn sample(self, b: &[u8]) -> f32 { - match (self.float, self.bytes, b) { - (false, 1, [v]) => f32::from(*v) / 255.0, - (false, 2, [a, b]) => f32::from(u16::from_be_bytes([*a, *b])) / 65535.0, - (false, 4, [a, b, c, d]) => (u32::from_be_bytes([*a, *b, *c, *d]) as f64 / f64::from(u32::MAX)) as f32, - (true, 2, [a, b]) => f16::from_bits(u16::from_be_bytes([*a, *b])).to_f32(), - (true, 4, [a, b, c, d]) => f32::from_be_bytes([*a, *b, *c, *d]), - (true, 8, [a, b, c, d, e, f, g, h]) => f64::from_be_bytes([*a, *b, *c, *d, *e, *f, *g, *h]) as f32, - _ => 0.0, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Compression { - None, - Rle, - Zlib, -} - -/// Big-endian reads with bounds checks; every failure is an error, never a panic. -struct Cursor<'a> { - b: &'a [u8], - pos: usize, - /// XCF 11 and later store pointers as 64-bit. - wide: bool, -} - -impl<'a> Cursor<'a> { - fn at(&self, pos: usize) -> Cursor<'a> { - Cursor { b: self.b, pos, wide: self.wide } - } - - fn take(&mut self, n: usize) -> Result<&'a [u8]> { - let end = self.pos.checked_add(n).ok_or_else(|| invalid("offset overflow"))?; - let s = self.b.get(self.pos..end).ok_or_else(|| invalid(format!("the file ends early (wanted {n} bytes at {})", self.pos)))?; - self.pos = end; - Ok(s) - } - - fn u32(&mut self) -> Result { - let s = self.take(4)?; - Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]])) - } - - fn ptr(&mut self) -> Result { - if self.wide { - let s = self.take(8)?; - usize::try_from(u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])).map_err(|_| invalid("pointer does not fit in memory")) - } else { - self.u32().map(|v| v as usize) - } - } - - /// A STRING: `n+1` then `n` bytes and a NUL (0 for the empty string). - fn string(&mut self) -> Result { - Ok(String::from_utf8_lossy(self.string_bytes()?).into_owned()) - } - - /// The same bounded STRING read without allocating or decoding an unused field. - fn string_bytes(&mut self) -> Result<&'a [u8]> { - let n = self.u32()? as usize; - if n > MAX_STRING { - return Err(invalid(format!("a string of {n} bytes exceeds the limit"))); - } - let s = self.take(n)?; - Ok(s.strip_suffix(&[0]).unwrap_or(s)) - } - - fn skip(&mut self, n: usize) -> Result<()> { - self.take(n).map(|_| ()) - } -} - -/// One property record: its type and payload. -struct Prop<'a> { - kind: u32, - data: &'a [u8], -} - -/// Reads a property list, measuring known payloads whose length words GIMP writes incorrectly. -/// Ends at PROP_END (type 0). -fn props<'a>(c: &mut Cursor<'a>) -> Result>> { - let mut out = Vec::new(); - loop { - let kind = c.u32()?; - let len = c.u32()? as usize; - if kind == 0 { - return Ok(out); - } - // PROP_COLORMAP's length word was wrong in some releases (n+4 for 3n+4 bytes); its real - // size follows from the count. PROP_USER_UNIT's length is wrong in every release. - // PROP_LINK_LAYER's length can be four bytes short (#8857); read all its fields. - let len = match kind { - 1 => { - let n = c.at(c.pos).u32()? as usize; - 4usize.checked_add(n.checked_mul(3).ok_or_else(|| invalid("colormap overflow"))?).ok_or_else(|| invalid("colormap overflow"))? - } - 24 => user_unit_len(c)?, - 48 => link_layer_len(c)?, - _ => len, - }; - if len > MAX_PAYLOAD { - return Err(invalid(format!("property {kind} declares {len} bytes"))); - } - let data = c.take(len)?; - out.push(Prop { kind, data }); - if out.len() > 4096 { - return Err(invalid("too many properties")); - } - } -} - -/// A PROP_LINK_LAYER payload: flags, a path STRING, then the source width and height. -/// The dimensions are present for raster links too, where their values are unused. -fn link_layer_len(c: &Cursor<'_>) -> Result { - let mut p = c.at(c.pos); - p.skip(4)?; - p.string_bytes()?; - p.skip(8)?; - Ok(p.pos - c.pos) -} - -/// The real size of a PROP_USER_UNIT payload: a float, a count and three (XCF 21+) or five -/// strings. Measured without consuming. -fn user_unit_len(c: &Cursor<'_>) -> Result { - let mut p = c.at(c.pos); - p.skip(8)?; - for _ in 0..3 { - p.string()?; - } - // The two name forms of older files, when present: another string pair before the next - // property. Decide by whether a plausible property header follows. - let three = p.pos - c.pos; - let mut q = p.at(p.pos); - let looks_like_prop = |c: &mut Cursor<'_>| c.u32().map(|k| k <= 64).unwrap_or(false); - if looks_like_prop(&mut q) { - return Ok(three); - } - p.string()?; - p.string()?; - Ok(p.pos - c.pos) -} - -fn be_u32(b: &[u8]) -> Option { - b.get(..4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])) -} - -fn be_i32(b: &[u8]) -> Option { - be_u32(b).map(|v| v as i32) -} - -fn be_f32(b: &[u8]) -> Option { - be_u32(b).map(f32::from_bits) -} - -/// The parasites of a PROP_PARASITES payload as (name, data); a later duplicate wins. -fn parasites(data: &[u8]) -> Vec<(String, Vec)> { - let mut c = Cursor { b: data, pos: 0, wide: false }; - let mut out: Vec<(String, Vec)> = Vec::new(); - // Map each name to its output slot so duplicate replacement is O(1). The parasite - // records are file-controlled, so scanning `out` with iter_mut().find() per record is - // O(n^2) and lets a crafted payload with many distinct names stall import. The map - // preserves insertion order and last-value-wins behavior. - let mut index: HashMap = HashMap::new(); - while c.pos < data.len() { - let Ok(name) = c.string() else { break }; - let (Ok(_flags), Ok(len)) = (c.u32(), c.u32()) else { break }; - let Ok(payload) = c.take(len as usize) else { break }; - match index.get(&name) { - Some(&i) => out[i].1 = payload.to_vec(), - None => { - index.insert(name.clone(), out.len()); - out.push((name, payload.to_vec())); - } - } - } - out -} - -/// What one tile's bytes decode to, for a drawable of `bpp` bytes per pixel. -fn decode_tile(c: &Cursor<'_>, at: usize, end: usize, compression: Compression, bpp: usize, pixels: usize) -> Result> { - let expected = pixels.checked_mul(bpp).ok_or_else(|| invalid("tile size overflow"))?; - let input = c.b.get(at..end.min(c.b.len())).ok_or_else(|| invalid("a tile pointer is outside the file"))?; - match compression { - Compression::None => input.get(..expected).map(<[u8]>::to_vec).ok_or_else(|| invalid("an uncompressed tile is cut short")), - Compression::Zlib => { - let mut out = Vec::with_capacity(expected); - flate2::read::ZlibDecoder::new(input).take(expected as u64).read_to_end(&mut out).map_err(|e| invalid(format!("zlib tile: {e}")))?; - if out.len() != expected { - return Err(invalid("a zlib tile is cut short")); - } - Ok(out) - } - Compression::Rle => rle_decode(input, bpp, pixels), - } -} - -/// RLE tile data: one run-length stream per byte position of the pixel, each of `pixels` bytes. -fn rle_decode(input: &[u8], bpp: usize, pixels: usize) -> Result> { - let mut out = vec![0u8; pixels * bpp]; - let mut pos = 0usize; - let mut plane = Vec::with_capacity(pixels); - for b in 0..bpp { - plane.clear(); - while plane.len() < pixels { - let op = *input.get(pos).ok_or_else(|| invalid("an RLE tile is cut short"))?; - pos += 1; - let (run, verbatim) = match op { - 0..=126 => (usize::from(op) + 1, false), - 127 => { - let (p, q) = (input.get(pos).copied(), input.get(pos + 1).copied()); - pos += 2; - ( - usize::from(p.ok_or_else(|| invalid("an RLE tile is cut short"))?) * 256 - + usize::from(q.ok_or_else(|| invalid("an RLE tile is cut short"))?), - false, - ) - } - 128 => { - let (p, q) = (input.get(pos).copied(), input.get(pos + 1).copied()); - pos += 2; - ( - usize::from(p.ok_or_else(|| invalid("an RLE tile is cut short"))?) * 256 - + usize::from(q.ok_or_else(|| invalid("an RLE tile is cut short"))?), - true, - ) - } - _ => (256 - usize::from(op), true), - }; - if plane.len() + run > pixels { - return Err(invalid("an RLE run crosses the end of its tile")); - } - if verbatim { - let data = input.get(pos..pos + run).ok_or_else(|| invalid("an RLE tile is cut short"))?; - pos += run; - plane.extend_from_slice(data); - } else { - let v = *input.get(pos).ok_or_else(|| invalid("an RLE tile is cut short"))?; - pos += 1; - plane.resize(plane.len() + run, v); - } - } - for (i, v) in plane.iter().enumerate() { - out[i * bpp + b] = *v; - } - } - Ok(out) -} - -/// Image-wide facts the drawables need. -struct Image<'a> { - c: Cursor<'a>, - version: u32, - precision: Precision, - compression: Compression, - base_type: u32, - colormap: Vec<[u8; 3]>, - budget: usize, - /// Remaining allowance for copied layer metadata (names, item paths). Repeated layer - /// offsets referencing one record with a large name would otherwise allocate an owned - /// copy per reference, multiplying a small file into gigabytes of retained metadata. - meta_budget: usize, - warnings: Warnings, - /// Layers GIMP composites with "Clip to backdrop" (its default for every mode but Normal). - clipped_to_backdrop: usize, -} - -/// Pixel data of a drawable: `channels` normalised samples per pixel, row-major. -struct Pixels { - width: u32, - height: u32, - channels: usize, - data: Vec, -} - -impl<'a> Image<'a> { - /// Reads a hierarchy (`hptr`): the first level's tiles into `channels` floats per pixel, - /// `source_channels` as stored (indexed images expand to RGB here). - fn hierarchy(&mut self, hptr: usize, source_channels: usize, ctl: &Interrupt<'_>) -> Result { - let mut c = self.c.at(hptr); - let (w, h, bpp) = (c.u32()?, c.u32()?, c.u32()? as usize); - if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { - return Err(invalid(format!("drawable size {w}x{h} is out of range"))); - } - let expected_bpp = source_channels.checked_mul(self.precision.bytes).ok_or_else(|| invalid("bpp overflow"))?; - if bpp != expected_bpp { - return Err(invalid(format!("{bpp} bytes per pixel where {expected_bpp} were expected"))); - } - let indexed = self.base_type == 2; - let channels = if indexed { source_channels + 2 } else { source_channels }; - let count = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(channels)).ok_or_else(|| invalid("drawable overflow"))?; - let bytes = count.checked_mul(4).ok_or_else(|| invalid("drawable overflow"))?; - self.budget = self.budget.checked_sub(bytes).ok_or_else(|| invalid("the layers exceed the 1 GiB pixel limit"))?; - let lptr = c.ptr()?; - let mut l = self.c.at(lptr); - let (lw, lh) = (l.u32()?, l.u32()?); - if (lw, lh) != (w, h) { - return Err(invalid("the level does not match its hierarchy")); - } - let across = w.div_ceil(TILE) as usize; - let down = h.div_ceil(TILE) as usize; - let mut tiles = Vec::with_capacity(across * down); - for _ in 0..across * down { - let p = l.ptr()?; - if p == 0 { - return Err(invalid("the tile list ends before every tile")); - } - tiles.push(p); - } - let mut data = vec![0.0f32; count]; - let stride = w as usize * channels; - for (i, &at) in tiles.iter().enumerate() { - if i % 64 == 0 { - ctl.check().map_err(|_| IoError::Cancelled)?; - } - let (tx, ty) = ((i % across) as u32, (i / across) as u32); - let (tw, th) = ((w - tx * TILE).min(TILE), (h - ty * TILE).min(TILE)); - let end = tiles.get(i + 1).copied().filter(|&n| n > at).unwrap_or(self.c.b.len()); - let raw = decode_tile(&self.c, at, end, self.compression, bpp, (tw * th) as usize)?; - for py in 0..th as usize { - for px in 0..tw as usize { - let src = (py * tw as usize + px) * bpp; - let dst = (ty as usize * TILE as usize + py) * stride + (tx as usize * TILE as usize + px) * channels; - let pixel = &raw[src..src + bpp]; - if indexed { - let idx = usize::from(pixel[0]); - let [r, g, b] = self.colormap.get(idx).copied().unwrap_or([pixel[0]; 3]); - data[dst] = f32::from(r) / 255.0; - data[dst + 1] = f32::from(g) / 255.0; - data[dst + 2] = f32::from(b) / 255.0; - if source_channels == 2 { - data[dst + 3] = f32::from(pixel[1]) / 255.0; - } - } else { - for ch in 0..channels { - data[dst + ch] = self.precision.sample(&pixel[ch * self.precision.bytes..(ch + 1) * self.precision.bytes]); - } - } - } - } - } - Ok(Pixels { width: w, height: h, channels, data }) - } - - /// A channel structure (a layer mask, the selection or an extra channel) as one-channel - /// pixels, with its properties. - fn channel(&mut self, ptr: usize, ctl: &Interrupt<'_>) -> Result<(String, Vec>, Pixels)> { - let mut c = self.c.at(ptr); - let (_w, _h) = (c.u32()?, c.u32()?); - let name = c.string()?; - let props = props(&mut c)?; - let hptr = c.ptr()?; - let saved = (self.base_type, self.precision); - // Channels are always one plain sample per pixel, even in indexed images. - self.base_type = 0; - let px = self.hierarchy(hptr, 1, ctl); - (self.base_type, self.precision) = saved; - Ok((name, props, px?)) +/// The document depth the samples open at. +fn depth(p: Precision) -> SampleType { + match (p.float, p.bytes) { + (false, 1) => SampleType::U8, + (false, _) => SampleType::U16, + (true, _) => SampleType::F32, } } /// A layer as read, before the tree is built. struct Node { layer: Layer, - path: Vec, group: bool, - children: Vec, } /// GIMP's layer mode as Photoshop's, with a note when the two differ. @@ -604,301 +151,160 @@ fn write_pixels(surface: &mut Surface, px: &Pixels, x: i32, y: i32, budget: &mut Ok(()) } -struct ImageMetadata { - compression: Compression, - colormap: Vec<[u8; 3]>, - resolution: Option<(f32, f32)>, - guides: Vec<(i32, u8)>, - icc: Option>, - comment: Option, - path_count: usize, -} - -fn read_image_metadata(c: &mut Cursor<'_>) -> Result { - // Image properties. - let image_props = props(c)?; - let mut compression = Compression::None; - let mut colormap = Vec::new(); - let mut resolution = None; - let mut guides: Vec<(i32, u8)> = Vec::new(); - let mut icc = None; - let mut comment = None; - let mut path_count = 0usize; - for p in &image_props { - match p.kind { - 1 => { - let n = be_u32(p.data).unwrap_or(0) as usize; - colormap = p.data.get(4..).unwrap_or(&[]).as_chunks::<3>().0.iter().take(n.min(256)).copied().collect(); - } - 17 => { - compression = match p.data.first() { - Some(0) => Compression::None, - Some(1) => Compression::Rle, - Some(2) => Compression::Zlib, - Some(k) => return Err(invalid(format!("unknown compression {k}"))), - None => return Err(invalid("empty compression property")), - } - } - 18 => { - for g in p.data.as_chunks::<5>().0 { - guides.push((i32::from_be_bytes([g[0], g[1], g[2], g[3]]), g[4])); - } - } - 19 => { - if let (Some(x), Some(y)) = (be_f32(p.data), p.data.get(4..).and_then(be_f32)) { - resolution = Some((x, y)); - } - } - 21 => { - for (name, data) in parasites(p.data) { - match name.as_str() { - "icc-profile" if !data.is_empty() => icc = Some(data), - "gimp-comment" => comment = Some(String::from_utf8_lossy(&data).trim_end_matches('\0').to_string()), - _ => {} - } - } - } - 23 => path_count += be_u32(p.data.get(4..).unwrap_or(&[])).unwrap_or(0) as usize, - 25 => path_count += be_u32(p.data.get(8..).unwrap_or(&[])).unwrap_or(0) as usize, - _ => {} - } - } - - Ok(ImageMetadata { compression, colormap, resolution, guides, icc, comment, path_count }) -} - /// Imports an XCF file (already inflated when it was gzipped). pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result { - if !is_xcf(bytes) { - return Err(invalid("not an XCF file")); - } - let mut c = Cursor { b: bytes, pos: MAGIC.len(), wide: false }; - let tag = c.take(5)?; - let version = match tag { - b"file\0" => 0, - [b'v', a, b, d, 0] if a.is_ascii_digit() && b.is_ascii_digit() && d.is_ascii_digit() => { - u32::from(a - b'0') * 100 + u32::from(b - b'0') * 10 + u32::from(d - b'0') - } - _ => return Err(invalid("unknown XCF version tag")), - }; - c.wide = version >= 11; + let xcf = Xcf::parse(bytes).map_err(xcf_err)?; + let info = xcf.image(); + let version = info.version; let mut warnings = Warnings::default(); - if version > KNOWN_VERSION { - warnings.note(&format!("XCF version {version} is newer than this reader (version {KNOWN_VERSION}); unknown parts were skipped")); + if version > craft_xcf::KNOWN_VERSION { + warnings.note(&format!("XCF version {version} is newer than this reader (version {}); unknown parts were skipped", craft_xcf::KNOWN_VERSION)); } - let (w, h, base_type) = (c.u32()?, c.u32()?, c.u32()?); - if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { - return Err(invalid(format!("canvas {w}x{h} must be 1 to {MAX_SIDE} pixels a side"))); - } - if (w as usize).saturating_mul(h as usize).saturating_mul(16) > MAX_PIXEL_BYTES { - return Err(invalid("the canvas exceeds the 1 GiB pixel limit")); - } - let precision = if version >= 4 { Precision::from_header(version, c.u32()?)? } else { Precision::GAMMA8 }; - let mode = match base_type { - 0 => ColorMode::Rgb, - 1 => ColorMode::Grayscale, - 2 => ColorMode::Rgb, - t => return Err(invalid(format!("unknown image type {t}"))), + let mode = match info.base_type { + BaseType::Gray => ColorMode::Grayscale, + BaseType::Rgb | BaseType::Indexed => ColorMode::Rgb, }; - let depth = precision.depth(); - if base_type == 2 { + let precision = info.precision; + let depth = depth(precision); + if info.base_type == BaseType::Indexed { warnings.note("the indexed image opens as RGB"); } if !precision.float && precision.bytes == 4 { warnings.note("32-bit integer samples open as 16-bit"); } - let ImageMetadata { compression, colormap, resolution, guides, icc, comment, mut path_count } = read_image_metadata(&mut c)?; - - let mut layer_ptrs = Vec::new(); - loop { - let p = c.ptr()?; - if p == 0 { - break; - } - layer_ptrs.push(p); - if layer_ptrs.len() > MAX_LAYERS { - return Err(invalid(format!("more than {MAX_LAYERS} layers"))); - } - } - let mut channel_ptrs = Vec::new(); - loop { - let p = c.ptr()?; - if p == 0 { - break; - } - channel_ptrs.push(p); - if channel_ptrs.len() > MAX_CHANNELS { - return Err(invalid(format!("more than {MAX_CHANNELS} channels"))); - } - } - if version >= 18 { - let mut n = 0; - while c.ptr().ok().is_some_and(|p| p != 0) { - n += 1; - if n > MAX_CHANNELS { - break; - } - } - path_count += n; - } - - let mut image = Image { - c: c.at(0), - version, - precision, - compression, - base_type, - colormap, - budget: MAX_PIXEL_BYTES, - meta_budget: MAX_METADATA_BYTES, - warnings, - clipped_to_backdrop: 0, - }; + let mut reader = Reader { xcf: &xcf, ctl, budget: craft_xcf::MAX_PIXEL_BYTES, warnings, clipped_to_backdrop: 0 }; let fmt = PixelFormat::new(mode, depth, true); let mask_fmt = PixelFormat::new(ColorMode::Grayscale, depth, false); - let total = layer_ptrs.len().max(1) as f32; + let total = info.layers.len().max(1) as f32; // Layers, topmost first in the file. - let mut nodes: Vec = Vec::new(); + let mut nodes: Vec> = Vec::with_capacity(info.layers.len()); let mut linear_compositing = false; - for (i, &ptr) in layer_ptrs.iter().enumerate() { + for i in 0..info.layers.len() { ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(0.05 + 0.85 * i as f32 / total); - if let Some((node, linear)) = image.layer(ptr, fmt, mask_fmt, ctl)? { - linear_compositing |= linear; - nodes.push(node); + match reader.layer(i, fmt, mask_fmt)? { + Some((node, linear)) => { + linear_compositing |= linear; + nodes.push(Some(node)); + } + None => nodes.push(None), } } - let mut roots: Vec = Vec::new(); - for (i, mut node) in nodes.into_iter().enumerate() { - // Default path: the item's position at the top level, as a file without groups has it. - if node.path.is_empty() { - node.path = vec![i as u32]; + let tree = info.tree(); + for &i in &tree.too_deep { + if let Some(l) = info.layers.get(i) { + reader.warnings.layer(&l.name, "is nested deeper than the reader allows and was moved to the top level"); } - if node.path.len() > MAX_DEPTH { - image.warnings.layer(&node.layer.name, "is nested deeper than the reader allows and was moved to the top level"); - node.path.truncate(1); - } - place(&mut roots, node, &mut image.warnings); } - let layers = finish(roots); + for &i in &tree.misplaced { + if let Some(l) = info.layers.get(i) { + reader.warnings.layer(&l.name, "has an item path that leads to no group; opened at the top level"); + } + } + let layers = finish(&tree.roots, &mut nodes); // Channels: the selection and the extras. let mut channels = Vec::new(); let mut selection = None; - for &ptr in &channel_ptrs { + let keep_going = || ctl.check().is_ok(); + for i in 0..info.channel_count { ctl.check().map_err(|_| IoError::Cancelled)?; - let (name, cprops, px) = image.channel(ptr, ctl)?; + let (channel, px) = xcf.channel(i, &mut reader.budget, &keep_going).map_err(xcf_err)?; let mut surface = Surface::new(mask_fmt); - write_pixels(&mut surface, &px, 0, 0, &mut image.budget)?; - if cprops.iter().any(|p| p.kind == 4) { + write_pixels(&mut surface, &px, 0, 0, &mut reader.budget)?; + if channel.selection { selection = Some(surface); } else { - channels.push(AlphaChannel::new(name, surface)); + channels.push(AlphaChannel::new(channel.name, surface)); } } - let mut document = Document::new(name, Size::new(w, h), mode, depth); + let mut document = Document::new(name, Size::new(info.width, info.height), mode, depth); document.layers = layers; document.channels = channels; document.selection = selection; - if let Some((x, y)) = resolution.filter(|(x, _)| *x > 0.0 && *x < 1.0e6) { + if let Some((x, y)) = info.resolution.filter(|(x, _)| *x > 0.0 && *x < 1.0e6) { document.resolution_dpi = x; if let Some(w) = crate::unequal_resolution_warning(f64::from(x), f64::from(y)) { - image.warnings.note(&w); + reader.warnings.note(&w); } } - for (coord, orientation) in guides { - if coord < 0 && version < 15 { - continue; - } - match orientation { - 1 => document.guides.horizontal.push(f64::from(coord)), - 2 => document.guides.vertical.push(f64::from(coord)), - _ => {} + for guide in &info.guides { + match guide.orientation { + Orientation::Horizontal => document.guides.horizontal.push(f64::from(guide.position)), + Orientation::Vertical => document.guides.vertical.push(f64::from(guide.position)), } } - document.icc_profile = match (precision.linear, icc, mode) { + document.icc_profile = match (precision.linear, info.icc_profile.clone(), mode) { (true, icc, ColorMode::Grayscale) => { if icc.is_some() { - image.warnings.note("the linear-light image's own profile was replaced by linear gray"); + reader.warnings.note("the linear-light image's own profile was replaced by linear gray"); } Some(photocraft_cms::builtin::linear_gray().to_bytes()) } (true, icc, _) => { if icc.is_some() { - image.warnings.note("the linear-light image's own profile was replaced by linear sRGB"); + reader.warnings.note("the linear-light image's own profile was replaced by linear sRGB"); } Some(photocraft_cms::Builtin::LinearSrgb.profile().to_bytes()) } (false, Some(icc), _) => Some(Arc::new(icc)), (false, None, _) => None, }; - if let Some(comment) = comment.filter(|c| !c.is_empty()) { + if let Some(comment) = info.comment.clone().filter(|c| !c.is_empty()) { document.metadata.text.push(("Comment".into(), comment)); } - if path_count > 0 { - image.warnings.note(&format!("{path_count} path(s) were not imported")); + if info.path_count > 0 { + reader.warnings.note(&format!("{} path(s) were not imported", info.path_count)); } - add_document_warnings(&mut image, &document, precision, linear_compositing); + add_document_warnings(&mut reader, &document, precision, linear_compositing); ctl.progress(1.0); - Ok(ImportResult { document, warnings: image.warnings.finish(), source_read_only: true, preview_only: false }) + Ok(ImportResult { document, warnings: reader.warnings.finish(), source_read_only: true, preview_only: false }) } -fn add_document_warnings(image: &mut Image<'_>, document: &Document, precision: Precision, linear_compositing: bool) { +/// What the layers need while they are read. +struct Reader<'x, 'a, 'c> { + xcf: &'x Xcf<'a>, + ctl: &'c Interrupt<'c>, + budget: usize, + warnings: Warnings, + /// Layers GIMP composites with "Clip to backdrop" (its default for every mode but Normal). + clipped_to_backdrop: usize, +} + +fn add_document_warnings(reader: &mut Reader<'_, '_, '_>, document: &Document, precision: Precision, linear_compositing: bool) { // GIMP clips a layer in any mode but Normal to the layers beneath it, so it shows nothing where // they are transparent; PhotoCraft (like Photoshop) shows it there. Only tell when there is // transparency to show through: a bottom layer that is not opaque. - if image.clipped_to_backdrop > 0 && document.layers.first().is_some_and(|l| !l.locks.transparency || l.is_group()) { - image.warnings.note(&format!( + if reader.clipped_to_backdrop > 0 && document.layers.first().is_some_and(|l| !l.locks.transparency || l.is_group()) { + reader.warnings.note(&format!( "{} layer(s) use a mode GIMP clips to the layers beneath; where those are transparent GIMP shows nothing and PhotoCraft shows the layer", - image.clipped_to_backdrop + reader.clipped_to_backdrop )); } // GIMP blends and composites in linear light by default (since 2.10); PhotoCraft, like // Photoshop, in the document's own encoding, so semi-transparent edges and most blend modes // render a little differently. Layers set to a perceptual space in GIMP match. if !precision.linear && linear_compositing { - image.warnings.note("GIMP composites this image in linear light; PhotoCraft composites in gamma-encoded RGB, so blends and soft edges differ slightly"); + reader + .warnings + .note("GIMP composites this image in linear light; PhotoCraft composites in gamma-encoded RGB, so blends and soft edges differ slightly"); } if document.layers.is_empty() { - image.warnings.note("the XCF file has no layers"); + reader.warnings.note("the XCF file has no layers"); } } -/// Puts `node` where its item path says, under the groups already placed; a path that leads -/// nowhere (at any depth) puts it at the top level, so later siblings keep their indices. -fn place(roots: &mut Vec, node: Node, warnings: &mut Warnings) { - let depth = node.path.len().saturating_sub(1); - let mut probe: &Vec = roots; - let reachable = node.path.iter().take(depth).all(|&index| match probe.get(index as usize) { - Some(n) if n.group => { - probe = &n.children; - true - } - _ => false, - }); - if !reachable { - warnings.layer(&node.layer.name, "has an item path that leads to no group; opened at the top level"); - let mut node = node; - node.path = vec![]; - roots.push(node); - return; - } - let mut level = roots; - for &index in node.path.iter().take(depth) { - level = &mut level[index as usize].children; - } - level.push(node); -} - -/// Nodes top-first into layers bottom-first, groups recursively. -fn finish(nodes: Vec) -> Vec { - let mut out = Vec::with_capacity(nodes.len()); - for mut node in nodes.into_iter().rev() { +/// The tree's nodes (top-first) into layers bottom-first, groups recursively. Each layer is +/// taken out of `nodes` once. +fn finish(tree: &[TreeNode], nodes: &mut [Option]) -> Vec { + let mut out = Vec::with_capacity(tree.len()); + for t in tree.iter().rev() { + let Some(mut node) = nodes.get_mut(t.layer).and_then(Option::take) else { continue }; if node.group { - let children = finish(std::mem::take(&mut node.children)); + let children = finish(&t.children, nodes); if let Some(c) = node.layer.children_mut() { *c = children; } @@ -908,107 +314,17 @@ fn finish(nodes: Vec) -> Vec { out } -impl<'a> Image<'a> { - /// Reads a layer structure, and whether GIMP composites it in linear light. `None` for a - /// floating selection, which is reported instead. - fn layer(&mut self, ptr: usize, fmt: PixelFormat, mask_fmt: PixelFormat, ctl: &Interrupt<'_>) -> Result> { - let mut c = self.c.at(ptr); - let (lw, lh, kind) = (c.u32()?, c.u32()?, c.u32()?); - let name = c.string()?; - // Charge the owned name against the document-wide metadata budget: repeated layer - // offsets referencing one large name must not retain unbounded copies. - self.meta_budget = self.meta_budget.checked_sub(name.len()).ok_or_else(|| invalid("layer metadata exceeds the budget"))?; - let lprops = props(&mut c)?; - let hptr = c.ptr()?; - let mptr = c.ptr()?; - let mut effects = 0usize; - if self.version >= 20 { - while c.ptr()? != 0 { - effects += 1; - if effects > 1024 { - return Err(invalid("too many layer effects")); - } - } - } - let (type_rgb, alpha) = match kind { - 0 => (true, false), - 1 => (true, true), - 2 | 4 => (false, false), - 3 | 5 => (false, true), - k => return Err(invalid(format!("unknown layer type {k} on '{name}'"))), - }; - if type_rgb != (self.base_type != 1) && self.base_type != 2 { - return Err(invalid(format!("layer '{name}' does not match the image's colour model"))); - } - - let mut layer_mode = 0u32; - let mut opacity = 1.0f32; - // PROP_FLOAT_OPACITY wins over PROP_OPACITY whatever their order in the file. - let mut float_opacity = None; - let mut visible = true; - let (mut x, mut y) = (0i32, 0i32); - let mut apply_mask = true; - let mut group = false; - let mut expanded = true; - let mut path = Vec::new(); - let mut text = false; - let mut vector = false; - let mut link = false; - let mut floating = false; - let mut clipped = false; - let mut composite_mode = 0i32; - let mut composite_space = 0i32; - let mut blend_space = 0i32; - let mut locks = photocraft_doc::Locks::default(); - let mut tag = LabelColor::None; - for p in &lprops { - let v = be_u32(p.data).unwrap_or(0); - match p.kind { - 5 => floating = true, - 6 => opacity = (v.min(255) as f32) / 255.0, - 33 => float_opacity = be_f32(p.data).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0)).or(float_opacity), - 7 => layer_mode = v, - 8 => visible = v != 0, - 10 => locks.transparency = v != 0, - 11 => apply_mask = v != 0, - 15 => { - x = be_i32(p.data).unwrap_or(0); - y = p.data.get(4..).and_then(be_i32).unwrap_or(0); - } - 26 => text = true, - 28 => locks.pixels = v != 0, - 29 => group = true, - 30 => { - path = p.data.as_chunks::<4>().0.iter().map(|s| u32::from_be_bytes(*s)).collect(); - self.meta_budget = - self.meta_budget.checked_sub(path.len().saturating_mul(4)).ok_or_else(|| invalid("layer metadata exceeds the budget"))?; - } - 31 => expanded = v & 1 != 0, - 32 => locks.position = v != 0, - 34 => tag = label(v), - 35 => composite_mode = be_i32(p.data).unwrap_or(0), - 36 => composite_space = be_i32(p.data).unwrap_or(0), - 37 => blend_space = be_i32(p.data).unwrap_or(0), - 47 => vector = true, - 48 => link = true, - 21 => { - for (pname, _) in parasites(p.data) { - match pname.as_str() { - "gimphoto-clipped" => clipped = true, - "gimp-text-layer" => text = true, - _ => {} - } - } - } - _ => {} - } - } - if floating { +impl Reader<'_, '_, '_> { + /// Layer `index`, and whether GIMP composites it in linear light. `None` for a floating + /// selection, which is reported instead. + fn layer(&mut self, index: usize, fmt: PixelFormat, mask_fmt: PixelFormat) -> Result> { + let Some(l) = self.xcf.image().layers.get(index) else { return Ok(None) }; + let name = l.name.clone(); + if l.floating_selection { self.warnings.layer(&name, "is a floating selection and was not imported (anchor it in GIMP first)"); return Ok(None); } - - let (blend, note) = blend_mode(layer_mode); + let (blend, note) = blend_mode(l.mode); if let Some(note) = note { self.warnings.layer( &name, @@ -1018,57 +334,50 @@ impl<'a> Image<'a> { ), ); } - match composite_mode.unsigned_abs() { + match l.composite_mode.unsigned_abs() { 0 | 1 => {} 2 => self.clipped_to_backdrop += 1, 3 => self.warnings.layer(&name, "composites with Clip to layer, which is not reproduced"), 4 => self.warnings.layer(&name, "composites with Intersection, which is not reproduced"), _ => {} } - if text { + if l.text { self.warnings.layer(&name, "is a text layer and opens as pixels"); } - if vector { + if l.vector { self.warnings.layer(&name, "is a vector layer and opens as pixels"); } - if link { + if l.link { self.warnings.layer(&name, "is a link layer and opens as pixels"); } - if effects > 0 { - self.warnings.layer(&name, &format!("has {effects} layer effect(s) (non-destructive filters) that are not applied")); + if l.effects > 0 { + self.warnings.layer(&name, &format!("has {} layer effect(s) (non-destructive filters) that are not applied", l.effects)); } - let mut layer = if group { + let mut layer = if l.group { let mut g = Layer::group(name.clone(), Vec::new()); if let LayerContent::Group(gr) = &mut g.content { - gr.expanded = expanded; + gr.expanded = l.expanded; } - g.blend = if blend == BlendMode::PassThrough { BlendMode::PassThrough } else { blend }; + g.blend = blend; g } else { - let mut l = Layer::raster(name.clone(), fmt); - l.blend = if blend == BlendMode::PassThrough { BlendMode::Normal } else { blend }; - l + let mut layer = Layer::raster(name.clone(), fmt); + layer.blend = if blend == BlendMode::PassThrough { BlendMode::Normal } else { blend }; + layer }; - layer.opacity = float_opacity.unwrap_or(opacity); - layer.visible = visible; - layer.locks = locks; - layer.label = tag; - layer.clipped = clipped; + layer.opacity = l.opacity; + layer.visible = l.visible; + layer.locks = Locks { transparency: l.lock_alpha, pixels: l.lock_content, position: l.lock_position, ..Locks::default() }; + layer.label = label(l.color_tag); + layer.clipped = l.clipped; - if !group && hptr != 0 { - let source_channels = match (self.base_type, alpha) { - (2, false) => 1, - (2, true) => 2, - (1, false) => 1, - (1, true) => 2, - (_, false) => 3, - (_, true) => 4, - }; - let mut px = self.hierarchy(hptr, source_channels, ctl)?; - if (px.width, px.height) != (lw, lh) { - return Err(invalid(format!("layer '{name}' pixels are {}x{} where {lw}x{lh} were declared", px.width, px.height))); - } + let ctl = self.ctl; + let keep_going = || ctl.check().is_ok(); + if !l.group + && let Some(mut px) = self.xcf.layer_pixels(index, &mut self.budget, &keep_going).map_err(xcf_err)? + { + let alpha = l.has_alpha(); if !alpha { // An opaque layer: add the alpha channel the document's pixel format carries. let n = px.channels; @@ -1080,19 +389,18 @@ impl<'a> Image<'a> { px = Pixels { width: px.width, height: px.height, channels: n + 1, data }; } let mut surface = Surface::new(fmt); - write_pixels(&mut surface, &px, x, y, &mut self.budget)?; + write_pixels(&mut surface, &px, l.x, l.y, &mut self.budget)?; layer.content = LayerContent::Raster(surface); if !alpha { layer.locks.transparency = true; } } - if mptr != 0 { - let (_mname, _mprops, px) = self.channel(mptr, ctl)?; + if let Some((_, px)) = self.xcf.layer_mask(index, &mut self.budget, &keep_going).map_err(xcf_err)? { let mut surface = Surface::new(mask_fmt); - write_pixels(&mut surface, &px, x, y, &mut self.budget)?; - layer.mask = Some(LayerMask { surface, enabled: apply_mask, linked: true, density: 1.0, feather: 0.0 }); + write_pixels(&mut surface, &px, l.x, l.y, &mut self.budget)?; + layer.mask = Some(LayerMask { surface, enabled: l.apply_mask, linked: true, density: 1.0, feather: 0.0 }); } - let linear = composite_space.unsigned_abs() == 1 || blend_space.unsigned_abs() == 1; - Ok(Some((Node { layer, path, group, children: Vec::new() }, linear))) + let linear = l.composite_space.unsigned_abs() == 1 || l.blend_space.unsigned_abs() == 1; + Ok(Some((Node { layer, group: l.group }, linear))) } } diff --git a/crates/io/src/xcf/tests.rs b/crates/io/src/xcf/tests.rs index 5ad14f19b2..770be535b1 100644 --- a/crates/io/src/xcf/tests.rs +++ b/crates/io/src/xcf/tests.rs @@ -2,6 +2,8 @@ //! every compression, precisions, groups, masks, channels, limits and malformed input. use super::*; +use craft_xcf::{Compression, MAX_STRING, TILE}; +use photocraft_codecs::f16; use photocraft_raster::Interrupt; /// A small XCF writer for tests: version 11+ layout (64-bit pointers) by default. @@ -779,36 +781,6 @@ fn a_path_failing_below_the_top_level_lands_at_the_top_level() { assert!(r.warnings.iter().any(|w| w.contains("Stray") && w.contains("item path")), "{:?}", r.warnings); } -/// A parasite name field: u32 `len+1`, then the bytes and a trailing NUL. -fn parasite_name(out: &mut Vec, name: &str) { - out.extend_from_slice(&((name.len() as u32) + 1).to_be_bytes()); - out.extend_from_slice(name.as_bytes()); - out.push(0); -} - -/// One PROP_PARASITES record: name, u32 flags, u32 len, then the payload. -fn parasite_record(out: &mut Vec, name: &str, payload: &[u8]) { - parasite_name(out, name); - out.extend_from_slice(&0u32.to_be_bytes()); - out.extend_from_slice(&(payload.len() as u32).to_be_bytes()); - out.extend_from_slice(payload); -} - -#[test] -fn duplicate_parasites_keep_order_and_last_value() { - // Duplicate names must resolve to the last payload while keeping first-seen order. - // This is the behavior the name->index map must preserve versus the old linear scan. - let mut data = Vec::new(); - parasite_record(&mut data, "gimp-comment", b"first"); - parasite_record(&mut data, "gimp-image-grid", b"grid"); - parasite_record(&mut data, "gimp-comment", b"second"); - let out = parasites(&data); - assert_eq!(out.len(), 2, "duplicate collapses to one slot"); - assert_eq!(out[0].0, "gimp-comment"); - assert_eq!(out[0].1, b"second", "last value wins"); - assert_eq!(out[1].0, "gimp-image-grid", "insertion order preserved"); -} - #[test] fn a_narrow_drawable_is_charged_the_tiles_it_stores() { // One pixel wide and 300000 tall: 1.2 MB of samples a layer, but 1172 whole tiles (307 MB diff --git a/docs/kra.md b/docs/kra.md index 19e39bcf1e..6b893e8ce6 100644 --- a/docs/kra.md +++ b/docs/kra.md @@ -2,7 +2,7 @@ PhotoCraft opens Krita's native documents (`.kra`, and the `.krz` archive variant) with their layers. File › Open, recent files, drops, the CLI (`convert`, `info`, `batch`) and automation -(`doc.open`, MCP) all use the reader in `photocraft-io`; the browser build accepts them too. A +(`doc.open`, MCP) all use the import in `photocraft-io`, on craft-libs' `craft-kra` reader; the browser build accepts them too. A file is recognised by its `mimetype` entry (`application/x-krita`). Krita files are import-only: Save suggests OpenRaster (`.ora`), which Krita opens with its layers, and `.pcraft` keeps everything. diff --git a/docs/ora.md b/docs/ora.md index f981a74d8d..d21fa9d3fc 100644 --- a/docs/ora.md +++ b/docs/ora.md @@ -2,8 +2,8 @@ PhotoCraft opens and saves OpenRaster (`.ora`), the layered format Krita, MyPaint, GIMP, Pinta and others share. File › Open, recent files, drops, Save and Save As, the CLI (`convert`, `info`, -`batch`) and automation (`doc.open`, `doc.save`, MCP) all use the same reader and writer in -`photocraft-io`. The browser build accepts `.ora` too. A file is recognised by its `mimetype` +`batch`) and automation (`doc.open`, `doc.save`, MCP) all use the same import and export in +`photocraft-io`, on craft-libs' `craft-ora` archive reader and writer. The browser build accepts `.ora` too. A file is recognised by its `mimetype` entry, so an OpenRaster file with another extension still opens as one. ## What is kept diff --git a/docs/xcf.md b/docs/xcf.md index afa4e2a42d..60b86417c6 100644 --- a/docs/xcf.md +++ b/docs/xcf.md @@ -2,7 +2,7 @@ PhotoCraft opens GIMP's native `.xcf` files (and `.xcf.gz`) with their layers, read only. File › Open, recent files, drops, the CLI (`convert`, `info`, `batch`) and automation (`doc.open`, MCP) -use the same reader in `photocraft-io` (`crates/io/src/xcf.rs`). A file is recognised by its +use the same import in `photocraft-io` (`crates/io/src/xcf.rs`), on craft-libs' `craft-xcf` reader. A file is recognised by its `gimp xcf ` signature, so an XCF with another extension still opens as one. Save suggests `.pcraft`, which keeps everything PhotoCraft holds; exporting as `.xcf` fails with a message.