From 6f012b6621ac37d47f89eaae529669217e37007a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 04:48:37 -0800 Subject: [PATCH] File formats: .pcraft documents open and place as one image MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Open and File › Place read layered raster .pcraft documents through craft-doc and store them as one PNG, sized by the document's resolution. A placed file links like any image. - The image is the file's full-size composite when it has one. - Without one, the layers are combined at the canvas size when the document is RGB at 8 or 16 bits and every visible layer is a raster layer that blends Normal, with no clipping, layer effects, vector mask, frame, advanced blending or feathered layer mask. Hidden layers are not read, and an RGB ICC profile the document names is kept. - Otherwise the composite preview comes in at the canvas's size, and Open, Place, links.update, links.relink and links.replaceEmbedded warn when it has fewer pixels than the canvas, naming both sizes and why the layers were not combined. - A full-size composite or preview the file names but doesn't hold, can't decode or, for the full-size one, of another size than the canvas is an error. The Links commands decode the kept PNG before taking it. The import fuzz tests cover mutated bundles and manifests. --- Cargo.lock | 60 +++ Cargo.toml | 2 + crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/fileio.rs | 4 + crates/engine/src/cmd/fileio/formats.rs | 10 +- crates/engine/src/cmd/fileio/load.rs | 28 +- crates/engine/src/cmd/fileio/pcraftread.rs | 378 ++++++++++++++++++ .../engine/src/cmd/fileio/tests_pcraftread.rs | 326 +++++++++++++++ crates/engine/src/cmd/links.rs | 38 +- crates/engine/src/cmd/place.rs | 2 +- crates/engine/src/cmd/place/dcs.rs | 2 +- crates/engine/tests/import_fuzz.rs | 88 ++++ docs/file-format-parity.md | 1 + docs/mcp.md | 13 +- 14 files changed, 939 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/cmd/fileio/pcraftread.rs create mode 100644 crates/engine/src/cmd/fileio/tests_pcraftread.rs diff --git a/Cargo.lock b/Cargo.lock index 12572feaa3..d80bc87579 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -613,6 +613,19 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake3" +version = "1.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + [[package]] name = "block" version = "0.1.6" @@ -1106,6 +1119,15 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie-factory" version = "0.3.3" @@ -1452,6 +1474,22 @@ dependencies = [ "zbus", ] +[[package]] +name = "craft-doc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +dependencies = [ + "blake3", + "craft-ecproj-format", + "craft-pcraft-format", + "craft-vectorcraft-format", + "flate2", + "ruzstd", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1491,6 +1529,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ecproj-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-eps" version = "0.1.0" @@ -1784,6 +1832,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-pcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -8637,6 +8696,7 @@ dependencies = [ "chrono", "craft-cdr", "craft-codepage", + "craft-doc", "craft-docpath", "craft-image-codecs", "craft-jxl", diff --git a/Cargo.toml b/Cargo.toml index bb9fd22f7c..242abcfe87 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,8 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0 # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4d576cf153..2a3fa75fe6 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -43,6 +43,8 @@ vectorcraft-metafile = { workspace = true } vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } craft-cdr = { workspace = true } +# `.pcraft` documents opened and placed as images (cmd/fileio/pcraftread.rs). +craft-doc = { workspace = true } vectorcraft-scriptcheck = { workspace = true } vectorcraft-js = { workspace = true } # The commands' parameter schemas (schemas.rs). diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index e5515f0fe3..5f66067142 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -51,6 +51,8 @@ mod jp2read; mod metafile; mod naming; mod native; +mod pcraftread; +pub(crate) use pcraftread::is_pcraft; mod pcxread; pub mod pdf; mod pdfimport; @@ -264,6 +266,8 @@ mod tests_heifread; #[cfg(test)] mod tests_jp2read; #[cfg(test)] +mod tests_pcraftread; +#[cfg(test)] mod tests_pcxread; #[cfg(test)] mod tests_pxrread; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 6ee790d901..4fee998d8e 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -558,6 +558,9 @@ pub const FORMATS: &[Format] = &[ Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS }, // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), + // Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size + // composite, the layers combined, or the preview with a note. Exports don't write them. + reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -618,6 +621,7 @@ pub const OPEN_EXTS: &[&str] = &[ "cdr", "cdt", "cmx", + "pcraft", ]; /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to @@ -625,10 +629,11 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. -/// The packaging declares no type for HP-GL plot files or PICT pictures either. +/// The packaging declares no type for HP-GL plot files, PICT pictures or layered raster `.pcraft` +/// documents either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -718,6 +723,7 @@ pub const PLACE_EXTS: &[&str] = &[ "cdr", "cdt", "cmx", + "pcraft", "txt", "rtf", "docx", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 2b3613984a..1f322ee9b6 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -74,6 +74,9 @@ pub struct RasterImage { /// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd, /// [`psdread::clipping_path`]). pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>, + /// What the image leaves out of its file, for Open, Place and the Links commands to warn of: a + /// `.pcraft` document read as its reduced preview ([`super::pcraftread`]). + pub note: Option, } pub(super) fn err(e: impl std::fmt::Display) -> EngineError { @@ -92,6 +95,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if vectorcraft_affinity::is_affinity(bytes) { return format("affinity"); } + if super::pcraftread::is_pcraft(bytes) { + return format("pcraft"); + } if super::cdr::is_cdr(bytes) { // A template keeps its meaning from the extension. return by_name.filter(|f| f.id == "cdt").or_else(|| format("cdr")); @@ -566,6 +572,14 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result Ok(None) => (raster_doc(&title, bytes)?, vec![], false), Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false), }, + // A `.pcraft` document opens as its full-size image, its layers combined, or its preview + // with a note that says so. + "pcraft" => { + let mut img = raster_image(bytes)?; + img.blob = crate::cmd::links::readable_and_kept(img.blob, true, false)?; + let note = img.note.take(); + (image_doc(&title, img)?, note.into_iter().collect(), false) + } _ if format.raster => (raster_doc(&title, bytes)?, vec![], false), _ => return Err(err(format!("{} files can't be opened yet", format.label))), }; @@ -1136,8 +1150,11 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; /// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported /// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes -/// it) is read with that path. +/// it) is read with that path. A `.pcraft` document is read by [`super::pcraftread::image`]. pub fn raster_image(bytes: &[u8]) -> Result { + if super::pcraftread::is_pcraft(bytes) { + return super::pcraftread::image(bytes); + } let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); @@ -1321,7 +1338,7 @@ fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: } let blob = ImageBlob::new(mime, bytes); let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd)); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip }) + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip, note: None }) } /// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from @@ -1404,7 +1421,12 @@ pub(crate) fn preview_with_clip(mut blob: ImageBlob) -> ImageBlob { /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { - let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?; + image_doc(name, raster_image(bytes)?) +} + +/// [`raster_doc`] of an image already read. +fn image_doc(name: &str, img: RasterImage) -> Result { + let RasterImage { key, blob, width, height, ppi, clip, note: _ } = img; let (sx, sy) = crate::cmd::place::pt_per_px(ppi); let mut d = Document::new(width as f64 * sx, height as f64 * sy); let layer = d.layers[0].id; diff --git a/crates/engine/src/cmd/fileio/pcraftread.rs b/crates/engine/src/cmd/fileio/pcraftread.rs new file mode 100644 index 0000000000..40116bfa0a --- /dev/null +++ b/crates/engine/src/cmd/fileio/pcraftread.rs @@ -0,0 +1,378 @@ +//! `.pcraft` documents (a layered raster document in a ZIP bundle) for File › Open and File › +//! Place, read with craft-doc and stored as PNG. The image is, in this order: +//! +//! 1. the bundle's full-size composite, when its manifest names one; +//! 2. the canvas combined from its layers, when the document is RGB at 8 or 16 bits and every +//! visible layer is a raster layer that blends Normal ([`combine`]); +//! 3. otherwise its composite preview, with a note that names the preview's size, the canvas's +//! and why the layers were not combined, unless the preview is the canvas's size. +//! +//! A full-size composite or preview that the manifest names but the bundle does not hold, or that +//! does not decode, is an error, as is a full-size composite of another size than the canvas. The +//! image is sized by the document's resolution, so a preview places at the canvas's size (at +//! 1 ppi when that would take less). + +use std::fmt; + +use craft_doc::{Limits, RenditionKind, Samples}; +use serde::Deserialize; +use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor}; + +use super::super::Result; +use super::load::{MAX_RASTER_ALLOC, RasterImage, as_png, err, raster_image}; + +/// Whether `bytes` are a `.pcraft` bundle: a ZIP archive holding the manifest craft-doc reads. +pub(crate) fn is_pcraft(bytes: &[u8]) -> bool { + craft_doc::sniff(bytes).is_some_and(|kind| kind.extension() == "pcraft") +} + +/// The image of `.pcraft` bundle `bytes` (see the module documentation), with +/// [`RasterImage::note`] saying so when only a preview smaller than the canvas was read. +pub(super) fn image(bytes: &[u8]) -> Result { + let limits = limits(); + let canvas: Canvas = craft_doc::pcraft_document(bytes, &limits).map_err(err)?; + let (w, h) = (canvas.size.width, canvas.size.height); + if w == 0 || h == 0 { + return Err(err(format!("the .pcraft document's canvas of {w} × {h} pixels is empty"))); + } + let composite = craft_doc::rendition(bytes, RenditionKind::Composite, &limits).map_err(err)?; + if let Some(full) = composite.as_ref().filter(|c| c.is_full_composite) { + let img = stored_png(&full.bytes, canvas.ppi(), "full-size image")?; + if (img.width, img.height) != (w, h) { + return Err(err(format!("the .pcraft document's full-size image is {} × {} pixels, not {w} × {h} as its canvas", img.width, img.height))); + } + return Ok(img); + } + let reason = match combine(bytes, &canvas, &limits)? { + Ok(img) => return Ok(img), + Err(reason) => reason, + }; + let Some(preview) = composite else { + return Err(err(format!("the .pcraft document has no full-size image or preview, and its layers can't be combined: {reason}"))); + }; + let (pw, ph) = vectorcraft_doc::header_size(&preview.bytes).ok_or_else(|| err("the .pcraft document's preview isn't a PNG image"))?; + // The preview covers the canvas: its resolution is the document's (72 ppi without a usable + // one) scaled by its size, and at least 1 ppi, the least a stored image's resolution reads as. + let (x, y) = canvas.ppi().unwrap_or((72.0, 72.0)); + let ppi = ((x * f64::from(pw) / f64::from(w)).max(1.0), (y * f64::from(ph) / f64::from(h)).max(1.0)); + let mut img = stored_png(&preview.bytes, Some(ppi), "preview")?; + let reduced = (img.width, img.height) != (w, h); + let (pw, ph) = (img.width, img.height); + img.note = reduced.then(|| format!("only the {pw} × {ph} preview of this {w} × {h} pixel .pcraft document was read: {reason}")); + Ok(img) +} + +/// The limits of one read: the decoded allowance for an entry, and twice that for everything one +/// call reads and decodes. +fn limits() -> Limits { + let mut limits = Limits::default(); + limits.max_entry = MAX_RASTER_ALLOC; + limits.max_total = MAX_RASTER_ALLOC.saturating_mul(2); + limits +} + +/// PNG `png` from the bundle (its `what`) as a stored image whose PNG records resolution `ppi`. The +/// image's resolution is the one read back from the PNG, as the Links commands read it later. +fn stored_png(png: &[u8], ppi: Option<(f64, f64)>, what: &str) -> Result { + if craft_image_codecs::detect(png) != Some(craft_image_codecs::Format::Png) { + return Err(err(format!("the .pcraft document's {what} isn't a PNG image"))); + } + match ppi { + Some(r) => raster_image(&super::ppi::with_png_resolution(png, r)), + None => raster_image(png), + } +} + +/// The document members that size the image and decide whether its layers can be combined. +#[derive(Deserialize)] +struct Canvas { + size: Size, + resolution_dpi: f32, + mode: String, + depth: String, + #[serde(default)] + icc_profile: Option, +} + +#[derive(Deserialize)] +struct Size { + width: u32, + height: u32, +} + +impl Canvas { + /// The document's resolution, when it is a usable one. + fn ppi(&self) -> Option<(f64, f64)> { + let dpi = f64::from(self.resolution_dpi); + (dpi.is_finite() && (1.0..=100_000.0).contains(&dpi)).then_some((dpi, dpi)) + } +} + +/// The document's layers, bottom first. +#[derive(Deserialize)] +struct Layers { + layers: Vec, +} + +/// The members of a layer that change how it draws. Members that don't (its name, locks, label, +/// id, links, XMP and the blocks kept for PSD files) are skipped; any other member is kept in +/// `unknown`, so a layer with a setting this reader doesn't know is not combined. +#[derive(Default)] +struct Layer { + visible: bool, + blend: String, + opacity: f32, + fill_opacity: f32, + clipped: bool, + mask: Option, + vector_mask: Option, + effects: Option, + kind: String, + frame: bool, + advanced_blending: bool, + unknown: Option, +} + +#[derive(Deserialize)] +struct Mask { + enabled: bool, + density: f32, + feather: f32, +} + +#[derive(Deserialize)] +struct Toggle { + #[serde(default = "yes")] + enabled: bool, +} + +fn yes() -> bool { + true +} + +#[derive(Deserialize)] +struct Effects { + #[serde(default)] + enabled: bool, + #[serde(default)] + items: Vec, +} + +/// A layer's `content`: its kind. A group's children are skipped: a visible group is not combined. +#[derive(Deserialize)] +struct Content { + kind: String, +} + +impl<'de> Deserialize<'de> for Layer { + fn deserialize>(d: D) -> std::result::Result { + struct LayerVisitor; + impl<'de> Visitor<'de> for LayerVisitor { + type Value = Layer; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a layer object") + } + + fn visit_map>(self, mut map: A) -> std::result::Result { + let mut l = Layer { fill_opacity: 1.0, ..Layer::default() }; + let (mut visible, mut blend, mut opacity, mut kind) = (None, None, None, None); + while let Some(key) = map.next_key::()? { + match key.as_str() { + "visible" => visible = Some(map.next_value()?), + "blend" => blend = Some(map.next_value()?), + "opacity" => opacity = Some(map.next_value()?), + "fill_opacity" => l.fill_opacity = map.next_value()?, + "clipped" => l.clipped = map.next_value()?, + "mask" => l.mask = map.next_value()?, + "vector_mask" => l.vector_mask = map.next_value()?, + "effects" => l.effects = map.next_value()?, + "content" => kind = Some(map.next_value::()?.kind), + "frame" => l.frame = map.next_value::>()?.is_some(), + "excluded_channels" => l.advanced_blending |= map.next_value::()? != 0, + "blend_if" | "advanced" => l.advanced_blending |= map.next_value::>()?.is_some(), + "id" | "name" | "locks" | "label" | "psd_blocks" | "psd_id" | "fill_cache" | "link_group" | "video" | "xmp" => { + map.next_value::()?; + } + _ => { + map.next_value::()?; + l.unknown.get_or_insert(key); + } + } + } + l.visible = visible.ok_or_else(|| serde::de::Error::missing_field("visible"))?; + l.blend = blend.ok_or_else(|| serde::de::Error::missing_field("blend"))?; + l.opacity = opacity.ok_or_else(|| serde::de::Error::missing_field("opacity"))?; + l.kind = kind.ok_or_else(|| serde::de::Error::missing_field("content"))?; + Ok(l) + } + } + d.deserialize_map(LayerVisitor) + } +} + +/// Why visible layer `l` can't be combined by [`combine`], or `None` when it can. +fn unsupported(l: &Layer) -> Option { + let unit = |v: f32| v.is_finite() && (0.0..=1.0).contains(&v); + if let Some(key) = &l.unknown { + return Some(format!("a visible layer has a setting this version doesn't read (`{key}`)")); + } + if l.kind != "raster" { + let kind = match l.kind.as_str() { + "group" => "a visible layer group", + "text" => "a visible type layer", + "shape" => "a visible shape layer", + "smart" => "a visible smart object", + "adjustment" => "a visible adjustment layer", + "fill" => "a visible fill layer", + _ => "a visible layer of a kind this version doesn't read", + }; + return Some(format!("the document has {kind}")); + } + let reason = if l.blend != "Normal" { + "a visible layer blends in a mode other than Normal" + } else if !unit(l.opacity) || !unit(l.fill_opacity) { + "a visible layer's opacity is out of range" + } else if l.clipped { + "a visible layer is clipped to the layer below it" + } else if l.effects.as_ref().is_some_and(|e| e.enabled && !e.items.is_empty()) { + "a visible layer has layer effects" + } else if l.vector_mask.as_ref().is_some_and(|v| v.enabled) { + "a visible layer has a vector mask" + } else if l.mask.as_ref().is_some_and(|m| m.enabled && (m.feather != 0.0 || !unit(m.density))) { + "a visible layer has a feathered layer mask" + } else if l.advanced_blending { + "a visible layer uses advanced blending options" + } else if l.frame { + "a visible layer has a frame" + } else { + return None; + }; + Some(reason.into()) +} + +/// The canvas of `.pcraft` bundle `bytes` combined from its layers, or why it can't be: the +/// document must be RGB at 8 or 16 bits, the canvas's pixels as 32-bit floating-point RGBA within +/// [`MAX_RASTER_ALLOC`], and each visible layer a raster layer that blends Normal at an opacity and +/// fill opacity between 0 and 1, with no clipping, layer effects, vector mask, frame or advanced +/// blending options, and a layer mask that is off or not feathered. Hidden layers are not read. +/// Each layer is laid over the layers below it as the straight-alpha Normal blend lays a source +/// over a backdrop, its alpha scaled by its opacity, its fill opacity and its layer mask (the mask +/// value scaled toward opaque by the mask's density). An RGB ICC profile the document names is +/// kept in the PNG; another profile is a reason not to combine. A visible layer without saved +/// pixels, or with samples other than 8 or 16 bits, is a reason too. +fn combine(bytes: &[u8], canvas: &Canvas, limits: &Limits) -> Result> { + let no = |reason: &str| Ok(Err(reason.to_string())); + if canvas.mode != "Rgb" { + return Ok(Err(format!("the document's color mode is {}, not RGB", canvas.mode))); + } + let deep = match canvas.depth.as_str() { + "U8" => false, + "U16" => true, + _ => return no("the document stores 32-bit samples"), + }; + let (w, h) = (canvas.size.width, canvas.size.height); + let pixels = u64::from(w) * u64::from(h); + if pixels.saturating_mul(16) > MAX_RASTER_ALLOC { + return no("the canvas is too large to combine its layers"); + } + let Layers { layers } = craft_doc::pcraft_document(bytes, limits).map_err(err)?; + let visible: Vec = layers.iter().enumerate().filter(|(_, l)| l.visible).map(|(i, _)| i).collect(); + if let Some(reason) = visible.iter().find_map(|&i| unsupported(&layers[i])) { + return Ok(Err(reason)); + } + let icc = match canvas.icc_profile { + Some(_) => craft_doc::pcraft_icc_profile(bytes, limits).map_err(err)?, + None => None, + }; + if icc.as_deref().is_some_and(|icc| vectorcraft_doc::cmyk::icc_color_space(icc) != Some(*b"RGB ")) { + return no("the document's color profile isn't an RGB profile"); + } + let n = usize::try_from(pixels).map_err(err)?; + let mut out = vec![[0.0f32; 4]; n]; + for i in visible { + let l = &layers[i]; + let Some(px) = craft_doc::pcraft_layer_rgba(bytes, &[i], limits).map_err(err)? else { + return no("a visible layer has no saved pixels"); + }; + if (px.width, px.height) != (w, h) || px.rgba.len() != n * 4 { + return Err(err("a layer of the .pcraft document doesn't cover its canvas")); + } + let Some(rgba) = Levels::of(&px.rgba) else { return no("a visible layer stores 32-bit samples") }; + let mask = match px.mask.as_ref().filter(|m| m.enabled) { + Some(m) => match Levels::of(&m.alpha).filter(|_| m.alpha.len() == n) { + Some(levels) => Some((levels, m.density)), + None => return no("a visible layer's mask stores 32-bit samples"), + }, + None => None, + }; + let opacity = l.opacity * l.fill_opacity; + for (p, b) in out.iter_mut().enumerate() { + let coverage = mask.as_ref().map_or(1.0, |(m, density)| 1.0 - density * (1.0 - m.at(p))); + let s = [rgba.at(p * 4), rgba.at(p * 4 + 1), rgba.at(p * 4 + 2), rgba.at(p * 4 + 3)]; + *b = over(*b, s, opacity * coverage); + } + } + let img: image::DynamicImage = if deep { + let samples = out.iter().flat_map(|p| level16(*p)).collect(); + image::ImageBuffer::from_raw(w, h, samples) + .map(image::DynamicImage::ImageRgba16) + .ok_or_else(|| err("the combined layers don't fit the canvas"))? + } else { + let samples = out.iter().flat_map(|p| level8(*p)).collect(); + image::ImageBuffer::from_raw(w, h, samples) + .map(image::DynamicImage::ImageRgba8) + .ok_or_else(|| err("the combined layers don't fit the canvas"))? + }; + drop(out); + as_png(img, icc, canvas.ppi()).map(Ok) +} + +/// 8- or 16-bit samples read as levels from 0 to 1. +enum Levels<'a> { + U8(&'a [u8]), + U16(&'a [u16]), +} + +impl<'a> Levels<'a> { + fn of(s: &'a Samples) -> Option { + match s { + Samples::U8(v) => Some(Levels::U8(v)), + Samples::U16(v) => Some(Levels::U16(v)), + _ => None, + } + } + + fn at(&self, i: usize) -> f32 { + match self { + Levels::U8(v) => v.get(i).map_or(0.0, |&v| f32::from(v) / 255.0), + Levels::U16(v) => v.get(i).map_or(0.0, |&v| f32::from(v) / 65535.0), + } + } +} + +/// Straight-alpha source `s` laid over backdrop `b` with the Normal blend, the source's alpha +/// scaled by `k`. +fn over(b: [f32; 4], s: [f32; 4], k: f32) -> [f32; 4] { + let sa = s[3] * k; + if sa <= 0.0 { + return b; + } + let kb = b[3] * (1.0 - sa); + let a = sa + kb; + if a <= 0.0 { + return [0.0; 4]; + } + let mix = |c: usize| (kb * b[c] + sa * s[c]) / a; + [mix(0), mix(1), mix(2), a] +} + +fn level8(p: [f32; 4]) -> [u8; 4] { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if p[3] <= 0.0 { [0; 4] } else { [q(p[0]), q(p[1]), q(p[2]), q(p[3])] } +} + +fn level16(p: [f32; 4]) -> [u16; 4] { + let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; + if p[3] <= 0.0 { [0; 4] } else { [q(p[0]), q(p[1]), q(p[2]), q(p[3])] } +} diff --git a/crates/engine/src/cmd/fileio/tests_pcraftread.rs b/crates/engine/src/cmd/fileio/tests_pcraftread.rs new file mode 100644 index 0000000000..444ba06606 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_pcraftread.rs @@ -0,0 +1,326 @@ +//! Reading `.pcraft` documents built here from scratch (a hand-written manifest, PNG previews +//! encoded here and layers whose surfaces are one default pixel, in a stored ZIP archive): the +//! full-size composite is the image when the bundle has one; otherwise visible Normal raster layers +//! are combined at the canvas's size; otherwise the preview is read, with a note when it is smaller +//! than the canvas. Damaged and unreadable bundles are refused with a message. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use super::*; + +/// A surface of one `pixel` (hex of its bytes) everywhere, in `sample` (U8 or U16). +fn surface(sample: &str, mode: &str, alpha: bool, pixel: &str) -> String { + format!(r#"{{"format":{{"mode":"{mode}","sample":"{sample}","alpha":{alpha}}},"default":"{pixel}","tiles":[]}}"#) +} + +/// An 8-bit RGBA surface of one pixel everywhere. +fn rgba8(p: [u8; 4]) -> String { + surface("U8", "Rgb", true, &p.iter().map(|b| format!("{b:02x}")).collect::()) +} + +/// Effects that are on, with none in the list. +const NO_EFFECTS: &str = r#"{"enabled":true,"items":[],"psd_raw":null}"#; + +/// A layer: `visible`, `blend`, `opacity`, `content`, its `mask` and `effects` (JSON), and `extra` +/// members (each `,"key":value`). +fn layer_with(visible: bool, blend: &str, opacity: f32, content: &str, mask: &str, effects: &str, extra: &str) -> String { + format!( + r#"{{"id":1,"name":"L","visible":{visible},"locks":{{}},"blend":"{blend}","opacity":{opacity},"fill_opacity":1.0,"clipped":false, + "mask":{mask},"effects":{effects},"label":"None","content":{content},"psd_blocks":[],"psd_id":null,"fill_cache":null{extra}}}"# + ) +} + +/// [`layer_with`] without a mask or effects. +fn layer(visible: bool, blend: &str, opacity: f32, content: &str, extra: &str) -> String { + layer_with(visible, blend, opacity, content, "null", NO_EFFECTS, extra) +} + +fn raster(surface: &str) -> String { + format!(r#"{{"kind":"raster","surface":{surface}}}"#) +} + +/// A visible Normal raster layer of `pixel` at `opacity`. +fn plain(pixel: [u8; 4], opacity: f32) -> String { + layer(true, "Normal", opacity, &raster(&rgba8(pixel)), "") +} + +/// A `w` × `h` PNG of `pixel`. +fn png(w: u32, h: u32, pixel: [u8; 4]) -> Vec { + let mut out = vec![]; + image::RgbaImage::from_pixel(w, h, image::Rgba(pixel)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// What a test bundle holds besides its layers. +struct Bundle<'a> { + size: (u32, u32), + dpi: f32, + depth: &'a str, + version: u32, + layers: Vec, + /// The full-size composite's entry, when the manifest names it (`None` bytes: not in the archive). + full: Option>>, + /// The preview's entry, likewise. + preview: Option>>, +} + +impl Bundle<'_> { + fn new(layers: Vec) -> Self { + Bundle { size: (300, 200), dpi: 150.0, depth: "U8", version: 1, layers, full: None, preview: Some(Some(png(30, 20, [9, 9, 9, 255]))) } + } + + fn bytes(&self) -> Vec { + let (w, h) = self.size; + let named = |m: &Option>>, path: &str| if m.is_some() { format!(r#""{path}""#) } else { "null".into() }; + let mut manifest = format!( + r#"{{"format_version":{},"generator":"test 0.1.0", + "document":{{"id":1,"name":"Untitled","size":{{"width":{w},"height":{h}}},"resolution_dpi":{},"mode":"Rgb","depth":"{}", + "icc_profile":null,"layers":[{}],"channels":[],"guides":{{}},"selection":null,"metadata":{{}},"global_light":{{}}}}, + "thumbnail":null,"composite":{}"#, + self.version, + self.dpi, + self.depth, + self.layers.join(","), + named(&self.preview, "composite/preview.png"), + ); + if self.full.is_some() { + manifest.push_str(r#","full_composite":"composite/full.png""#); + } + manifest.push('}'); + let mut files: Vec<(&str, Vec)> = vec![("manifest.json", manifest.into_bytes())]; + if let Some(Some(b)) = &self.preview { + files.push(("composite/preview.png", b.clone())); + } + if let Some(Some(b)) = &self.full { + files.push(("composite/full.png", b.clone())); + } + super::zip::store(&files).unwrap() + } +} + +/// Place `file` (named `art.pcraft`) in a new document: the reply and the placed image's (natural +/// width in points, its stored pixels). +fn place(file: &[u8]) -> (Value, f64, image::DynamicImage) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + let r = s.execute("file.place", &json!({"name": "art.pcraft", "dataBase64": vectorcraft_format::base64_encode(file)})).unwrap(); + let doc = &s.doc().unwrap().doc; + let node = doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let NodeKind::Image(im) = &node.kind else { panic!("an image, got {:?}", node.kind) }; + let width = node.geometric_bounds().map(|b| b.width()).unwrap(); + let pixels = image::load_from_memory(&doc.images[&im.key].bytes).unwrap(); + (r, width, pixels) +} + +fn warnings(r: &Value) -> Vec { + r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect() +} + +fn place_error(file: &[u8]) -> String { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + s.execute("file.place", &json!({"name": "art.pcraft", "dataBase64": vectorcraft_format::base64_encode(file)})).unwrap_err().to_string() +} + +#[test] +fn the_full_size_composite_is_placed_rather_than_the_layers_or_the_preview() { + // The red layer could be combined, and the preview the manifest names is not in the archive. + let mut b = Bundle::new(vec![plain([255, 0, 0, 255], 1.0)]); + b.full = Some(Some(png(300, 200, [0, 200, 0, 255]))); + b.preview = Some(None); + let file = b.bytes(); + assert!(super::pcraftread::is_pcraft(&file)); + assert_eq!(detect("art.zip", &file).map(|f| f.id), Some("pcraft"), "by its content"); + let (r, width, pixels) = place(&file); + assert_eq!(r["format"], "pcraft"); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!((pixels.width(), pixels.height()), (300, 200)); + assert_eq!(pixels.to_rgba8().get_pixel(5, 5).0, [0, 200, 0, 255]); + // Sized by the document's resolution: 300 px at 150 ppi are 144 pt (the PNG keeps the + // resolution in whole pixels per meter). + assert!((width - 144.0).abs() < 0.5, "{width}"); +} + +#[test] +fn visible_normal_raster_layers_are_combined_at_the_canvas_size() { + let file = Bundle::new(vec![ + plain([255, 0, 0, 255], 1.0), + // Half its alpha and half its opacity: a quarter over the red. + plain([0, 0, 255, 128], 0.5), + // Hidden layers draw nothing, whatever they are. + layer(false, "Normal", 1.0, &raster(&rgba8([0, 255, 0, 255])), ""), + layer(false, "Screen", 1.0, r#"{"kind":"text","text":"A","cache":null}"#, r#","advanced":{"knockout":"deep"}"#), + ]) + .bytes(); + let (r, width, pixels) = place(&file); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!((pixels.width(), pixels.height()), (300, 200), "the canvas's size, not the 30 × 20 preview's"); + let [red, green, blue, alpha] = pixels.to_rgba8().get_pixel(150, 100).0; + assert!(red > blue && blue > 0 && green == 0 && alpha == 255, "{:?}", [red, green, blue, alpha]); + assert!((width - 144.0).abs() < 0.5, "{width}"); + + // A 16-bit document's layers combine into 16-bit samples. + let mut b = Bundle::new(vec![layer(true, "Normal", 1.0, &raster(&surface("U16", "Rgb", true, "ffff000000000080")), "")]); + b.depth = "U16"; + let (_, _, pixels) = place(&b.bytes()); + assert!(matches!(pixels, image::DynamicImage::ImageRgba16(_)), "{:?}", pixels.color()); +} + +#[test] +fn a_layer_mask_hides_by_its_density_unless_it_is_off() { + // A mask that hides everything, at half density. + let mask = |enabled: bool, feather: f32| { + format!(r#"{{"surface":{},"enabled":{enabled},"linked":true,"density":0.5,"feather":{feather}}}"#, surface("U8", "Grayscale", false, "00")) + }; + let blue_at = |mask: &str| { + let top = layer_with(true, "Normal", 1.0, &raster(&rgba8([0, 0, 255, 255])), mask, NO_EFFECTS, ""); + let (r, _, pixels) = place(&Bundle::new(vec![plain([255, 0, 0, 255], 1.0), top]).bytes()); + (warnings(&r), pixels.to_rgba8().get_pixel(0, 0).0) + }; + let (w, [red, _, blue, _]) = blue_at(&mask(true, 0.0)); + assert!(w.is_empty() && red > 100 && blue > 100, "half hidden: {red} {blue}"); + let (w, [red, _, blue, _]) = blue_at(&mask(false, 0.0)); + assert!(w.is_empty() && red == 0 && blue == 255, "a mask that is off hides nothing: {red} {blue}"); + let (w, [red, ..]) = blue_at(&mask(true, 4.0)); + assert!(w.iter().any(|w| w.contains("feathered layer mask")) && red == 9, "a feathered mask leaves the preview: {w:?}"); +} + +#[test] +fn layers_that_cant_be_combined_leave_the_preview_with_a_note() { + let file = Bundle::new(vec![plain([255, 0, 0, 255], 1.0), layer(true, "Multiply", 1.0, &raster(&rgba8([0, 0, 255, 255])), "")]).bytes(); + let (r, width, pixels) = place(&file); + assert_eq!((pixels.width(), pixels.height()), (30, 20)); + let w = warnings(&r); + assert!(w.len() == 1 && w[0].contains("30 × 20 preview") && w[0].contains("300 × 200") && w[0].contains("Normal"), "{w:?}"); + // The preview covers the canvas, at the same size as the full image. + assert!((width - 144.0).abs() < 0.5, "{width}"); + + // Each other setting that changes how a layer draws leaves the preview too. + let pixels = raster(&rgba8([0; 4])); + let shadow = r#"{"enabled":true,"items":[{"DropShadow":{}}],"psd_raw":null}"#; + for (content, effects, extra, said) in [ + (pixels.as_str(), shadow, "", "layer effects"), + (&pixels, NO_EFFECTS, r#","blend_if":{"ranges":[1]}"#, "advanced blending"), + (&pixels, NO_EFFECTS, r#","excluded_channels":2"#, "advanced blending"), + (&pixels, NO_EFFECTS, r#","vector_mask":{"enabled":true,"path":{}}"#, "vector mask"), + (&pixels, NO_EFFECTS, r#","frame":{"path":{}}"#, "frame"), + (&pixels, NO_EFFECTS, r#","a_new_setting":true"#, "a_new_setting"), + (r#"{"kind":"group","children":[],"expanded":true}"#, NO_EFFECTS, "", "layer group"), + (r#"{"kind":"text","text":"A","cache":null}"#, NO_EFFECTS, "", "type layer"), + ] { + let l = layer_with(true, "Normal", 1.0, content, "null", effects, extra); + let (r, _, pixels) = place(&Bundle::new(vec![l]).bytes()); + let w = warnings(&r); + assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains(said), "{said}: {w:?}"); + } + + // A preview of the canvas's own size is not reduced, so nothing is said. + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + b.size = (30, 20); + let (r, _, pixels) = place(&b.bytes()); + assert!(warnings(&r).is_empty() && pixels.width() == 30, "{r}"); +} + +/// A linked preview keeps its size when it is read again: the resolution it was placed at is the +/// one its stored PNG gives back, at least 1 ppi when the canvas is far larger than the preview. +#[test] +fn a_linked_preview_keeps_its_size_when_it_is_updated() { + let dir = vectorcraft_testkit::TempDir::new("pcraft-preview-size"); + for (size, dpi) in [((300, 200), 150.0), ((300, 200), 72.0), ((3000, 2000), 10.0)] { + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + (b.size, b.dpi) = (size, dpi); + let path = dir.join("art.pcraft"); + std::fs::write(&path, b.bytes()).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let width = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().width(); + let placed = width(&s); + for preserve in ["transforms", "bounds"] { + s.execute("links.relink", &json!({"ids": [id.0], "path": path.to_string_lossy(), "preserve": preserve})).unwrap(); + s.execute("links.update", &json!({"ids": [id.0]})).unwrap(); + assert!((width(&s) - placed).abs() < 1e-6, "{size:?} at {dpi} ppi, {preserve}: {} then {placed}", width(&s)); + } + // The 30 px preview places at the canvas's width, or at 1 ppi when that would take less. + let ppi = (f64::from(dpi) * 30.0 / f64::from(size.0)).max(1.0); + assert!((placed - 30.0 * 72.0 / ppi).abs() < 0.5, "{size:?} at {dpi} ppi: {placed}"); + } +} + +#[test] +fn damaged_or_unreadable_bundles_are_refused() { + let multiply = || vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]; + // The full-size composite the manifest names is missing, or not the canvas's size: never the preview. + let mut b = Bundle::new(multiply()); + b.full = Some(None); + assert!(place_error(&b.bytes()).contains("composite/full.png")); + b.full = Some(Some(png(30, 20, [0; 4]))); + assert!(place_error(&b.bytes()).contains("not 300 × 200")); + b.full = Some(Some(b"not a png".to_vec())); + assert!(place_error(&b.bytes()).contains("isn't a PNG")); + // No preview and layers that can't be combined. + let mut b = Bundle::new(multiply()); + b.preview = None; + assert!(place_error(&b.bytes()).contains("no full-size image or preview")); + // A newer format version. + let mut b = Bundle::new(multiply()); + b.version = 99; + assert!(place_error(&b.bytes()).contains("newer")); +} + +#[test] +fn pcraft_files_open_and_place_linked_and_updates_read_them_again() { + let b64 = vectorcraft_format::base64_encode; + let red = Bundle::new(vec![plain([255, 0, 0, 255], 1.0)]).bytes(); + let blue = Bundle::new(vec![plain([0, 0, 255, 255], 1.0)]).bytes(); + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&red)})).unwrap(); + assert_eq!((&r["format"], &r["warnings"]), (&json!("pcraft"), &json!([])), "{r}"); + let multiply = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]).bytes(); + let r = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&multiply)})).unwrap(); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("preview")), "Open says so too: {r}"); + + let dir = vectorcraft_testkit::TempDir::new("pcraft-link"); + let path = dir.join("art.pcraft"); + std::fs::write(&path, &red).unwrap(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap(); + let id = r["ids"][0].as_u64().unwrap(); + let shown = |s: &Session| { + let doc = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &doc.node(NodeId(id)).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "linked"); + image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8().get_pixel(0, 0).0 + }; + assert_eq!(shown(&s), [255, 0, 0, 255]); + std::fs::write(&path, &blue).unwrap(); + s.execute("links.update", &json!({"ids": [id]})).unwrap(); + assert_eq!(shown(&s), [0, 0, 255, 255], "the update reads the file again"); + // A file that now has only its preview to show says so. + std::fs::write(&path, &multiply).unwrap(); + let r = s.execute("links.update", &json!({"ids": [id]})).unwrap(); + let w = warnings(&r); + assert!(w.len() == 1 && w[0].starts_with("art.pcraft: only the 30 × 20 preview"), "{r}"); + // A preview whose header reads but whose pixels don't is not taken: the link counts as missing. + let mut damaged = png(30, 20, [9, 9, 9, 255]); + let n = damaged.len(); + damaged[40..n - 12].fill(0xff); + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + b.preview = Some(Some(damaged)); + let damaged = b.bytes(); + let e = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&damaged)})).unwrap_err(); + assert!(e.to_string().contains("pixels can't be read"), "{e}"); + std::fs::write(&path, damaged).unwrap(); + let r = s.execute("links.update", &json!({"ids": [id]})).unwrap(); + assert_eq!(r["missing"], json!([id]), "{r}"); + let r = s.execute("links.replaceEmbedded", &json!({"ids": [id], "dataBase64": b64(&multiply)})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("preview")), "{r}"); + + // The dialogs list it; the desktop packaging doesn't associate it; nothing writes it. + assert!(OPEN_EXTS.contains(&"pcraft") && PLACE_EXTS.contains(&"pcraft") && UNASSOCIATED_EXTS.contains(&"pcraft")); + let r = s.execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pcraft").unwrap().clone(); + assert_eq!((f["read"].as_bool(), f["write"].as_bool()), (Some(true), Some(false))); +} diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 5a77b6d780..de6f945b58 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns; a .pcraft file read only as its reduced preview, after the file's name]}", has_doc, update ), @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Replace Image", [], None, - "{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}", + "{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids], warnings?: [a .pcraft document read only as its reduced preview]}", has_doc, replace_embedded ), @@ -636,11 +636,12 @@ pub(crate) fn store_image(d: &mut Document, key: &str, full: ImageBlob, linked: d.images.insert(key.to_string(), blob); } -/// Whether `bytes` are a PNG, JPEG, GIF or WebP file: the formats [`fileio::raster_image`] keeps -/// as they are after reading only their header. +/// Whether `bytes` are a PNG, JPEG, GIF or WebP file, the formats [`fileio::raster_image`] keeps +/// as they are after reading only their header, or a `.pcraft` document, whose full-size composite +/// or preview it keeps the same way. pub(crate) fn kept_unread(bytes: &[u8]) -> bool { use craft_image_codecs::Format as F; - matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP)) + matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP)) || fileio::is_pcraft(bytes) } /// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the @@ -1275,8 +1276,13 @@ fn replace_embedded(s: &mut Session, p: &Value) -> Result { let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?; let mut img = fileio::raster_image(&bytes)?; img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?; + let note = img.note.clone(); s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?; - Ok(json!({ "replaced": ids_json(&ids) })) + let mut out = json!({ "replaced": ids_json(&ids) }); + if let Some(note) = note { + out["warnings"] = json!([note]); + } + Ok(out) } /// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels @@ -2089,7 +2095,8 @@ fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) - } } let updated: Vec = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect(); - let warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read)); + let mut warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read)); + warnings.extend(file_notes(reads.iter().map(|(_, read)| read))); if !reads.is_empty() { s.edit("Update Links", |d, _| { editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g)))) @@ -2102,6 +2109,22 @@ fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) - Ok(out) } +/// The notes of the images in `reads` that leave part of their file out ([`RasterImage::note`], a +/// `.pcraft` document read as its reduced preview), each after its file's name, once per file. +fn file_notes<'a>(reads: impl Iterator) -> Vec { + let mut out: Vec = vec![]; + for read in reads { + let Read::Image((link, img)) = read else { continue }; + let Some(note) = &img.note else { continue }; + let name = Path::new(&link.path).file_name().map_or_else(|| link.path.clone(), |n| n.to_string_lossy().into_owned()); + let note = format!("{name}: {note}"); + if !out.contains(¬e) { + out.push(note); + } + } + out +} + /// The warnings for the spot plates of the DCS files in `reads` whose ink a swatch of `d` already /// names in another color, or as a process color ([`super::place::dcs::swatch_notes`]), or that an /// earlier file of `reads` adds as a spot swatch in another color, each once. @@ -2354,6 +2377,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { let unpreserved = preserve.and_then(|_| unpreserved_note(&doc, &reads)); drop(doc); let mut warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); + warnings.extend(file_notes(reads.iter().map(|(_, read)| read))); warnings.extend(unpreserved); if !reads.is_empty() { s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?; diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index d1c86a4f62..3e0a808fd5 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -329,7 +329,7 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o let (sx, sy) = pt_per_px(img.ppi); let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy); let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes)); - let mut warnings: Vec = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect(); + let mut warnings: Vec = unread.into_iter().chain(img.note.clone()).chain(fileio::size_note(&img.blob.bytes)).collect(); *slices_out = psd_slices(slices_from, natural, &mut warnings); let clip = img.clip.clone().map(|(path, _)| path); return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None }); diff --git a/crates/engine/src/cmd/place/dcs.rs b/crates/engine/src/cmd/place/dcs.rs index efa02e06a8..0c44e2f946 100644 --- a/crates/engine/src/cmd/place/dcs.rs +++ b/crates/engine/src/cmd/place/dcs.rs @@ -105,7 +105,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result { let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref()) .ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?; let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero)); - let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip }; + let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip, note: None }; let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect(); Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings }) } diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 636c19fb36..8e4364480b 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -10,6 +10,7 @@ //! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor //! `.cdr` drawings (mutated and cut short, plain, compressed and packaged, opened and placed), //! nor `.cmx` files (mutated, cut short and garbage after the header, opened and placed), +//! nor layered raster `.pcraft` documents (mutated and cut short archives and manifests, opened and placed), //! nor the font files a folder search reads (damaged fonts, collections whose headers give any count of //! faces), nor scripts written for the reference app checked without running them (garbage, //! generated script text and mutated scripts). @@ -480,6 +481,93 @@ proptest! { } } +// ---------- layered raster .pcraft documents ---------- + +/// A `.pcraft` manifest of a 40 × 30 canvas with two visible raster layers, one under a layer mask, +/// that can be combined, and a hidden one. +fn pcraft_manifest() -> String { + let surface = |mode: &str, pixel: &str| { + let alpha = mode == "Rgb"; + format!(r#"{{"format":{{"mode":"{mode}","sample":"U8","alpha":{alpha}}},"default":"{pixel}","tiles":[]}}"#) + }; + let layer = |visible: bool, pixel: &str, mask: &str| { + format!( + r#"{{"id":1,"name":"L","visible":{visible},"locks":{{}},"blend":"Normal","opacity":0.5,"fill_opacity":1.0,"clipped":false,"mask":{mask}, + "effects":{{"enabled":false,"items":[],"psd_raw":null}},"label":"None","content":{{"kind":"raster","surface":{}}}, + "psd_blocks":[],"psd_id":null,"fill_cache":null}}"#, + surface("Rgb", pixel) + ) + }; + let mask = format!(r#"{{"surface":{},"enabled":true,"linked":true,"density":0.75,"feather":0.0}}"#, surface("Grayscale", "40")); + format!( + r#"{{"format_version":1,"generator":"test 0.1.0","document":{{"id":1,"name":"U","size":{{"width":40,"height":30}},"resolution_dpi":72.0, + "mode":"Rgb","depth":"U8","icc_profile":null,"layers":[{},{},{}],"channels":[],"guides":{{}},"selection":null,"metadata":{{}}, + "global_light":{{}}}},"thumbnail":null,"composite":"composite/preview.png"}}"#, + layer(true, "ff000080", "null"), + layer(true, "0000ffff", &mask), + layer(false, "00ff00ff", "null"), + ) +} + +/// A `.pcraft` bundle of `manifest` with a 4 × 3 preview. +fn pcraft_bundle(manifest: &[u8]) -> Vec { + let mut preview = vec![]; + image::RgbaImage::new(4, 3).write_to(&mut std::io::Cursor::new(&mut preview), image::ImageFormat::Png).unwrap(); + vectorcraft_engine::cmd::fileio::zip::store(&[("manifest.json", manifest), ("composite/preview.png", &preview)]).unwrap() +} + +/// Open and place `.pcraft` file `bytes`: neither may panic. +fn pcraft_survives(what: &str, bytes: &[u8]) -> Result<(), TestCaseError> { + survive(what, || vectorcraft_engine::cmd::fileio::load("x.pcraft", bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.pcraft", "dataBase64":vectorcraft_format::base64_encode(bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "{what}: placement panicked: {:?}", r.err()); + Ok(()) +} + +#[test] +fn the_pcraft_sample_combines_its_layers() { + let l = vectorcraft_engine::cmd::fileio::load("x.pcraft", &pcraft_bundle(pcraft_manifest().as_bytes())).unwrap(); + assert!(l.warnings.is_empty(), "{:?}", l.warnings); + assert_eq!(l.doc.artboards[0].rect.width(), 40.0, "the canvas, not the preview"); +} + +proptest! { + #![proptest_config(config())] + + #[test] + fn pcraft_mutated_bundles_open_and_place( + cut in prop::option::of(4usize..4096), + edits in prop::collection::vec((0usize..8192, any::()), 0..24), + ) { + let mut bytes = pcraft_bundle(pcraft_manifest().as_bytes()); + let n = bytes.len(); + for (at, b) in edits { bytes[at % n] = b; } + if let Some(cut) = cut { + bytes.truncate(cut); + } + pcraft_survives(".pcraft bundle", &bytes)?; + } + + #[test] + fn pcraft_mutated_manifests_open_and_place( + cut in prop::option::of(1usize..2048), + edits in prop::collection::vec((0usize..4096, any::()), 1..16), + ) { + let mut manifest = pcraft_manifest().into_bytes(); + let n = manifest.len(); + for (at, b) in edits { manifest[at % n] = b; } + if let Some(cut) = cut { + manifest.truncate(cut); + } + pcraft_survives(".pcraft manifest", &pcraft_bundle(&manifest))?; + } +} + // ---------- Affinity documents with every feature the reader maps ---------- #[path = "support/affinity_docs.rs"] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 947ff99e89..9547365394 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -370,6 +370,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | WebP | export (Export for Screens) | yes | yes (lossless by default; `lossless: false` writes lossy WebP at `quality` 0–100, default 90) | lossy files are `VP8 `, with an `ALPH` chunk when some pixels are not opaque; `tests_text.rs` | | JPEG XL `.jxl` | — | yes (first frame; 16-bit and floating-point samples as 8 bits, alpha kept; CMYK refused) | no | decoded with jxl-oxide; the size is checked from the header before decoding; container Exif resolution sizes opened and placed images; tests in `crates/engine/src/cmd/fileio/tests_jxlread.rs` and `crates/engine/tests/import_fuzz.rs` | | HEIC / HEIF | open, place | yes (HEVC-coded still images: single pictures and grids of tiles, 8 to 10 bits, with an alpha image; image sequences, other codings and grids of cropped tiles are refused) | no | `.heic`, `.heif`; decoded by heic-rs in the engine's default `heif` feature (a build without it refuses the files with a message); the container's rotation, mirror and crop are applied; without an `nclx` box the HEVC stream's video signal type gives the matrix and range; an RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; EXIF resolution tags size the image, or 72 ppi; bounded decoding; `tests_heifread.rs` | +| Layered raster `.pcraft` | open, place | yes (as one image: the full-size composite when the file has one; else the layers combined at the canvas size when the document is RGB at 8 or 16 bits and every visible layer is a Normal raster layer without clipping, layer effects, a vector mask, a frame, advanced blending or a feathered layer mask; else the composite preview, with a warning when it is smaller than the canvas) | no | read with craft-doc; sized by the document's resolution, the preview at the canvas's size (at least 1 ppi); a linked file is read the same way again when it is updated; a missing or damaged full-size composite or preview is an error; `tests_pcraftread.rs` | | PCX | open, place | yes (1 bit in the header palette's first two colors, black and white without them; 1 bit in two to four planes and 4 bits with up to 16 colors; 2 bits in the CGA colors the header's CGA palette settings pick; 8 bits with the 256-color palette, gray without one; 24-bit color in three planes) | no | the header's HDpi and VDpi size the image; a file of another depth or plane count, cut short or past the pixel allowance is refused with a message; tests in `crates/engine/src/cmd/fileio/tests_pcxread.rs` and `crates/engine/tests/import_fuzz.rs` | | JPEG 2000 | open, place | yes (JP2 and raw codestream images; multiple codestreams and JPX composition or layers are refused) | no | `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c`, `.jpc`; resolution uses the valid `resd` (display) value on each axis, or else the valid `resc` (capture) value, or 72 ppi; bounded decoding; `tests_jp2read.rs` | | PICT | open, place (legacy) | yes (versions 1 and 2: shapes, lines, regions, text, bitmaps, pixel maps and QuickTime JPEG images; placed as one group clipped to the picture's frame) | no | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; a two-color pattern fills with its average color; inverted shapes, transfer modes other than a copy and QuickTime images in other formats come back as warnings; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs` and `crates/engine/tests/import_fuzz.rs` | diff --git a/docs/mcp.md b/docs/mcp.md index 8cb939c506..c93bb1dbbc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -758,7 +758,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). The app refuses `attributes.openUrl`, `file.export.svg.browser`, `file.saveForWeb.browser` and `file.showPackage` for every control and MCP request, since each opens another app, so the headless error for them does not suggest `--connect`. | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | +| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | @@ -12090,6 +12090,17 @@ or the embedded ICC profile describes one the decoder knows; other images with a samples as stored. CMYK files are refused, and an image past the pixel allowance is refused from its header, before its pixels are decoded. `file.place {path}` links the file like any image. VectorCraft doesn't write JPEG XL. +Layered raster `.pcraft` documents open and place as one image, stored as PNG and sized by the document's resolution. +The image is the file's full-size composite when it has one. Without one, the layers are combined at the canvas size +when the document is RGB at 8 or 16 bits and every visible layer is a raster layer that blends Normal, with no +clipping, layer effects, vector mask, frame, advanced blending options or feathered layer mask; hidden layers are not +read, and an RGB ICC profile the document names is kept. Otherwise the composite preview comes in at the canvas's +size (at 1 ppi when that would take less), and when it has fewer pixels than the canvas the reply's `warnings` name both sizes and why the layers were not +combined. A full-size composite or preview the file names but doesn't hold or can't be decoded is an error. +`file.place {path}` links the file like any image, and `links.update` and `links.relink` read it again the same way; +their `warnings`, and those of `links.replaceEmbedded`, say when only the preview was read. VectorCraft doesn't write +`.pcraft` files. + ```json {"name":"export","arguments":{"path":"/tmp/poster.psd","options":{"ppi":300,"maxEditability":true}}} {"name":"run_command","arguments":{"command":"document.export","params":{"format":"psd","layers":false,"colorModel":"cmyk"}}}