Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Add OpenRaster (.ora) import and export (#2257)

Scott Campbell7722172585a0
diff --git a/Cargo.lock b/Cargo.lock
index d5d5a957f..189c9bc02 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4440,6 +4440,7 @@ dependencies = [
"photocraft-vector",
"proptest",
"resvg",
+ "roxmltree",
"serde_json",
"thiserror 2.0.21",
]
diff --git a/README.md b/README.md
index c378d6f92..fd5dd0a49 100644
--- a/README.md
+++ b/README.md
@@ -199,7 +199,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
</td>
<td width="33%" valign="top">
<h4>🗂️ Formats</h4>
- PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), <a href="docs/pdn.md">Paint.NET PDN3 (read, with editable layers and all 14 blend modes)</a>, SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR and Radiance HDR, and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="crates/codecs/README.md#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
+ PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), <a href="docs/pdn.md">Paint.NET PDN3 (read, with editable layers and all 14 blend modes)</a>, <a href="docs/ora.md">OpenRaster (read and write, with layers, groups and blend modes, for Krita, MyPaint and GIMP)</a>, SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR and Radiance HDR, and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="crates/codecs/README.md#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
</td>
<td width="33%" valign="top">
<h4>🪄 The everyday essentials</h4>
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index 202458469..345edf965 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -341,7 +341,7 @@ fn same_dir(a: &Path, b: &Path) -> bool {
fn is_input(p: &Path) -> bool {
let known = |e: &str| {
- matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "af" | "afdesign" | "afphoto" | "afpub")
+ matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "af" | "afdesign" | "afphoto" | "afpub")
|| photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read)
};
p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))
@@ -548,6 +548,26 @@ mod missing_font_warning_tests {
let _ = std::fs::remove_dir_all(&folder);
}
+ #[test]
+ fn convert_reads_and_writes_openraster() {
+ let folder = std::env::temp_dir().join(format!("photocraft-cli-ora-{}", std::process::id()));
+ std::fs::create_dir_all(&folder).unwrap();
+ let path = |name: &str| folder.join(name).to_string_lossy().to_string();
+ let (native, ora, png) = (path("layers.pcraft"), path("layers.ora"), path("back.png"));
+ let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":16,"height":12}"#, "--cmd", "layer.new.layer", "--out", &native]);
+ assert_eq!(code, 0, "{stderr}");
+ let (code, _, stderr) = invoke(&["convert", &native, &ora]);
+ assert_eq!(code, 0, "{stderr}");
+ let (code, stdout, stderr) = invoke(&["info", &ora, "--compact"]);
+ assert_eq!(code, 0, "{stderr}");
+ let info: Value = serde_json::from_str(&stdout).unwrap();
+ assert_eq!(info["layers"].as_array().map(Vec::len), Some(2), "{info}");
+ let (code, _, stderr) = invoke(&["convert", &ora, &png]);
+ assert_eq!(code, 0, "{stderr}");
+ assert!(is_input(std::path::Path::new(&ora)));
+ let _ = std::fs::remove_dir_all(&folder);
+ }
+
#[test]
fn no_type_layers_do_not_produce_missing_font_warnings() {
let folder = std::env::temp_dir().join(format!("photocraft-cli-no-font-warning-{}", std::process::id()));
diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs
index af0ea95df..21b70492a 100644
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@ -14,12 +14,12 @@ use wasm_bindgen::JsCast as _;
type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
-/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
+/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster and Affinity documents, flat images, and
/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
- "pcraft", "pdn", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm",
- "pam", "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",
- "afdesign", "afphoto", "afpub",
+ "pcraft", "pdn", "ora", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm",
+ "ppm", "pam", "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco",
+ "ase", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
const CANVAS_ID: &str = "photocraft_canvas";
@@ -427,6 +427,7 @@ fn mime_for(name: &str) -> &'static str {
Some("webp") => "image/webp",
Some("gif") => "image/gif",
Some("psd" | "psb") => "image/vnd.adobe.photoshop",
+ Some("ora") => "image/openraster",
_ => "application/octet-stream",
}
}
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 373be0b45..bd8eb15f2 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -16,13 +16,13 @@ use std::sync::Arc;
#[cfg(test)]
mod recovery_tests;
-/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
+/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster and Affinity documents, flat images, and
/// Photoshop brushes (.abr), gradients (.grd), swatches (.aco, .ase) and keyboard shortcut sets
/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
const OPEN_EXTS: &[&str] = &[
- "pcraft", "pdn", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm",
- "pam", "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase",
- "kys", "af", "afdesign", "afphoto", "afpub",
+ "pcraft", "pdn", "ora", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm",
+ "ppm", "pam", "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco",
+ "ase", "kys", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
@@ -39,7 +39,12 @@ fn open_filter_extensions(extensions: &[&str]) -> Vec<String> {
/// An explicit SVG filter keeps vector artwork discoverable even when a native picker defaults to
/// the PhotoCraft-only filter. SVG is also included in All Formats for normal multi-format opens.
fn open_filters() -> Vec<(&'static str, Vec<String>)> {
- vec![("All Formats", open_filter_extensions(OPEN_EXTS)), ("PhotoCraft", open_filter_extensions(&["pcraft"])), ("SVG", open_filter_extensions(SVG_EXTS))]
+ vec![
+ ("All Formats", open_filter_extensions(OPEN_EXTS)),
+ ("PhotoCraft", open_filter_extensions(&["pcraft"])),
+ ("OpenRaster", open_filter_extensions(&["ora"])),
+ ("SVG", open_filter_extensions(SVG_EXTS)),
+ ]
}
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
@@ -48,6 +53,7 @@ fn open_filters() -> Vec<(&'static str, Vec<String>)> {
const SAVE_FILTERS: &[(&str, &[&str])] = &[
("PSD Document", &["psd", "psb"]),
("PhotoCraft", &["pcraft"]),
+ ("OpenRaster", &["ora"]),
("PNG", &["png"]),
("JPEG", &["jpg"]),
("WebP", &["webp"]),
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index c6bfa1bea..e9cbca924 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -145,13 +145,13 @@ impl Headless {
warnings
}
};
- // A layered document save (PSD, PSB or .pcraft) is a full write, not a flattened copy:
+ // A layered document save (PSD, PSB, OpenRaster or .pcraft) is a full write, not a flattened copy:
// record the current revision as saved so the session stops reporting `dirty`, and make
// the file the document's path. A flat export (PNG, JPEG, …) is a copy and leaves both
// alone (#1547).
let ext =
format.map(|f| f.trim_start_matches('.').to_ascii_lowercase()).or_else(|| target.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()));
- let layered = matches!(ext.as_deref(), Some("psd" | "psb")) || ext.as_deref() == Some(photocraft_format::EXTENSION);
+ let layered = matches!(ext.as_deref(), Some("psd" | "psb" | "ora")) || ext.as_deref() == Some(photocraft_format::EXTENSION);
if layered {
// Saving by index must not retarget the next automation command.
let previously_active = self.session.active_index();
diff --git a/crates/automation/tests/openraster.rs b/crates/automation/tests/openraster.rs
new file mode 100644
index 000000000..fe941c50b
--- /dev/null
+++ b/crates/automation/tests/openraster.rs
@@ -0,0 +1,68 @@
+//! OpenRaster through the agent surface (`doc.*` and `engine.execute`, as MCP and the CLI use
+//! it): save a layered document as .ora, reopen it with its layers, edit it and save it back in
+//! place.
+
+use photocraft_automation::Headless;
+use serde_json::json;
+
+fn tmp(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "pc-openraster-{name}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
+fn exec(h: &mut Headless, command: &str, params: serde_json::Value) -> serde_json::Value {
+ h.handle("engine.execute", json!({"command": command, "params": params})).unwrap()
+}
+
+#[test]
+fn layered_documents_save_reopen_and_save_in_place_as_openraster() {
+ let dir = tmp("roundtrip");
+ let path = dir.join("art.ora");
+ let path_str = path.to_str().unwrap();
+ let mut h = Headless::trusted_local();
+ h.handle("doc.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap();
+ exec(&mut h, "layer.new.layer", json!({}));
+ exec(&mut h, "paint.stroke", json!({"points": [[4, 4], [30, 20]], "size": 6, "hardness": 1.0, "color": "#ff0000"}));
+ let top = h.session.active().unwrap().doc.layers.last().unwrap().id.0;
+ exec(&mut h, "layer.setProps", json!({"layer": top, "name": "Ink", "opacity": 0.5, "blend": "Multiply"}));
+ let before = photocraft_compose::flatten(&h.session.active().unwrap().doc);
+
+ let saved = h.handle("doc.save", json!({"path": path_str})).unwrap();
+ assert!(saved["warnings"].as_array().is_none_or(Vec::is_empty), "{saved}");
+ let bytes = std::fs::read(&path).unwrap();
+ assert_eq!(bytes.get(30..54), Some(&b"mimetypeimage/openraster"[..]), "a stored mimetype comes first");
+ assert!(!h.session.active().unwrap().is_dirty(), "an OpenRaster save is a layered save");
+ assert_eq!(h.session.active().unwrap().path.as_deref(), Some(path_str));
+
+ let opened = h.handle("doc.open", json!({"path": path_str})).unwrap();
+ let doc = &h.session.active().unwrap().doc;
+ assert_eq!(doc.layers.len(), 2, "{opened}");
+ let ink = doc.layers.last().unwrap();
+ assert_eq!((ink.name.as_str(), ink.opacity, ink.blend), ("Ink", 0.5, photocraft_doc::BlendMode::Multiply));
+ assert_eq!(photocraft_compose::flatten(doc).px, before.px);
+
+ // Edit, then a pathless save writes the .ora back in place and clears dirty.
+ exec(&mut h, "image.adjustments.invert", json!({}));
+ assert!(h.session.active().unwrap().is_dirty());
+ h.handle("doc.save", json!({})).unwrap();
+ assert!(!h.session.active().unwrap().is_dirty());
+ let reread = photocraft_io::import("art.ora", &std::fs::read(&path).unwrap()).unwrap().document;
+ assert_eq!(photocraft_compose::flatten(&reread).px, photocraft_compose::flatten(&h.session.active().unwrap().doc).px);
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+fn a_corrupt_openraster_file_reports_an_error() {
+ let dir = tmp("corrupt");
+ let path = dir.join("broken.ora");
+ std::fs::write(&path, b"PK\x03\x04 not really a zip").unwrap();
+ let mut h = Headless::trusted_local();
+ let err = h.handle("doc.open", json!({"path": path.to_str().unwrap()})).unwrap_err();
+ assert!(err.to_string().contains("OpenRaster"), "{err}");
+ std::fs::remove_dir_all(dir).unwrap();
+}
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index d28efc04c..d75cd6450 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -116,8 +116,8 @@ pub(crate) fn list_images(dir: &str) -> Result<Vec<String>> {
/// Extensions the batch commands pick up from a folder.
const OPENABLE: &[&str] = &[
- "pdn", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", "ppm", "pgm", "heic",
- "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", "afphoto", "afpub",
+ "pdn", "ora", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", "ppm", "pgm",
+ "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", "afphoto", "afpub",
];
/// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone
@@ -152,7 +152,7 @@ pub fn extension(path: &str) -> Option<String> {
/// Whether a save without a new path may write back to `path`: only layered files (PSD, PSB,
/// .pcraft). A flat file goes through Save As instead, so it is never flattened over the original.
pub fn saves_in_place(path: &str) -> bool {
- extension(path).is_some_and(|ext| matches!(ext.as_str(), "psd" | "psb" | "pcraft"))
+ extension(path).is_some_and(|ext| matches!(ext.as_str(), "psd" | "psb" | "pcraft" | "ora"))
}
/// Whether `path` names a document template (.psdt). A template opens as a new untitled document
diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs
index 6bd48acde..65cfea290 100644
--- a/crates/engine/src/file_cmds/tests.rs
+++ b/crates/engine/src/file_cmds/tests.rs
@@ -543,7 +543,7 @@ fn guide_layouts() {
#[test]
fn only_layered_files_save_in_place() {
- for path in ["a.psd", "dir/a.PSB", r"C:\w\a.pcraft", "my.dir/a.psd"] {
+ for path in ["a.psd", "dir/a.PSB", r"C:\w\a.pcraft", "my.dir/a.psd", "a.ora", "dir/A.ORA"] {
assert!(saves_in_place(path), "{path}");
}
// Flat formats, no extension, a dotted folder with an extensionless file, a dot file.
diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml
index 60063e72c..9bd4c559c 100644
--- a/crates/io/Cargo.toml
+++ b/crates/io/Cargo.toml
@@ -37,6 +37,8 @@ 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).
+roxmltree = "0.20"
# SVG import (svg.rs): usvg parses, resvg rasterises what the shape model can't hold. Both are
# already in the tree through the UI's icon loader; text shaping needs the fonts feature set.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 66072f3b1..c9971c7e3 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -16,6 +16,8 @@
//! * Layered TIFFs (Photoshop layer data in tags 37724 and 34377) open with their
//! layers through the PSD path and are written back the same way; see `tiff_layers`.
//! * Paint.NET PDN3 documents open as editable bitmap layers (import only).
+//! * OpenRaster (`.ora`) documents open and save with their layers, groups, blend modes,
+//! opacity and visibility; see `ora`.
//! * Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`) open natively
//! with no source save path, what isn't imported listed in the warnings; a file
//! whose native data can't be read opens as its embedded preview; see `affinity`.
@@ -40,6 +42,7 @@ mod flat;
mod gradient_bake;
pub mod linked;
mod multichannel_map;
+mod ora;
pub mod pattern_map;
mod pdn;
pub mod pixels;
@@ -69,6 +72,9 @@ pub enum IoError {
/// Paint.NET document decode failure.
#[error("PDN: {0}")]
Pdn(String),
+ /// OpenRaster read failure.
+ #[error("OpenRaster: {0}")]
+ Ora(String),
/// PSD parse/write failure.
#[error("PSD: {0}")]
Psd(#[from] PsdError),
@@ -222,6 +228,9 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, m
if affinity::is_affinity(bytes) || affinity::has_extension(name) {
return affinity::import(name, bytes);
}
+ if ora::is_ora(bytes) || has_extension(name, "ora") {
+ return ora::import(name, bytes, ctl);
+ }
if has_extension(name, "pdn") || bytes.starts_with(b"PDN3") {
return pdn::import(name, bytes, ctl);
}
@@ -264,6 +273,9 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result
if affinity::EXTENSIONS.contains(&ext.as_str()) {
return Err(IoError::Unsupported("Affinity export is not implemented; save a new PSD, PNG or .pcraft copy".into()));
}
+ if ext == "ora" {
+ return ora::export(doc);
+ }
if ext == photocraft_format::EXTENSION {
let previews = photocraft_format::SaveOptions {
thumbnail: Some(photocraft_compose::thumbnail(doc, 256)),
diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs
new file mode 100644
index 000000000..b15f498b5
--- /dev/null
+++ b/crates/io/src/ora.rs
@@ -0,0 +1,677 @@
+//! OpenRaster (`.ora`) read and write. Layout from the public OpenRaster specification
+//! (https://www.openraster.org/, `stack.xml` 0.0.x): a ZIP whose first, stored entry is
+//! `mimetype` = `image/openraster`, a `stack.xml` layer tree, one PNG per layer, and a
+//! `mergedimage.png` / `Thumbnails/thumbnail.png` rendering.
+//!
+//! Read: raster layers (PNG, any position and size), groups (isolated and pass-through),
+//! names, opacity, visibility, `svg:*` and Krita's `krita:*` composite operations, and the
+//! `edit-locked` / `alpha-preserve` flags. Everything else is skipped with a warning.
+//! Write: raster layers and groups as above; other layer kinds are written as their rendered
+//! pixels, layer masks are applied to the pixels, and whatever ORA cannot hold is warned about.
+
+#[cfg(test)]
+mod tests;
+
+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};
+
+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;
+ }
+ 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
+/// `krita:<id>` composite operations Krita writes into ORA for modes SVG has no name for.
+/// Returns the mode and whether it only approximates Krita's formula.
+pub(crate) fn krita_blend(id: &str) -> Option<(BlendMode, bool)> {
+ use BlendMode as B;
+ Some(match id {
+ "normal" => (B::Normal, false),
+ "multiply" => (B::Multiply, false),
+ "screen" => (B::Screen, false),
+ "overlay" => (B::Overlay, false),
+ "darken" => (B::Darken, false),
+ "lighten" => (B::Lighten, false),
+ "dodge" => (B::ColorDodge, false),
+ "burn" => (B::ColorBurn, false),
+ "hard_light" => (B::HardLight, false),
+ "soft_light" => (B::SoftLight, false),
+ // The W3C soft light curve, close to but not Photoshop's.
+ "soft_light_svg" => (B::SoftLight, true),
+ "diff" => (B::Difference, false),
+ "exclusion" => (B::Exclusion, false),
+ "linear_burn" => (B::LinearBurn, false),
+ "linear_dodge" | "add" => (B::LinearDodge, false),
+ "subtract" => (B::Subtract, false),
+ "divide" => (B::Divide, false),
+ "vivid_light" => (B::VividLight, false),
+ "linear light" => (B::LinearLight, false),
+ "pin_light" => (B::PinLight, false),
+ "hard_mix_photoshop" => (B::HardMix, false),
+ // Krita's own Hard Mix thresholds differently from Photoshop's.
+ "hard mix" => (B::HardMix, true),
+ "darker color" => (B::DarkerColor, false),
+ "lighter color" => (B::LighterColor, false),
+ "hue" => (B::Hue, false),
+ "saturation" => (B::Saturation, false),
+ "color" => (B::Color, false),
+ "luminize" => (B::Luminosity, false),
+ "dissolve" => (B::Dissolve, false),
+ "reflect" => (B::Reflect, false),
+ "glow" => (B::Glow, false),
+ "negation" => (B::Negation, false),
+ "xor" => (B::Xor, true),
+ _ => return None,
+ })
+}
+
+/// The Krita composite-op id written for `mode` (`None` for modes Krita has no counterpart for).
+pub(crate) fn krita_id(mode: BlendMode) -> Option<&'static str> {
+ use BlendMode as B;
+ Some(match mode {
+ B::Normal | B::PassThrough => "normal",
+ B::Dissolve => "dissolve",
+ B::Darken => "darken",
+ B::Multiply => "multiply",
+ B::ColorBurn => "burn",
+ B::LinearBurn => "linear_burn",
+ B::DarkerColor => "darker color",
+ B::Lighten => "lighten",
+ B::Screen => "screen",
+ B::ColorDodge => "dodge",
+ B::LinearDodge => "linear_dodge",
+ B::LighterColor => "lighter color",
+ B::Overlay => "overlay",
+ B::SoftLight => "soft_light",
+ B::HardLight => "hard_light",
+ B::VividLight => "vivid_light",
+ B::LinearLight => "linear light",
+ B::PinLight => "pin_light",
+ B::HardMix => "hard_mix_photoshop",
+ B::Difference => "diff",
+ B::Exclusion => "exclusion",
+ B::Subtract => "subtract",
+ B::Divide => "divide",
+ B::Hue => "hue",
+ B::Saturation => "saturation",
+ B::Color => "color",
+ B::Luminosity => "luminize",
+ B::Reflect => "reflect",
+ B::Glow => "glow",
+ B::Negation => "negation",
+ B::Xor | B::PaintNetColorBurn | B::PaintNetColorDodge => return None,
+ })
+}
+
+/// The SVG compositing names of the OpenRaster specification.
+const SVG_OPS: [(&str, BlendMode); 15] = [
+ ("svg:src-over", BlendMode::Normal),
+ ("svg:multiply", BlendMode::Multiply),
+ ("svg:screen", BlendMode::Screen),
+ ("svg:overlay", BlendMode::Overlay),
+ ("svg:darken", BlendMode::Darken),
+ ("svg:lighten", BlendMode::Lighten),
+ ("svg:color-dodge", BlendMode::ColorDodge),
+ ("svg:color-burn", BlendMode::ColorBurn),
+ ("svg:hard-light", BlendMode::HardLight),
+ ("svg:soft-light", BlendMode::SoftLight),
+ ("svg:difference", BlendMode::Difference),
+ ("svg:color", BlendMode::Color),
+ ("svg:luminosity", BlendMode::Luminosity),
+ ("svg:hue", BlendMode::Hue),
+ ("svg:saturation", BlendMode::Saturation),
+];
+
+/// A composite-op attribute as a blend mode; unknown names fall back to Normal with a warning.
+fn composite_op(op: &str, layer: &str, warnings: &mut Warnings) -> BlendMode {
+ if let Some((_, mode)) = SVG_OPS.iter().find(|(name, _)| *name == op) {
+ if op == "svg:soft-light" {
+ warnings.note("svg:soft-light (the W3C curve) opens as Photoshop's Soft Light, which differs slightly");
+ }
+ return *mode;
+ }
+ match op {
+ "svg:plus" => return BlendMode::LinearDodge,
+ // Not in the specification's list, but written by several applications.
+ "svg:exclusion" => return BlendMode::Exclusion,
+ _ => {}
+ }
+ if let Some((mode, approx)) = op.strip_prefix("krita:").and_then(krita_blend) {
+ if approx {
+ warnings.note(&format!("Krita's {op} blend mode is approximated by {}", mode.label()));
+ }
+ return mode;
+ }
+ warnings.layer(layer, &format!("composite operation {op} is not supported; it opens as Normal"));
+ BlendMode::Normal
+}
+
+/// Warnings gathered during import, each distinct message once; per-layer ones are grouped.
+#[derive(Default)]
+pub(crate) struct Warnings {
+ general: Vec<String>,
+ per_layer: Vec<(String, Vec<String>)>,
+}
+
+impl Warnings {
+ pub(crate) fn note(&mut self, message: &str) {
+ if !self.general.iter().any(|m| m == message) {
+ self.general.push(message.to_string());
+ }
+ }
+ pub(crate) fn layer(&mut self, layer: &str, message: &str) {
+ match self.per_layer.iter_mut().find(|(m, _)| m == message) {
+ Some((_, layers)) => {
+ if !layers.iter().any(|l| l == layer) {
+ layers.push(layer.to_string());
+ }
+ }
+ None => self.per_layer.push((message.to_string(), vec![layer.to_string()])),
+ }
+ }
+ pub(crate) fn finish(self) -> Vec<String> {
+ let mut out = self.general;
+ for (message, layers) in self.per_layer {
+ let shown: Vec<String> = layers.iter().take(5).map(|l| format!("\"{l}\"")).collect();
+ let more = layers.len().saturating_sub(5);
+ let tail = if more > 0 { format!(" and {more} more") } else { String::new() };
+ out.push(format!("{} ({}{tail})", message, shown.join(", ")));
+ }
+ out
+ }
+}
+
+/// 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").map(str::trim).filter(|n| !n.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") {
+ layer.locks.all = true;
+ }
+ if flag(node, "alpha-preserve") {
+ layer.locks.transparency = true;
+ }
+ Ok(())
+}
+
+struct Reader<'a, 'c> {
+ zip: ZipReader<'a>,
+ ctl: &'c Interrupt<'c>,
+ nodes: usize,
+ budget: usize,
+ warnings: Warnings,
+ /// Decoded layer PNGs, converted to the document depth once every layer is known.
+ images: Vec<Image>,
+}
+
+/// A layer as read, before its pixels are converted to the document's format.
+enum Node {
+ Raster { layer: Layer, image: Option<usize>, x: i32, y: i32 },
+ Group { layer: Layer, children: Vec<Node> },
+}
+
+impl Reader<'_, '_> {
+ fn png(&mut self, src: &str, layer: &str) -> Result<Option<usize>> {
+ let Some(entry) = self.zip.find(src).cloned() 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;
+ opts.limits.max_alloc = self.budget as u64;
+ let image = codecs::decode_with(&data, &opts).map_err(|e| invalid(format!("{src}: {e}")))?;
+ let (w, h) = image.dimensions();
+ let rgba16 = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(8)).ok_or_else(|| invalid("layer image size overflow"))?;
+ self.budget = self.budget.checked_sub(rgba16).ok_or_else(|| invalid("decoded layers exceed the 1 GiB limit"))?;
+ if !matches!(codecs::detect(&data), Some(Format::Png)) {
+ self.warnings.note("some layer images are not PNG, as OpenRaster expects; they were read anyway");
+ }
+ self.images.push(image);
+ Ok(Some(self.images.len() - 1))
+ }
+
+ fn stack(&mut self, stack: roxmltree::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) {
+ 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" => {
+ 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())?,
+ None => {
+ self.warnings.layer(&layer.name, "the layer has no image; it opens empty");
+ None
+ }
+ };
+ out.push(Node::Raster { layer, image, x, y });
+ }
+ "stack" => {
+ let mut layer = Layer::group("", Vec::new());
+ props(child, &mut layer, index, &mut self.warnings)?;
+ // `auto` (the default) isolates only when something needs it: an
+ // OpenRaster group without its own blend mode is a pass-through group.
+ let isolate = child.attribute("isolation").map(str::trim) == Some("isolate");
+ if !isolate && layer.blend == BlendMode::Normal {
+ layer.blend = BlendMode::PassThrough;
+ }
+ let children = self.stack(child, 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"));
+ }
+ }
+ }
+ Ok(out)
+ }
+}
+
+/// Sample depth of the document: the deepest layer image (8 or 16 bit; float stays float).
+fn document_depth(images: &[Image]) -> SampleType {
+ images.iter().fold(SampleType::U8, |d, i| match (d, i.sample_type()) {
+ (SampleType::F32, _) | (_, CSample::F32 | CSample::F16) => SampleType::F32,
+ (SampleType::U16, _) | (_, CSample::U16) => SampleType::U16,
+ _ => SampleType::U8,
+ })
+}
+
+pub(crate) fn csample(depth: SampleType) -> CSample {
+ crate::flat::csample(depth)
+}
+
+/// Builds the document tree bottom-to-top (stack.xml lists the topmost node first).
+fn build(nodes: Vec<Node>, images: &[Image], fmt: PixelFormat, ctl: &Interrupt<'_>) -> Result<Vec<Layer>> {
+ let mut out = Vec::with_capacity(nodes.len());
+ for node in nodes.into_iter().rev() {
+ ctl.check().map_err(|_| IoError::Cancelled)?;
+ match node {
+ Node::Raster { mut layer, image, x, y } => {
+ let mut surface = Surface::new(fmt);
+ if let Some(image) = image.and_then(|i| images.get(i)) {
+ let (w, h) = image.dimensions();
+ let px = image.convert(ChannelLayout::Rgba, csample(fmt.sample));
+ let rect = Rect::new(x, y, x.saturating_add(w as i32), y.saturating_add(h as i32));
+ if rect.width() != w || rect.height() != h || px.data().len() != (w as usize) * (h as usize) * fmt.bytes_per_pixel() {
+ return Err(invalid("layer image does not fit its position"));
+ }
+ surface.write_interleaved(rect, px.data());
+ surface.prune();
+ }
+ layer.content = LayerContent::Raster(surface);
+ out.push(layer);
+ }
+ Node::Group { mut layer, children } => {
+ let children = build(children, images, fmt, ctl)?;
+ if let Some(c) = layer.children_mut() {
+ *c = children;
+ }
+ out.push(layer);
+ }
+ }
+ }
+ Ok(out)
+}
+
+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 = roxmltree::Document::parse(xml).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 mut reader = Reader { zip, ctl, nodes: 0, budget: MAX_PIXEL_BYTES, warnings: Warnings::default(), images: Vec::new() };
+ let nodes = reader.stack(root, 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);
+ document.layers = build(nodes, &reader.images, fmt, ctl)?;
+ let xres = num(image, "xres", 72.0)?;
+ let yres = num(image, "yres", xres)?;
+ if xres > 0.0 && xres < 1.0e6 {
+ document.resolution_dpi = xres as f32;
+ reader.warnings.general.extend(crate::unequal_resolution_warning(xres, yres));
+ }
+ if document.layers.is_empty() {
+ reader.warnings.note("the OpenRaster file has no layers");
+ }
+ Ok(ImportResult { document, warnings: reader.warnings.finish(), source_read_only: false, preview_only: false })
+}
+
+// ---------------------------------------------------------------------------------------------
+// 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("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ '"' => out.push_str("&quot;"),
+ '\'' => out.push_str("&apos;"),
+ '\t' => out.push_str("&#9;"),
+ '\n' => out.push_str("&#10;"),
+ 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> {
+ match mode {
+ BlendMode::PassThrough => Some("svg:src-over".into()),
+ BlendMode::LinearDodge => Some("svg:plus".into()),
+ m => SVG_OPS.iter().find(|(_, s)| *s == m).map(|(n, _)| (*n).to_string()).or_else(|| krita_id(m).map(|id| format!("krita:{id}"))),
+ }
+}
+
+struct Writer<'a> {
+ doc: &'a Document,
+ zip: ZipWriter,
+ xml: String,
+ next: usize,
+ sample: CSample,
+ warnings: Warnings,
+}
+
+/// Straight RGBA floats as interleaved PNG samples at `sample` depth.
+fn encode_rgba(px: &[[f32; 4]], sample: CSample) -> Vec<u8> {
+ match sample {
+ CSample::U16 => px.iter().flat_map(|p| p.map(|v| ((v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16).to_ne_bytes())).flatten().collect(),
+ _ => px.iter().flat_map(|p| p.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)).collect(),
+ }
+}
+
+fn png(w: u32, h: u32, px: &[[f32; 4]], sample: CSample) -> Result<Vec<u8>> {
+ let image = Image::from_raw(w, h, ChannelLayout::Rgba, sample, encode_rgba(px, sample))?;
+ let opts = codecs::EncodeOptions { embed_icc: false, ..Default::default() };
+ Ok(codecs::encode(&image, Format::Png, &opts)?)
+}
+
+/// `px` (row-major over `rect`) cut down to the pixels that aren't fully transparent, with
+/// transparent pixels zeroed, so masked-out or empty margins aren't written.
+fn crop(rect: Rect, mut px: Vec<[f32; 4]>) -> (Rect, Vec<[f32; 4]>) {
+ let w = rect.width() as usize;
+ if w == 0 {
+ return (Rect::EMPTY, Vec::new());
+ }
+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);
+ for (i, p) in px.iter_mut().enumerate() {
+ if p[3] <= 0.0 {
+ *p = [0.0; 4];
+ continue;
+ }
+ let (x, y) = (i % w, i / w);
+ (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));
+ }
+ if x0 >= x1 {
+ return (Rect::EMPTY, Vec::new());
+ }
+ if (x0, y0, x1) == (0, 0, w) && y1 == px.len() / w {
+ return (rect, px);
+ }
+ let out = (y0..y1).flat_map(|y| px.get(y * w + x0..y * w + x1).unwrap_or_default().iter().copied()).collect();
+ (Rect::new(rect.x0 + x0 as i32, rect.y0 + y0 as i32, rect.x0 + x1 as i32, rect.y0 + y1 as i32), out)
+}
+
+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" },
+ layer.opacity.clamp(0.0, 1.0)
+ );
+ 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\"");
+ }
+ 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");
+ }
+ if !layer.effects.items.is_empty() || layer.effects.psd_raw.is_some() {
+ self.warnings.layer(&layer.name, "layer styles are not saved to OpenRaster");
+ }
+ if layer.vector_mask.as_ref().is_some_and(|m| m.enabled) {
+ self.warnings.layer(&layer.name, "vector masks are not saved to OpenRaster");
+ }
+ if layer.fill_opacity < 1.0 {
+ self.warnings.layer(&layer.name, "fill opacity was combined into the layer opacity");
+ }
+ attrs
+ }
+
+ /// The layer's own pixels (straight RGBA floats) and their bounds; its pixel mask applied.
+ fn pixels(&mut self, layer: &Layer) -> (Rect, Vec<[f32; 4]>) {
+ let canvas = self.doc.bounds();
+ let (rect, mut buf) = match &layer.content {
+ LayerContent::Raster(s) => {
+ let r = s.content_bounds();
+ (r, photocraft_compose::surface_to_buffer(s, r).px)
+ }
+ _ => {
+ // Rendered as it shows on its own, before the layer's blending options.
+ let mut solo = layer.clone();
+ solo.visible = true;
+ solo.opacity = 1.0;
+ solo.fill_opacity = 1.0;
+ solo.blend = BlendMode::Normal;
+ solo.clipped = false;
+ solo.mask = None;
+ solo.effects = Default::default();
+ let r = photocraft_compose::composite_bounds(&solo, canvas).unwrap_or(canvas).intersect(&canvas);
+ self.warnings.layer(&layer.name, &format!("{} layers are saved to OpenRaster as pixels", layer.content.kind_name().to_lowercase()));
+ (r, photocraft_compose::render_layer(&solo, r).px)
+ }
+ };
+ if let Some(mask) = layer.mask.as_ref().filter(|m| m.enabled) {
+ if mask.feather > 0.0 {
+ self.warnings.layer(&layer.name, "layer mask feathering is not applied in OpenRaster");
+ }
+ self.warnings.layer(&layer.name, "layer masks were applied to the layer pixels");
+ let mut values = Vec::new();
+ mask.values_into(rect, &mut values);
+ for (p, m) in buf.iter_mut().zip(values) {
+ p[3] *= m;
+ }
+ }
+ if layer.fill_opacity < 1.0 {
+ for p in &mut buf {
+ p[3] *= layer.fill_opacity.clamp(0.0, 1.0);
+ }
+ }
+ crop(rect, buf)
+ }
+
+ fn layers(&mut self, layers: &[Layer], depth: usize) -> Result<()> {
+ if depth > photocraft_doc::MAX_GROUP_DEPTH {
+ return Err(IoError::Unsupported(format!("layer groups nested deeper than {}", photocraft_doc::MAX_GROUP_DEPTH)));
+ }
+ // stack.xml lists the topmost layer first.
+ for layer in layers.iter().rev() {
+ match &layer.content {
+ LayerContent::Group(g) => {
+ let attrs = 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>");
+ }
+ 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 (rect, px) = self.pixels(layer);
+ let (rect, px) = if rect.is_empty() { (Rect::from_xywh(0, 0, 1, 1), vec![[0.0; 4]]) } else { (rect, px) };
+ 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));
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+pub(crate) fn export(doc: &Document) -> Result<ExportResult> {
+ if !matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale) {
+ return Err(IoError::Unsupported("OpenRaster holds RGB layers; convert the document to RGB or Grayscale first".into()));
+ }
+ let sample = match doc.depth {
+ 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() };
+ if doc.depth == SampleType::F32 {
+ w.warnings.note("32-bit float layers are saved as 16-bit PNGs");
+ }
+ 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, mut warnings, .. } = w;
+ zip.add("stack.xml", xml.as_bytes())?;
+ let merged = photocraft_compose::flatten(doc);
+ zip.add("mergedimage.png", &png(doc.size.width, doc.size.height, &merged.px, sample)?)?;
+ 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())?)?;
+ if !doc.channels.is_empty() {
+ warnings.note("alpha channels are not saved to OpenRaster");
+ }
+ if !doc.metadata.text.is_empty() || doc.metadata.xmp.is_some() || doc.metadata.exif.is_some() {
+ warnings.note("metadata (XMP, EXIF, text) is not saved to OpenRaster");
+ }
+ if doc.icc_profile.is_some() {
+ warnings.note("the colour profile is not saved to OpenRaster; readers assume sRGB");
+ }
+ if doc.mode == ColorMode::Grayscale {
+ warnings.note("grayscale layers are saved as RGB");
+ }
+ Ok(ExportResult { bytes: zip.finish()?, warnings: warnings.finish() })
+}
diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs
new file mode 100644
index 000000000..6f8c79c9b
--- /dev/null
+++ b/crates/io/src/ora/tests.rs
@@ -0,0 +1,348 @@
+use super::*;
+use photocraft_doc::{Adjustment, Color, Fill, LayerMask};
+
+const CANVAS: Size = Size { width: 70, height: 50 };
+
+fn px(fmt: PixelFormat, rgba: [f32; 4]) -> Vec<u8> {
+ let mut out = vec![0; fmt.bytes_per_pixel()];
+ photocraft_raster::encode_pixel(&fmt, &rgba, &mut out);
+ out
+}
+
+/// A raster layer holding a `w`x`h` block at (`x`, `y`) of a colour ramp in `fmt`.
+fn block(name: &str, fmt: PixelFormat, x: i32, y: i32, w: u32, h: u32, seed: u32) -> Layer {
+ let mut s = Surface::new(fmt);
+ let mut data = Vec::new();
+ for j in 0..h {
+ for i in 0..w {
+ let v = |k: u32| ((i * 7 + j * 13 + k * 29 + seed * 31) % 256) as f32 / 255.0;
+ data.extend(px(fmt, [v(0), v(1), v(2), 0.25 + 0.75 * v(3)]));
+ }
+ }
+ s.write_interleaved(Rect::from_xywh(x, y, w, h), &data);
+ Layer::new(name, LayerContent::Raster(s))
+}
+
+fn doc(depth: SampleType) -> Document {
+ let fmt = PixelFormat::new(ColorMode::Rgb, depth, true);
+ let mut d = Document::new("t.ora", CANVAS, ColorMode::Rgb, depth);
+ let mut base = block("Base", fmt, 0, 0, 70, 50, 1);
+ base.locks.transparency = true;
+ let mut off = block("Off canvas", fmt, -12, 30, 40, 30, 2);
+ off.blend = BlendMode::Multiply;
+ off.opacity = 0.5;
+ let mut hidden = block("Hidden", fmt, 10, 10, 5, 5, 3);
+ hidden.visible = false;
+ let mut inner = block("Inner screen", fmt, 20, 5, 30, 20, 4);
+ inner.blend = BlendMode::Screen;
+ let mut group = Layer::group("Isolated", vec![inner, block("Inner plain", fmt, 5, 5, 8, 8, 5)]);
+ group.blend = BlendMode::Overlay;
+ group.opacity = 0.75;
+ let mut through_child = block("Through child", fmt, 40, 20, 25, 25, 6);
+ through_child.blend = BlendMode::LinearLight;
+ through_child.locks.all = true;
+ let through = Layer::group("Pass <&> \"through\"", vec![through_child]);
+ d.layers = vec![base, off, hidden, group, through];
+ d
+}
+
+fn round_trip(d: &Document) -> (Document, Vec<String>, Vec<String>) {
+ let out = export(d).unwrap();
+ let back = crate::import("back.ora", &out.bytes).unwrap();
+ (back.document, out.warnings, back.warnings)
+}
+
+/// Layer trees equal in what OpenRaster stores.
+fn assert_same(a: &[Layer], b: &[Layer]) {
+ assert_eq!(a.len(), b.len());
+ for (a, b) in a.iter().zip(b) {
+ assert_eq!(a.name, b.name);
+ assert_eq!(a.visible, b.visible, "{}", a.name);
+ assert_eq!(a.blend, b.blend, "{}", a.name);
+ assert!((a.opacity - b.opacity).abs() < 1e-6, "{}", a.name);
+ assert_eq!(a.locks.all, b.locks.all, "{}", a.name);
+ assert_eq!(a.locks.transparency, b.locks.transparency, "{}", a.name);
+ match (&a.content, &b.content) {
+ (LayerContent::Raster(x), LayerContent::Raster(y)) => {
+ let r = x.content_bounds();
+ assert_eq!(r, y.content_bounds(), "{}", a.name);
+ assert_eq!(x.to_interleaved(r), y.to_interleaved(r), "{}", a.name);
+ }
+ (LayerContent::Group(x), LayerContent::Group(y)) => assert_same(&x.children, &y.children),
+ _ => panic!("layer kinds differ for {}", a.name),
+ }
+ }
+}
+
+#[test]
+fn layers_groups_and_properties_round_trip_at_8_and_16_bit() {
+ for depth in [SampleType::U8, SampleType::U16] {
+ let d = doc(depth);
+ let (back, export_warnings, import_warnings) = round_trip(&d);
+ assert!(export_warnings.is_empty(), "{export_warnings:?}");
+ assert!(import_warnings.is_empty(), "{import_warnings:?}");
+ assert_eq!(back.size, d.size);
+ assert_eq!(back.depth, depth);
+ assert_same(&d.layers, &back.layers);
+ assert_eq!(photocraft_compose::flatten(&d).px, photocraft_compose::flatten(&back).px);
+ }
+}
+
+#[test]
+fn float_documents_save_as_16_bit() {
+ let mut d = doc(SampleType::U16);
+ d.depth = SampleType::F32;
+ let fmt = PixelFormat::RGBA32F;
+ d.layers = vec![block("Float", fmt, 0, 0, 10, 10, 9)];
+ let (back, warnings, _) = round_trip(&d);
+ assert!(warnings.iter().any(|w| w.contains("16-bit")), "{warnings:?}");
+ assert_eq!(back.depth, SampleType::U16);
+ let (a, b) = (photocraft_compose::flatten(&d), photocraft_compose::flatten(&back));
+ let err = a.px.iter().zip(&b.px).flat_map(|(p, q)| (0..4).map(move |c| (p[c] - q[c]).abs())).fold(0.0f32, f32::max);
+ assert!(err < 1.0 / 65535.0 + 1e-6, "{err}");
+}
+
+#[test]
+fn every_blend_mode_is_written_or_reported() {
+ for mode in BlendMode::layer_modes() {
+ let mut d = Document::new("m.ora", CANVAS, ColorMode::Rgb, SampleType::U8);
+ let mut l = block("L", PixelFormat::RGBA8, 0, 0, 4, 4, 0);
+ l.blend = mode;
+ d.layers.push(l);
+ let (back, warnings, import_warnings) = round_trip(&d);
+ let got = back.layers.first().map(|l| l.blend);
+ if op_name(mode).is_some() {
+ assert_eq!(got, Some(mode), "{mode:?}");
+ assert!(warnings.is_empty(), "{mode:?}: {warnings:?}");
+ } else {
+ assert_eq!(got, Some(BlendMode::Normal), "{mode:?}");
+ assert!(warnings.iter().any(|w| w.contains("no OpenRaster equivalent")), "{mode:?}");
+ }
+ // Xor round-trips through nothing; the approximations only warn on import.
+ let _ = import_warnings;
+ }
+}
+
+#[test]
+fn masks_are_applied_to_pixels_and_reported() {
+ let mut d = Document::new("m.ora", CANVAS, ColorMode::Rgb, SampleType::U8);
+ let mut l = block("Masked", PixelFormat::RGBA8, 0, 0, 20, 20, 0);
+ let mut mask = LayerMask::hide_all();
+ mask.surface.fill_rect(Rect::from_xywh(0, 0, 10, 20), &[1.0]);
+ l.mask = Some(mask);
+ d.layers.push(l);
+ let (back, warnings, _) = round_trip(&d);
+ assert!(warnings.iter().any(|w| w.contains("layer masks were applied")), "{warnings:?}");
+ let s = back.layers.first().and_then(Layer::surface).unwrap();
+ assert_eq!(s.content_bounds(), Rect::from_xywh(0, 0, 10, 20));
+ assert_eq!(photocraft_compose::flatten(&d).px, photocraft_compose::flatten(&back).px);
+}
+
+#[test]
+fn other_layer_kinds_are_rendered_or_left_out() {
+ let mut d = Document::new("k.ora", CANVAS, ColorMode::Rgb, SampleType::U8);
+ d.layers.push(block("Base", PixelFormat::RGBA8, 0, 0, 70, 50, 0));
+ d.layers.push(Layer::new("Solid", LayerContent::Fill(Fill::Solid(Color::rgb(0.2, 0.4, 0.6)))));
+ d.layers.push(Layer::new("Invert", LayerContent::Adjustment(Adjustment::Invert)));
+ let (back, warnings, _) = round_trip(&d);
+ assert_eq!(back.layers.len(), 2);
+ assert!(warnings.iter().any(|w| w.contains("fill layers are saved to OpenRaster as pixels")), "{warnings:?}");
+ assert!(warnings.iter().any(|w| w.contains("adjustment layers cannot be saved")), "{warnings:?}");
+ let solid = back.layers.get(1).and_then(Layer::surface).unwrap();
+ assert_eq!(solid.content_bounds(), back.bounds());
+}
+
+#[test]
+fn grayscale_saves_as_rgb_and_cmyk_is_refused() {
+ let mut g = Document::new("g.ora", CANVAS, ColorMode::Grayscale, SampleType::U8);
+ g.layers.push(block("Gray", PixelFormat::GRAYA8, 0, 0, 10, 10, 0));
+ let (back, warnings, _) = round_trip(&g);
+ assert!(warnings.iter().any(|w| w.contains("grayscale")), "{warnings:?}");
+ assert_eq!(back.mode, ColorMode::Rgb);
+ let c = Document::new("c.ora", CANVAS, ColorMode::Cmyk, SampleType::U8);
+ assert!(matches!(export(&c), Err(IoError::Unsupported(_))));
+}
+
+#[test]
+fn archive_layout_follows_the_specification() {
+ let out = export(&doc(SampleType::U8)).unwrap();
+ // A stored `mimetype` first, readable at a fixed offset.
+ assert_eq!(out.bytes.get(30..38), Some(&b"mimetype"[..]));
+ assert_eq!(out.bytes.get(38..54), Some(MIMETYPE));
+ assert!(is_ora(&out.bytes));
+ let zip = ZipReader::new(&out.bytes).unwrap();
+ for entry in ["stack.xml", "mergedimage.png", "Thumbnails/thumbnail.png"] {
+ assert!(zip.find(entry).is_some(), "{entry}");
+ }
+ let thumb = codecs::decode(&zip.read_by_name("Thumbnails/thumbnail.png", 1 << 20).unwrap()).unwrap();
+ assert!(thumb.dimensions().0 <= 256 && thumb.dimensions().1 <= 256);
+ let merged = codecs::decode(&zip.read_by_name("mergedimage.png", 1 << 20).unwrap()).unwrap();
+ assert_eq!(merged.dimensions(), (70, 50));
+ let xml = String::from_utf8(zip.read_by_name("stack.xml", 1 << 20).unwrap()).unwrap();
+ assert!(xml.contains("name=\"Pass &lt;&amp;&gt; &quot;through&quot;\""), "{xml}");
+ assert!(xml.contains("isolation=\"auto\""), "{xml}");
+ assert!(xml.contains("composite-op=\"krita:linear light\""), "{xml}");
+}
+
+/// An ORA archive from a hand-written stack.xml and named PNG entries.
+fn archive(stack: &str, images: &[(&str, Vec<u8>)]) -> Vec<u8> {
+ let mut z = ZipWriter::new();
+ z.add("mimetype", MIMETYPE).unwrap();
+ z.add("stack.xml", stack.as_bytes()).unwrap();
+ for (name, data) in images {
+ z.add(name, data).unwrap();
+ }
+ z.finish().unwrap()
+}
+
+fn solid_png(w: u32, h: u32, rgba: [u8; 4]) -> Vec<u8> {
+ let data = rgba.iter().copied().cycle().take((w * h * 4) as usize).collect();
+ codecs::encode(&Image::from_raw(w, h, ChannelLayout::Rgba, CSample::U8, data).unwrap(), Format::Png, &Default::default()).unwrap()
+}
+
+fn gray16_png(w: u32, h: u32) -> Vec<u8> {
+ let data = (0..w * h).flat_map(|i| ((i * 1000) as u16).to_ne_bytes()).collect();
+ codecs::encode(&Image::from_raw(w, h, ChannelLayout::Gray, CSample::U16, data).unwrap(), Format::Png, &Default::default()).unwrap()
+}
+
+#[test]
+fn reads_other_applications_stacks() {
+ // The shapes Krita, MyPaint and GIMP write: a root stack with attributes, `auto`
+ // isolation, svg:plus, krita: ids, unknown elements, fractional positions.
+ let xml = r#"<?xml version='1.0' encoding='UTF-8'?>
+<image version="0.0.3" w="8" h="6" xres="150" yres="150">
+ <stack opacity="1" name="root" isolation="isolate" composite-op="svg:src-over">
+ <layer name="Plus" src="data/a.png" x="2.4" y="1" composite-op="svg:plus" opacity="0.5" selected="true"/>
+ <stack name="Folder" isolation="auto" composite-op="krita:darker color">
+ <layer name="Inside" src="data/b.png" composite-op="krita:hard mix" visibility="hidden" alpha-preserve="true"/>
+ </stack>
+ <stack name="Through"><layer src="data/b.png"/></stack>
+ <text name="Caption">hello</text>
+ <layer name="Gray16" src="data/g.png" composite-op="svg:soft-light" edit-locked="true"/>
+ <layer name="Strange" src="data/a.png" composite-op="svg:dst-in"/>
+ <layer name="Lost" src="data/missing.png"/>
+ </stack>
+</image>"#;
+ let bytes =
+ archive(xml, &[("data/a.png", solid_png(3, 2, [255, 0, 0, 255])), ("data/b.png", solid_png(8, 6, [0, 0, 255, 128])), ("data/g.png", gray16_png(4, 4))]);
+ // Detected by content, whatever the name says.
+ let r = crate::import("no extension", &bytes).unwrap();
+ let d = &r.document;
+ assert_eq!((d.size.width, d.size.height, d.depth), (8, 6, SampleType::U16));
+ assert_eq!(d.resolution_dpi, 150.0);
+ let names: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).collect();
+ assert_eq!(names, ["Lost", "Strange", "Gray16", "Through", "Folder", "Plus"]);
+ let get = |n: &str| d.layers.iter().find(|l| l.name == n).unwrap();
+ let plus = get("Plus");
+ assert_eq!((plus.blend, plus.opacity), (BlendMode::LinearDodge, 0.5));
+ assert_eq!(plus.surface().unwrap().content_bounds(), Rect::from_xywh(2, 1, 3, 2));
+ let folder = get("Folder");
+ assert_eq!(folder.blend, BlendMode::DarkerColor, "a blend mode isolates an auto group");
+ let inside = folder.children().unwrap().first().unwrap();
+ assert!(!inside.visible && inside.locks.transparency);
+ assert_eq!(inside.blend, BlendMode::HardMix);
+ assert_eq!(get("Through").blend, BlendMode::PassThrough);
+ let gray = get("Gray16");
+ assert!(gray.locks.all);
+ assert_eq!(gray.blend, BlendMode::SoftLight);
+ assert_eq!(gray.surface().unwrap().format(), PixelFormat::RGBA16);
+ assert_eq!(get("Strange").blend, BlendMode::Normal);
+ assert!(get("Lost").surface().unwrap().content_bounds().is_empty());
+ let all = r.warnings.join("\n");
+ for needle in ["svg:dst-in", "<text>", "missing from the archive", "krita:hard mix", "svg:soft-light"] {
+ assert!(all.contains(needle), "{needle} not in {all}");
+ }
+}
+
+#[test]
+fn malformed_archives_fail_cleanly() {
+ let png = solid_png(2, 2, [1, 2, 3, 4]);
+ let ok = |s: &str| archive(s, &[("a.png", png.clone())]);
+ let cases: Vec<(&str, Vec<u8>)> = vec![
+ ("not a zip", b"definitely not a zip archive at all".to_vec()),
+ ("no stack", {
+ let mut z = ZipWriter::new();
+ z.add("mimetype", MIMETYPE).unwrap();
+ z.finish().unwrap()
+ }),
+ ("wrong mimetype", {
+ let mut z = ZipWriter::new();
+ z.add("mimetype", b"image/png").unwrap();
+ z.add("stack.xml", b"<image w='1' h='1'><stack/></image>").unwrap();
+ z.finish().unwrap()
+ }),
+ ("bad xml", ok("<image w='2' h='2'><stack>")),
+ ("wrong root", ok("<picture w='2' h='2'><stack/></picture>")),
+ ("no root stack", ok("<image w='2' h='2'/>")),
+ ("zero width", ok("<image w='0' h='2'><stack/></image>")),
+ ("fractional width", ok("<image w='2.5' h='2'><stack/></image>")),
+ ("huge canvas", ok("<image w='300000' h='300000'><stack/></image>")),
+ ("bad opacity", ok("<image w='2' h='2'><stack><layer src='a.png' opacity='lots'/></stack></image>")),
+ ("nan opacity", ok("<image w='2' h='2'><stack><layer src='a.png' opacity='NaN'/></stack></image>")),
+ ("far offset", ok("<image w='2' h='2'><stack><layer src='a.png' x='99999999999'/></stack></image>")),
+ ("not an image", archive("<image w='2' h='2'><stack><layer src='a.png'/></stack></image>", &[("a.png", b"garbage".to_vec())])),
+ ("not utf-8", archive("", &[]).into_iter().chain([]).collect()),
+ ];
+ for (what, bytes) in cases {
+ assert!(crate::import("x.ora", &bytes).is_err(), "{what}");
+ }
+ let deep = format!("<image w='2' h='2'><stack>{}{}</stack></image>", "<stack>".repeat(200), "</stack>".repeat(200));
+ assert!(matches!(crate::import("x.ora", &ok(&deep)), Err(IoError::Unsupported(_))));
+}
+
+#[test]
+fn layer_and_pixel_budgets_are_enforced() {
+ let many = format!("<image w='2' h='2'><stack>{}</stack></image>", "<stack/>".repeat(MAX_NODES + 1));
+ assert!(crate::import("x.ora", &archive(&many, &[])).is_err());
+ // A tiny PNG claiming a vast size is refused by the decoder limits, not allocated.
+ let big = solid_png(1, 1, [0; 4]);
+ let mut forged = big.clone();
+ if let Some(ihdr) = forged.get_mut(16..24) {
+ ihdr.copy_from_slice(&[0, 0, 0x75, 0x30, 0, 0, 0x75, 0x30]);
+ }
+ let xml = "<image w='2' h='2'><stack><layer src='a.png'/></stack></image>";
+ assert!(crate::import("x.ora", &archive(xml, &[("a.png", forged)])).is_err());
+}
+
+#[test]
+fn truncated_and_corrupted_files_never_panic() {
+ let bytes = export(&doc(SampleType::U8)).unwrap().bytes;
+ let step = (bytes.len() / 300).max(1);
+ for cut in (0..bytes.len()).step_by(step) {
+ let _ = crate::import("x.ora", bytes.get(..cut).unwrap_or_default());
+ }
+ let mut state = 0x9e37_79b9_u32;
+ for _ in 0..300 {
+ let mut b = bytes.clone();
+ for _ in 0..4 {
+ state ^= state << 13;
+ state ^= state >> 17;
+ state ^= state << 5;
+ let i = state as usize % b.len();
+ if let Some(byte) = b.get_mut(i) {
+ *byte ^= (state >> 24) as u8 | 1;
+ }
+ }
+ let _ = crate::import("x.ora", &b);
+ }
+}
+
+#[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);
+ let out = crate::export(&d, "picture.ORA", &Default::default()).unwrap();
+ assert!(is_ora(&out.bytes));
+ let back = crate::import("picture.ora", &out.bytes).unwrap();
+ assert!(!back.source_read_only);
+}
diff --git a/crates/io/tests/krita_corpus.rs b/crates/io/tests/krita_corpus.rs
new file mode 100644
index 000000000..cafbe2c71
--- /dev/null
+++ b/crates/io/tests/krita_corpus.rs
@@ -0,0 +1,87 @@
+//! Krita-authored oracles: OpenRaster (`.ora`) files whose archives carry
+//! Krita's own rendering of the layer stack (`mergedimage.png`). The files are generated by
+//! `tools/krita-oracles/generate.py` in https://github.com/storytold/photocraft-corpus and are
+//! not bundled. Run with
+//! `KRITA_TEST_DIR=<dir> cargo test -p photocraft-io --test krita_corpus -- --ignored --nocapture`.
+
+use std::path::{Path, PathBuf};
+
+fn files(dir: &Path, ext: &str) -> Vec<PathBuf> {
+ let mut out: Vec<PathBuf> =
+ std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().path()).filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext))).collect();
+ out.sort();
+ out
+}
+
+/// Krita's merged image, read straight out of the archive.
+fn merged(bytes: &[u8]) -> photocraft_doc::Document {
+ let zip = photocraft_format::zip::ZipReader::new(bytes).unwrap();
+ let png = zip.read_by_name("mergedimage.png", 1 << 28).unwrap();
+ photocraft_io::import("mergedimage.png", &png).unwrap().document
+}
+
+/// Largest premultiplied channel difference (0..1) between our composite and Krita's, and
+/// where it is (x, y, ours, Krita's).
+fn max_error(doc: &photocraft_doc::Document, oracle: &photocraft_doc::Document, tolerance: f32) -> (f32, f32, String) {
+ assert_eq!(doc.size, oracle.size);
+ let ours = photocraft_compose::flatten(doc);
+ let theirs = photocraft_compose::flatten(oracle);
+ let w = doc.size.width as usize;
+ let mut worst = (0.0f32, String::new());
+ let mut over = 0usize;
+ for (i, (a, b)) in ours.px.iter().zip(&theirs.px).enumerate() {
+ let e = (0..4).map(|c| if c == 3 { (a[3] - b[3]).abs() } else { (a[c] * a[3] - b[c] * b[3]).abs() }).fold(0.0f32, f32::max);
+ over += usize::from(e > tolerance);
+ if e > worst.0 {
+ let q = |p: &[f32; 4]| p.map(|v| (v * 255.0).round() as i32);
+ worst = (e, format!("at ({}, {}): ours {:?}, Krita {:?}", i % w, i / w, q(a), q(b)));
+ }
+ }
+ (worst.0, over as f32 / ours.px.len().max(1) as f32, worst.1)
+}
+
+/// Files whose difference is known: the file, the share of pixels allowed outside the tolerance,
+/// and why. Everything else must match within the tolerance everywhere.
+const KNOWN: &[(&str, f32, &str)] = &[
+ ("blend-darker_color.ora", 0.02, "Krita weighs the channels differently when it picks the darker colour; near-ties pick the other pixel"),
+ ("blend-lighter_color.ora", 0.02, "Krita weighs the channels differently when it picks the lighter colour; near-ties pick the other pixel"),
+ ("blend-hard_mix_photoshop.ora", 0.02, "a channel sum of exactly 1 goes up in Photoshop's Hard Mix (ours) and down in Krita's"),
+ ("depth-rgba-u16.ora", 1.0, "Krita blends this linear-light 16-bit document in linear light, but its ORA export stores sRGB 8-bit layers"),
+];
+
+fn run(ext: &str, tolerance: f32) {
+ let root = std::env::var_os("KRITA_TEST_DIR").expect("set KRITA_TEST_DIR");
+ let paths = files(Path::new(&root), ext);
+ assert!(!paths.is_empty(), "no .{ext} files found");
+ let (mut passed, mut failed) = (0, Vec::new());
+ for path in &paths {
+ let bytes = std::fs::read(path).unwrap();
+ let name = path.file_name().unwrap().to_string_lossy().into_owned();
+ let r = photocraft_io::import(&name, &bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
+ let (error, share, at) = max_error(&r.document, &merged(&bytes), tolerance);
+ // Saving as .pcraft keeps every imported layer exactly.
+ let native = photocraft_io::export(&r.document, "copy.pcraft", &Default::default()).unwrap();
+ assert_eq!(r.document.layers, photocraft_io::import("copy.pcraft", &native.bytes).unwrap().document.layers, "{name}");
+ let known = KNOWN.iter().find(|(n, ..)| *n == name);
+ eprintln!(
+ "{name}: {} layers, max error {:.2}/255 {at}{}{}",
+ r.document.layers.len(),
+ error * 255.0,
+ known.map(|(_, _, w)| format!(" ({:.1}% of pixels; known: {w})", share * 100.0)).unwrap_or_default(),
+ if r.warnings.is_empty() { String::new() } else { format!("\n warnings: {}", r.warnings.join("; ")) }
+ );
+ if error <= tolerance {
+ passed += 1;
+ } else if known.is_none_or(|(_, allowed, _)| share > *allowed) {
+ failed.push(format!("{name}: {:.2}/255 on {:.2}% of pixels", error * 255.0, share * 100.0));
+ }
+ }
+ eprintln!("{passed}/{} .{ext} files within {:.1}/255", paths.len(), tolerance * 255.0);
+ assert!(failed.is_empty(), "outside tolerance: {failed:#?}");
+}
+
+#[test]
+#[ignore = "requires KRITA_TEST_DIR with Krita-authored .ora files"]
+fn krita_ora_files_match_their_merged_image() {
+ run("ora", 3.0 / 255.0);
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index f73aae2d4..55ecd75a6 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -1038,7 +1038,7 @@ impl PhotocraftApp {
&& !photocraft_compose::blend_if_active(layer, st.doc.mode));
let ext = st.path.as_deref().and_then(|p| std::path::Path::new(p).extension()).map(|e| e.to_string_lossy().to_ascii_lowercase());
let writable = ext.is_some_and(|e| {
- matches!(e.as_str(), photocraft_format::EXTENSION | "psd" | "psb" | "tif" | "tiff")
+ matches!(e.as_str(), photocraft_format::EXTENSION | "psd" | "psb" | "tif" | "tiff" | "ora")
|| (plain_raster && photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write))
});
let suggested = match &st.path {
diff --git a/docs/ora.md b/docs/ora.md
new file mode 100644
index 000000000..ac83b847b
--- /dev/null
+++ b/docs/ora.md
@@ -0,0 +1,70 @@
+# OpenRaster documents
+
+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`
+entry, so an OpenRaster file with another extension still opens as one.
+
+## What is kept
+
+| | Open | Save |
+|---|---|---|
+| Pixel layers (any size and position, also off-canvas) | yes | yes, cropped to their pixels |
+| Groups, nested | yes | yes |
+| Pass-through groups | `isolation="auto"` without a blend mode | `isolation="auto"` |
+| Names, visibility, opacity | yes | yes |
+| Blend modes | the `svg:*` names, `svg:plus`, and Krita's `krita:*` names | `svg:*` where the spec has the mode, else `krita:*` (read back by Krita, Normal elsewhere) |
+| Locks | `edit-locked`, `alpha-preserve` | the same |
+| 8 and 16-bit | yes (the deepest layer sets the depth) | 8-bit documents as 8-bit PNGs, 16 and 32-bit as 16-bit PNGs |
+| Resolution | `xres` | `xres` and `yres` |
+| Merged image and thumbnail | not read (we render our own) | written (`mergedimage.png`, `Thumbnails/thumbnail.png`) |
+
+Saving reports what OpenRaster can't hold, layer by layer: pixel masks are applied to the
+layer's pixels, fill opacity is folded into the pixels, text, shape, fill and smart object layers
+are written as their rendered pixels, and adjustment layers, layer styles, vector masks,
+clipping, alpha channels, metadata and the colour profile are left out. Xor and Paint.NET's
+Color Burn and Color Dodge variants have no OpenRaster name and are saved as Normal. CMYK, Lab
+and other modes are refused with a message to convert first; Grayscale saves as RGB.
+
+OpenRaster elements other than `stack` and `layer` (MyPaint's text, for example), missing
+layer images and unknown composite operations open with a warning instead of failing the file.
+Krita's W3C Soft Light (`svg:soft-light`, `krita:soft_light_svg`) and its own Hard Mix open as
+Photoshop's Soft Light and Hard Mix, which differ slightly, also with a warning.
+
+## Limits and safety
+
+The reader takes the archive with the bounded ZIP reader of `photocraft-format` (no ZIP64,
+CRC-checked), parses `stack.xml` with `roxmltree` (16 MiB cap), and decodes each layer image
+through `photocraft-codecs` with size limits. Canvases are at most 300,000 px a side, at most
+8,192 layers and groups, nesting at most `MAX_GROUP_DEPTH` deep, and 1 GiB of decoded pixels in
+total. Malformed archives, XML, numbers and images return errors; truncated and corrupted files
+are covered by tests.
+
+## Verification
+
+Unit tests (`crates/io/src/ora/tests.rs`) round-trip layers, groups, pass-through, offsets,
+opacity, visibility, locks and every blend mode at 8 and 16 bit, check masks, rendered layer
+kinds, the archive layout and malformed input. `crates/automation/tests/openraster.rs` saves,
+reopens, edits and saves in place through the agent surface; the CLI test converts both ways.
+
+Real-file checks use Krita-authored oracles from
+[photocraft-corpus](https://github.com/storytold/photocraft-corpus) (`krita/`, made by
+`tools/krita-oracles/generate.py`). Each Krita file carries Krita's rendering of itself in
+`mergedimage.png`:
+
+```sh
+KRITA_TEST_DIR=/path/to/photocraft-corpus/krita cargo test -p photocraft-io --test krita_corpus -- --ignored --nocapture
+```
+
+2026-10-09, Krita 5.2.9: 30 of 34 `.ora` files render within 3/255 of Krita's merged image; the
+other four differ for known reasons listed in `crates/io/tests/krita_corpus.rs` (Krita's
+tie-break in Darker and Lighter Color, Hard Mix at a channel sum of exactly 1, and a
+linear-light 16-bit document that Krita blends in linear light). In the other direction,
+Krita opened every PhotoCraft re-export of those files and rendered 33 of them identically to
+its original; the exception is Photoshop's Soft Light, which is written as `svg:soft-light`.
+MyPaint and GIMP files have not been checked yet.
+
+Format reference: the [OpenRaster specification](https://www.openraster.org/). The reader and
+writer are written from the specification and from files Krita writes; no application code
+was used.
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 3fb52153c..520f0de0a 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -103,6 +103,7 @@ filled bar. This extends UI reachability and does not claim Photoshop-authored s
| Menu wiring | 626/626 menu items dispatch a command (`parity.md`) | high but shallow | Says nothing about behaviour. |
| PSD fidelity (rendering) | Corpus oracle 115/170 (68%): 30 differ, 26 have no usable reference, 1 import error. 2026-10-07: io corpus 146/170, psd-tools corpus 236/309 (was 229: Advanced Blending knockouts), Photoshop oracles 132/258 | medium | Push to 170/170 under way (effects/strokes, multi-instance effects, 16/32-bit and colour modes, references for skipped files). |
| PSD round trip | 169/169 re-import identically; every adjustment layer and blend mode round-trips | high (within corpus) | Floors in `crates/io/tests/corpus.rs`; raise, never lower. Corpora: `cargo xtask corpus --all` (ours: https://github.com/storytold/photocraft-corpus). |
+| OpenRaster read/write | 2026-10-09: 34 Krita 5.2.9-authored `.ora` files (27 blend modes, groups, pass-through, offsets, opacity, visibility, masks, 16-bit, gray) render within 3/255 of Krita's merged image (30) or differ for known reasons (4: Krita's lighter/darker-colour tie-break, Hard Mix at exactly 1, a linear-light 16-bit document); Krita re-opens our exports and renders them identically to its originals (33/34; Soft Light is written as `svg:soft-light`) | medium (one authoring app) | MyPaint and GIMP files untested. Masks are applied to pixels and layer styles dropped on save (reported). See [OpenRaster](ora.md). |
| Paint.NET import | 2026-10-09: 14/14 local PDN3 textures preserve editable layers exactly through `.pcraft` and render within 2.142/255 of full-size previews; a supplied 5.x document (1280×720, 11 layers) passes editing/history/native saves and matches its thumbnail within 0.418/255 mean; all 14 blend modes exercised synthetically | medium (limited corpus) | Import only; metadata omitted. More current-version files and full-size exports needed. See [PDN support](pdn.md). |
| Smart filters / text / effect shapes in PSDs | Measured on our Photoshop-authored set (https://github.com/storytold/photocraft-corpus, `corpus/photoshop`, 258 files): see the per-group floors in `crates/io/tests/corpus.rs` and `crates/engine/tests/photoshop_oracles.rs`. Smart objects and smart filters now survive PSD save and open (41 corpus files, 206 smart objects, round trip strict; Photoshop opens our exports with live filters); re-rendering Photoshop's smart filters with ours matches 5/30 (was 1/30) | low–medium | Remaining re-render gaps are filter maths (Gaussian/Motion Blur, Unsharp Mask, Emboss, Add Noise RNG) and bicubic placement. |
| Core editing (layers, masks, selections, adjustments, filters, transforms) | Broad engine coverage; many interaction bugs fixed after 0.2.0 (adjustment dialogs, Curves, crop, Move/Transform modifiers, gesture origin) | medium | Fixes not yet user-validated. |
diff --git a/packaging/linux/ai.storyteller.photocraft.desktop b/packaging/linux/ai.storyteller.photocraft.desktop
index f491187d7..d1fb15ce8 100644
--- a/packaging/linux/ai.storyteller.photocraft.desktop
+++ b/packaging/linux/ai.storyteller.photocraft.desktop
@@ -12,4 +12,4 @@ StartupNotify=false
StartupWMClass=photocraft
Categories=Graphics;2DGraphics;RasterGraphics;Photography;
Keywords=photo;image;editor;psd;layers;retouch;paint;
-MimeType=application/x-photocraft;image/x-paintnet;image/vnd.adobe.photoshop;image/x-psd;image/x-psb;image/png;image/jpeg;image/tiff;image/webp;image/gif;image/bmp;image/x-tga;image/x-icon;image/vnd.microsoft.icon;image/x-portable-anymap;image/x-portable-bitmap;image/x-portable-graymap;image/x-portable-pixmap;image/x-exr;image/vnd.radiance;image/avif;image/qoi;
+MimeType=application/x-photocraft;image/x-paintnet;image/openraster;image/vnd.adobe.photoshop;image/x-psd;image/x-psb;image/png;image/jpeg;image/tiff;image/webp;image/gif;image/bmp;image/x-tga;image/x-icon;image/vnd.microsoft.icon;image/x-portable-anymap;image/x-portable-bitmap;image/x-portable-graymap;image/x-portable-pixmap;image/x-exr;image/vnd.radiance;image/avif;image/qoi;
diff --git a/packaging/linux/ai.storyteller.photocraft.metainfo.xml.in b/packaging/linux/ai.storyteller.photocraft.metainfo.xml.in
index 0282e0f39..6fbba1351 100644
--- a/packaging/linux/ai.storyteller.photocraft.metainfo.xml.in
+++ b/packaging/linux/ai.storyteller.photocraft.metainfo.xml.in
@@ -63,6 +63,7 @@
<binary>photocraft</binary>
<mediatype>application/x-photocraft</mediatype>
<mediatype>image/x-paintnet</mediatype>
+ <mediatype>image/openraster</mediatype>
<mediatype>image/vnd.adobe.photoshop</mediatype>
<mediatype>image/x-psb</mediatype>
</provides>
diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in
index e927d73e6..5dec67ee2 100644
--- a/packaging/macos/Info.plist.in
+++ b/packaging/macos/Info.plist.in
@@ -72,6 +72,21 @@
<!-- Types macOS may not know; the system's own declaration wins when it has one. -->
<key>UTImportedTypeDeclarations</key>
<array>
+ <dict>
+ <key>UTTypeIdentifier</key>
+ <string>ai.storyteller.photocraft.ora</string>
+ <key>UTTypeDescription</key>
+ <string>OpenRaster Image</string>
+ <key>UTTypeConformsTo</key>
+ <array><string>public.data</string><string>public.image</string></array>
+ <key>UTTypeTagSpecification</key>
+ <dict>
+ <key>public.filename-extension</key>
+ <array><string>ora</string></array>
+ <key>public.mime-type</key>
+ <array><string>image/openraster</string></array>
+ </dict>
+ </dict>
<dict>
<key>UTTypeIdentifier</key>
<string>ai.storyteller.photocraft.pdn</string>
@@ -171,6 +186,7 @@
<string>public.avif</string>
<string>ai.storyteller.photocraft.qoi</string>
<string>ai.storyteller.photocraft.pdn</string>
+ <string>ai.storyteller.photocraft.ora</string>
</array>
</dict>
</array>
diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxs
index 847baf0f7..98dc1fdfd 100644
--- a/packaging/windows/photocraft.wxs
+++ b/packaging/windows/photocraft.wxs
@@ -102,6 +102,7 @@
<RegistryValue Root="HKLM" Key="Software\Classes\.psd\OpenWithProgids" Name="Photocraft.PhotoshopDocument" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\.psb\OpenWithProgids" Name="Photocraft.PhotoshopDocument" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\.pdn\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" />
+ <RegistryValue Root="HKLM" Key="Software\Classes\.ora\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\.png\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\.jpg\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\.jpeg\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" />
@@ -124,6 +125,7 @@
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".psd" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".psb" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".pdn" Value="" Type="string" />
+ <RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".ora" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".png" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".jpg" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".jpeg" Value="" Type="string" />