mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Use craft-kra, craft-ora, craft-xcf and craft-pdn from craft-libs for the format code
This commit is contained in:
1 parent
eee667f1d9
commit
d7f3793b63
16 files changed
+522
-2173
No files matched your search
Generated
+70
-9
@@ -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]]
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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"
|
||||
|
||||
+63
-147
@@ -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<T> = std::result::Result<T, IoError>;
|
||||
|
||||
/// 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<String>) -> 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<f64> {
|
||||
match attr(node, name) {
|
||||
None | Some("") => Ok(default),
|
||||
Some(v) => v.parse::<f64>().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<i32> {
|
||||
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 `<container>` element (`layers` or `masks`).
|
||||
fn children<'a, 'i>(node: roxmltree::Node<'a, 'i>, container: &str, tag: &'static str) -> impl Iterator<Item = roxmltree::Node<'a, 'i>> {
|
||||
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>,
|
||||
/// `<image name>/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<Option<Vec<u8>>> {
|
||||
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<Option<Vec<f32>>> {
|
||||
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<Option<Surface>> {
|
||||
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 `<layers>` 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<Vec<Layer>> {
|
||||
/// `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<Vec<Layer>> {
|
||||
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<ImportResult> {
|
||||
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<ImportResult> {
|
||||
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<ImportResult>
|
||||
}
|
||||
|
||||
pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result<ImportResult> {
|
||||
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<u32> {
|
||||
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<Im
|
||||
if document.layers.is_empty() {
|
||||
reader.warnings.note("no layers of the Krita document could be imported");
|
||||
}
|
||||
if image.children().any(|n| n.has_tag_name("assistants") || n.has_tag_name("ReferenceImages")) {
|
||||
if image.assistants || image.reference_images {
|
||||
reader.warnings.note("drawing assistants and reference images were left out");
|
||||
}
|
||||
Ok(ImportResult { document, warnings: reader.warnings.finish(), source_read_only: true, preview_only: false })
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::tiles::{Space, lzf_decompress};
|
||||
use super::*;
|
||||
use craft_kra::MIMETYPE;
|
||||
use craft_kra::tiles::Space;
|
||||
use photocraft_codecs::{ChannelLayout, Format, Image, SampleType as CSample};
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_format::zip::ZipWriter;
|
||||
@@ -210,26 +211,14 @@ fn deeply_nested_maindoc_is_an_error_not_a_stack_overflow() {
|
||||
let entity = format!("<!DOCTYPE DOC [<!ENTITY e \"{open}{close}\">]><DOC><IMAGE width=\"4\" height=\"4\">&e;</IMAGE></DOC>");
|
||||
// A quoted `?>` in the XML declaration must not hide the DOCTYPE behind it.
|
||||
let declared = format!("<?xml version=\"?>\"?>{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<u8>| {
|
||||
|
||||
+65
-240
@@ -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<f32>;
|
||||
/// Interleaved Krita pixels as encoded `fmt` bytes.
|
||||
fn convert(self, src: &[u8], fmt: PixelFormat, out: &mut Vec<u8>);
|
||||
}
|
||||
|
||||
impl Space {
|
||||
pub(crate) fn from_name(name: &str) -> Option<Space> {
|
||||
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<f32> {
|
||||
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<f32> {
|
||||
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<f32> {
|
||||
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<u8>) {
|
||||
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<Vec<u8>> {
|
||||
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<usize> {
|
||||
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<usize> {
|
||||
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::<usize>().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<TileFile<'a>> {
|
||||
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::<usize>().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::<i32>().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::<usize>().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<usize> {
|
||||
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<Item = (i32, i32)>, width: usize, height: usize, bpp: usize, dx: i32, dy: i32) -> Result<usize> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
+81
-192
@@ -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<T> = std::result::Result<T, IoError>;
|
||||
|
||||
/// 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<String>) -> 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<f64> {
|
||||
match node.attribute(name) {
|
||||
None => Ok(default),
|
||||
Some(v) => v.trim().parse::<f64>().ok().filter(|v| v.is_finite()).ok_or_else(|| invalid(format!("invalid {name} attribute `{v}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn int(node: roxmltree::Node<'_, '_>, name: &str) -> Result<i32> {
|
||||
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::<u32>().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<Option<usize>> {
|
||||
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<Vec<Node>> {
|
||||
fn stack(&mut self, stack: &[craft_ora::Node], depth: usize) -> Result<Vec<Node>> {
|
||||
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<Node>, images: &[Image], fmt: PixelFormat, budget: &mut usiz
|
||||
}
|
||||
|
||||
pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result<ImportResult> {
|
||||
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 <image> root"));
|
||||
}
|
||||
let side = |attr: &str| -> Result<u32> {
|
||||
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 <stack>"))?;
|
||||
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<Im
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Export
|
||||
|
||||
/// Attribute text with XML's five special characters escaped (and control characters dropped).
|
||||
fn escape(s: &str) -> 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:<id>`, which Krita reads back and others treat as Normal).
|
||||
fn op_name(mode: BlendMode) -> Option<String> {
|
||||
@@ -505,8 +402,7 @@ fn op_name(mode: BlendMode) -> Option<String> {
|
||||
|
||||
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<Vec<craft_ora::Node>> {
|
||||
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!("<stack {attrs} isolation=\"{isolation}\">"));
|
||||
self.layers(&g.children, depth + 1)?;
|
||||
self.xml.push_str("</stack>");
|
||||
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!("<layer {attrs} src=\"{src}\" x=\"{}\" y=\"{}\"/>", 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<ExportResult> {
|
||||
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!(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<image version=\"0.0.6\" w=\"{}\" h=\"{}\" xres=\"{}\" yres=\"{}\"><stack>",
|
||||
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("</stack></image>\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<String> {
|
||||
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());
|
||||
|
||||
@@ -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!("<image w=\"4\" h=\"4\">{}{}</image>", "<stack>".repeat(20_000), "</stack>".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<u8> {
|
||||
@@ -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("<image/>", &[])), 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);
|
||||
|
||||
+65
-224
@@ -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<T> = std::result::Result<T, IoError>;
|
||||
|
||||
// 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<String>) -> IoError {
|
||||
IoError::Pdn(message.into())
|
||||
}
|
||||
|
||||
fn count(graph: &Graph, object: &Value, field: &str) -> Result<usize> {
|
||||
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<BlendMode> {
|
||||
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<Vec<u8>> {
|
||||
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<ImportResult> {
|
||||
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 })
|
||||
|
||||
@@ -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<u8> {
|
||||
Ok(self.take(1)?.first().copied().unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn le_i32(&mut self) -> Result<i32> {
|
||||
Ok(i32::from_le_bytes(self.take(4)?.try_into().map_err(|_| invalid("invalid integer"))?))
|
||||
}
|
||||
|
||||
pub fn be_u32(&mut self) -> Result<usize> {
|
||||
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<usize> {
|
||||
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<String>,
|
||||
primitives: Vec<Option<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum Value {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Int(i64),
|
||||
String(String),
|
||||
Ref(i32),
|
||||
Array(Vec<Value>),
|
||||
Object { class: Arc<Class>, members: Vec<Value> },
|
||||
}
|
||||
|
||||
pub(super) struct Graph {
|
||||
pub root: Value,
|
||||
objects: HashMap<i32, Value>,
|
||||
order: Vec<i32>,
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
pub fn objects_of_class<'a>(&'a self, name: &'a str) -> impl Iterator<Item = (i32, &'a Value)> {
|
||||
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<Option<&'a Value>> {
|
||||
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<i64> {
|
||||
match self.resolve(value)? {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err(invalid("expected an integer")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn boolean(&self, value: &Value) -> Result<bool> {
|
||||
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<i32, Arc<Class>>,
|
||||
items: usize,
|
||||
strings: usize,
|
||||
}
|
||||
|
||||
pub(super) fn parse(reader: &mut Reader<'_>, ctl: &Interrupt<'_>) -> Result<Graph> {
|
||||
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<String> {
|
||||
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<Value> {
|
||||
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<Option<u8>> {
|
||||
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<Value> {
|
||||
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<Class>, depth: usize) -> Result<Value> {
|
||||
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<u8>, depth: usize) -> Result<Value> {
|
||||
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<Value> {
|
||||
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::<Result<Vec<_>>>()?;
|
||||
let primitives = if tag >= 4 {
|
||||
let types = self.reader.take(count)?.to_vec();
|
||||
types.into_iter().map(|t| self.type_info(t)).collect::<Result<Vec<_>>>()?
|
||||
} 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}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-53
@@ -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<u8> {
|
||||
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}");
|
||||
}
|
||||
+133
-825
File diff suppressed because it is too large.
Load diff
@@ -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<u8>, 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<u8>, 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
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
+2
-2
@@ -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
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
|
||||
Reference in new issue
Block a user