From b59f59a9c1e41b2ec99353d1a6af3907f781f5f0 Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Thu, 29 Oct 2026 17:57:03 -0400 Subject: [PATCH 1/8] PDF: spot channels as overprinting Separation plates (FILE-215-17) Save As / Save a Copy / file.saveACopy / doc.save to .pdf write every spot channel as an 8-bit Flate image XObject in a [/Separation / /DeviceCMYK ] colour space, painted after the flattened image in channel order with overprint on (/OP true /op true), so a RIP or Ghostscript's tiffsep/psdcmyk keeps each one as a named plate. 1 = solid ink, as the document stores it; the alternate is the ink colour separated to CMYK (preview only). A Multichannel document saves as its plates alone (an alpha-type channel as the black ink the composite shows, 1 - value). Each plate carries a 1-bit stencil mask so viewers without overprint preview still show every plate (a colour-key /Mask range renders blank in Quartz). No marks, labels, halftone screens or transparency. "pdfSpotPlates": false on scripted saves writes the image only. Tests: 5 new io pdf tests (structure, overprint and order, polarity, Multichannel, name escaping, stencil bits, opt-out, 16-bit) and an engine save_a_copy test for the param. Docs: file-format-parity, gaps G10, control-protocol. Co-Authored-By: Claude Fable 5.1 --- crates/automation/src/rpc.rs | 9 +- crates/automation/src/server.rs | 12 +- crates/engine/src/cmd/file_cmds.rs | 12 +- crates/engine/src/cmd/file_cmds/save.rs | 15 ++ crates/engine/src/cmd/file_cmds/tests.rs | 28 +++ crates/io/src/lib.rs | 7 +- crates/io/src/pdf.rs | 293 +++++++++++++++++++---- crates/io/src/pdf/tests.rs | 164 ++++++++++++- docs/control-protocol.md | 2 +- docs/file-format-parity.md | 7 +- docs/gaps.md | 8 +- 11 files changed, 482 insertions(+), 75 deletions(-) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 92ece2b943b..6b0fdf38386 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -126,8 +126,13 @@ impl Headless { "doc.new" => self.command_run("file.new", p), "doc.save" => { let tga_bits = photocraft_engine::file_cmds::tga_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; - let mut opts = - photocraft_io::ExportOptions { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits, ..Default::default() }; + let pdf_spot_plates = photocraft_engine::file_cmds::pdf_spot_plates_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; + let mut opts = photocraft_io::ExportOptions { + tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), + tga_bits, + pdf_spot_plates, + ..Default::default() + }; opts.encode.dpx_bits = photocraft_engine::file_cmds::dpx_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; opts.encode.dds = photocraft_engine::file_cmds::dds_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?.unwrap_or_default(); match p.get("quality") { diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 544dbc90f15..3a5b6505b6c 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -191,6 +191,10 @@ pub struct SaveParams { /// DDS: also write the full mip chain, each level a box filter of the one above. #[serde(default, rename = "ddsMipmaps")] pub dds_mipmaps: bool, + /// PDF: write the spot channels as overprinting Separation plates after the flattened image + /// (a Multichannel document as plates alone). On by default; false writes the image only. + #[serde(default, rename = "pdfSpotPlates")] + pub pdf_spot_plates: Option, #[serde(default)] pub index: Option, } @@ -1080,6 +1084,7 @@ impl PhotocraftMcp { p.quality.is_some().then_some("quality"), p.tiff_layers.then_some("tiffLayers"), dpx_bits.is_some().then_some("dpxBits"), + p.pdf_spot_plates.is_some().then_some("pdfSpotPlates"), p.index.is_some().then_some("index"), ] .into_iter() @@ -1105,7 +1110,12 @@ impl PhotocraftMcp { } let Some(r) = self .headless_op(move |h| { - let mut opts = photocraft_io::ExportOptions { tiff_layers: p.tiff_layers, tga_bits, ..Default::default() }; + let mut opts = photocraft_io::ExportOptions { + tiff_layers: p.tiff_layers, + tga_bits, + pdf_spot_plates: p.pdf_spot_plates.unwrap_or(true), + ..Default::default() + }; opts.encode.dpx_bits = dpx_bits; opts.encode.dds = photocraft_io::DdsOptions { compression: dds_compression.unwrap_or_default(), mipmaps: p.dds_mipmaps }; if let Some(q) = p.quality { diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 3925bf83215..096344e0170 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -50,7 +50,9 @@ pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack}; use save::save_a_copy; pub(crate) use save::{SaveOpts, encode, save_doc}; -pub use save::{dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, tga_bits_param, tiff_compression_param, tiff_would_write_layers}; +pub use save::{ + dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, pdf_spot_plates_param, tga_bits_param, tiff_compression_param, tiff_would_write_layers, +}; mod batch_naming; @@ -241,7 +243,7 @@ pub fn specs() -> Vec { "Save a Copy…", &["File"], Some("Cmd+Alt+S"), - r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)}"##, + r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone)}"##, native_doc, save_a_copy ), @@ -304,7 +306,7 @@ pub fn specs() -> Vec { "Batch…", &["File", "Automate"], None, - r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, batch ), @@ -313,7 +315,7 @@ pub fn specs() -> Vec { "Image Processor…", &["File", "Scripts"], None, - r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, image_processor ), @@ -341,7 +343,7 @@ pub fn specs() -> Vec { "Layers to Files…", &["File", "Export"], None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone)} → {files}"##, native_doc, layers_to_files ), diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index fff62dc7f46..4f16ea91085 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -28,6 +28,9 @@ pub(crate) struct SaveOpts { /// DDS: the compression and whether to write the mip chain (`"ddsCompression"`, /// `"ddsMipmaps"`); unset, uncompressed without mipmaps. pub dds: photocraft_io::DdsOptions, + /// PDF: spot channels as overprinting Separation plates (`"pdfSpotPlates"`); on unless the + /// params say `false`. + pub pdf_spot_plates: bool, /// PSD/PSB: embed the thumbnail resource (Preferences › File Handling › Image Previews). pub image_previews: bool, /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB @@ -45,6 +48,7 @@ impl Default for SaveOpts { dpx_bits: None, tiff_compression: None, dds: photocraft_io::DdsOptions::default(), + pdf_spot_plates: true, image_previews: true, psd_maximize_compatibility: true, } @@ -67,6 +71,7 @@ impl SaveOpts { dpx_bits: dpx_bits_param(p, cmd)?, tiff_compression: tiff_compression_param(p, cmd)?, dds: dds_param(p, cmd)?.unwrap_or_default(), + pdf_spot_plates: pdf_spot_plates_param(p, cmd)?, image_previews: file_handling.image_previews != crate::prefs::Ask::Never, psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, }) @@ -84,6 +89,15 @@ impl From> for SaveOpts { } } +/// Whether a PDF save in `p` writes spot plates (`"pdfSpotPlates": bool`; absent or null: yes). +/// Anything else is a bad parameter of command `cmd`. +pub fn pdf_spot_plates_param(p: &Value, cmd: &str) -> Result { + match p.get("pdfSpotPlates") { + None | Some(Value::Null) => Ok(true), + Some(v) => v.as_bool().ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`pdfSpotPlates` must be true or false, got {v}") }), + } +} + /// The Targa bits per pixel in `p` (`"tgaBits": 24 | 32`; absent or null: the automatic choice). /// Anything else is a bad parameter of command `cmd`. Shared by every save that takes it (the /// engine's commands, the app's Save As and control channel, the headless server). @@ -176,6 +190,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R let mut opts = photocraft_io::ExportOptions { tiff_layers: save.tiff_layers, tga_bits: save.tga_bits, + pdf_spot_plates: save.pdf_spot_plates, image_previews: save.image_previews, psd_maximize_compatibility: save.psd_maximize_compatibility, // Linked files a PSD embeds are resolved against the document being worked on. diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index d93c15fd829..b877f458ac7 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -275,6 +275,34 @@ fn save_a_copy_writes_the_targa_bits_asked_for() { } } +/// A PDF keeps the document's spot channels as `/Separation` plates unless `pdfSpotPlates` is +/// false; anything but a boolean is refused before anything is written. +#[test] +fn save_a_copy_writes_pdf_spot_plates_unless_asked_not_to() { + let dir = tmp("pdf-spot-plates"); + let mut s = session(12, 6, 8); + s.execute("select.all", json!({})).unwrap(); + s.execute("channel.newSpot", json!({"name": "Underbase White", "color": "#ffffff"})).unwrap(); + let has = |bytes: &[u8], needle: &str| bytes.windows(needle.len()).any(|w| w == needle.as_bytes()); + for (params, plates) in + [(json!({}), true), (json!({"pdfSpotPlates": true}), true), (json!({"pdfSpotPlates": null}), true), (json!({"pdfSpotPlates": false}), false)] + { + let out = join(&dir, "a.pdf"); + let mut p = params.clone(); + p["path"] = json!(out); + s.execute("file.saveACopy", p).unwrap(); + let bytes = std::fs::read(&out).unwrap(); + assert_eq!(has(&bytes, "/Separation /Underbase#20White /DeviceCMYK"), plates, "{params}"); + assert_eq!(has(&bytes, "/OP true /op true"), plates, "{params}: overprint rides with the plates"); + } + for bad in [json!(1), json!("true"), json!([true])] { + let out = join(&dir, "bad.pdf"); + let r = s.execute("file.saveACopy", json!({"path": out, "pdfSpotPlates": bad})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert!(!std::path::Path::new(&out).exists(), "{bad}: nothing written"); + } +} + /// `dpxBits` picks a DPX's bits per sample (byte 803 of the header); unset, it follows the /// document's depth. Anything but 8, 10, 12 or 16 is refused before anything is written. #[test] diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 0a184bda79b..8b75e0a909d 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -240,6 +240,10 @@ pub struct ExportOptions { /// PSD/PSB and layered TIFF: read and embed the files linked smart objects name (see /// [`PsdExportOptions::read_linked_files`]). On by default; automation turns it off. pub read_linked_files: bool, + /// PDF: write the document's spot channels as overprinting `/Separation` plates after the + /// flattened image, and a Multichannel document as its plates alone (FILE-215-17). On by + /// default; `false` writes the flattened image only (`"pdfSpotPlates": false`). + pub pdf_spot_plates: bool, } impl Default for ExportOptions { @@ -255,6 +259,7 @@ impl Default for ExportOptions { document_path: None, pcraft_cache: None, read_linked_files: true, + pdf_spot_plates: true, } } } @@ -591,7 +596,7 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & return ora::export(doc); } if ext == "pdf" { - return pdf::export(doc); + return pdf::export(doc, opts.pdf_spot_plates); } if ext == photocraft_format::EXTENSION { let doc = named_for_file(doc, name_or_ext); diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 92a5a058501..a5b6a3e6c54 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -4,8 +4,14 @@ //! through [`export`], and File › Print through [`print_pdf`] (called by the engine, which adds //! paper geometry, printer marks and labels around the image). One page holds a //! Flate-compressed image XObject, optional printer marks as vector operators and optional -//! Helvetica text; an embedded ICC profile rides in an ICCBased colour space. Multi-page PDF, -//! layer-preserving PDF and PDF import stay open (FILE-215-10). +//! Helvetica text; an embedded ICC profile rides in an ICCBased colour space. +//! +//! Spot channels leave as plates (FILE-215-17): one 8-bit image XObject per channel in a +//! `/Separation` colour space named after the channel, painted over the composite with overprint +//! on and its zero-ink samples stencil-masked, so a RIP or a separating rasteriser (Ghostscript +//! `tiffsep`, `psdcmyk`) keeps each one as its own named plate instead of mixing it into CMYK, and +//! a plain viewer still shows every plate's ink. Multi-page PDF, layer-preserving PDF and PDF +//! import stay open (FILE-215-10). use std::io::Write as _; @@ -24,6 +30,19 @@ pub struct PrintImage { pub icc: Option>, } +/// One spot plate: a named `/Separation` colorant with 8-bit ink density over the whole image +/// box (`width × height` samples, 255 = solid ink), and the CMYK a viewer mixes to show it. +pub struct SpotPlate { + /// The colorant name, as the channel is named. A RIP names the plate after it. + pub name: String, + /// The alternate colour (`/DeviceCMYK`, 1 = full ink) of the tint transform: how a viewer + /// previews the ink. A RIP prints the plate, not this. + pub cmyk: [f32; 4], + pub width: u32, + pub height: u32, + pub data: Vec, +} + /// Printer marks around the image. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Marks { @@ -32,14 +51,19 @@ pub struct Marks { pub registration: bool, } -/// One page: paper (pt), image box (pt, origin bottom-left), marks and texts. +/// One page: paper (pt), image box (pt, origin bottom-left), marks, texts and spot plates. +/// +/// The image is optional: a Multichannel document is nothing but its plates. The plates are +/// painted over the image box in order, each with overprint on, so painting one never knocks +/// the others (or the image) out. pub struct PrintPage { pub paper: (f64, f64), - pub image: PrintImage, + pub image: Option, pub rect: (f64, f64, f64, f64), pub marks: Marks, pub description: Option, pub label: Option, + pub plates: Vec, } fn pdf_string(s: &str) -> String { @@ -58,6 +82,25 @@ fn pdf_string(s: &str) -> String { o } +/// `s` as a PDF name object (ISO 32000-1 §7.3.5): `/` then the UTF-8 bytes, every byte outside +/// the regular printable ASCII range, `#` and the delimiters as `#xx`. An empty name would be +/// the bare `/`, which some readers reject, so it becomes `/Spot`. +fn pdf_name(s: &str) -> String { + let mut o = String::from("/"); + for b in s.bytes() { + let regular = (0x21..=0x7e).contains(&b) && !matches!(b, b'#' | b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'); + if regular { + o.push(char::from(b)); + } else { + o.push_str(&format!("#{b:02X}")); + } + } + if o.len() == 1 { + o.push_str("Spot"); + } + o +} + fn deflate(data: &[u8]) -> Vec { // Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static // Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger @@ -103,7 +146,43 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String { s } +/// An image XObject dictionary and its Flate-compressed samples, as one object body. `extra` +/// is spliced into the dictionary (e.g. a stencil mask reference). +fn image_object(width: u32, height: u32, colour_space: &str, extra: &str, data: &[u8]) -> Vec { + let z = deflate(data); + let mut body = format!( + "<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace {colour_space} /BitsPerComponent 8 {extra}/Filter /FlateDecode /Length {} >>\nstream\n", + z.len() + ) + .into_bytes(); + body.extend_from_slice(&z); + body.extend_from_slice(b"\nendstream"); + body +} + +/// The stencil mask of a plate: one bit per sample, rows padded to a byte, set (masked out, not +/// painted) where the plate has no ink. +fn stencil_mask(width: u32, height: u32, data: &[u8]) -> Vec { + let (w, h) = (width as usize, height as usize); + let stride = w.div_ceil(8); + let mut out = vec![0u8; stride.saturating_mul(h)]; + for (y, row) in data.chunks(w.max(1)).take(h).enumerate() { + for (x, &v) in row.iter().enumerate() { + if v == 0 + && let Some(b) = out.get_mut(y * stride + x / 8) + { + *b |= 0x80 >> (x % 8); + } + } + } + out +} + /// A one-page PDF. +/// +/// Objects: 1 catalog, 2 pages, 3 page, 4 contents, 5 font, then the image, its ICC profile, +/// the overprint ExtGState and, per plate, its stencil mask then its image XObject, each only +/// when present. pub fn print_pdf(page: &PrintPage) -> Vec { let mut out: Vec = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); let mut offsets: Vec = Vec::new(); @@ -113,21 +192,49 @@ pub fn print_pdf(page: &PrintPage) -> Vec { out.extend_from_slice(body); out.extend_from_slice(b"\nendobj\n"); }; - let img = &page.image; let (pw, ph) = page.paper; let (x, y, w, h) = page.rect; - // 1 catalog, 2 pages, 3 page, 4 contents, 5 image, 6 font, 7 ICC (optional). + // Object numbers of the optional objects, in the order they are written. + let mut next = 6usize; + let mut take = |present: bool| { + let n = present.then_some(next); + next += usize::from(present); + n + }; + let image_obj = take(page.image.is_some()); + let icc_obj = take(page.image.as_ref().is_some_and(|i| i.icc.is_some())); + let gs_obj = take(!page.plates.is_empty()); + // Per plate: the stencil mask at `first_plate + 2i`, the plate image right after it. + let first_plate = next; + let plate_objs: Vec = (0..page.plates.len()).map(|i| first_plate + 2 * i + 1).collect(); + obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>"); obj(&mut out, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); + let mut xobjects = String::new(); + if let Some(n) = image_obj { + xobjects.push_str(&format!("/Im0 {n} 0 R ")); + } + for (i, n) in plate_objs.iter().enumerate() { + xobjects.push_str(&format!("/Sp{i} {n} 0 R ")); + } + let ext_gstate = gs_obj.map(|n| format!("/ExtGState << /GS0 {n} 0 R >> ")).unwrap_or_default(); obj( &mut out, format!( - "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 5 0 R >> /Font << /F1 6 0 R >> >> /Contents 4 0 R >>" + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << {xobjects}>> {ext_gstate}/Font << /F1 5 0 R >> >> /Contents 4 0 R >>" ) .as_bytes(), ); // An explicit white page, so every viewer (and rasteriser) shows paper, not transparency. - let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n"); + let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\n"); + if image_obj.is_some() { + content.push_str(&format!("q {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n")); + } + // Each plate overprints what is already on the page: with `/OP true` a Separation paints its + // own colorant only, leaving the others (and the composite) as they are. + for i in 0..page.plates.len() { + content.push_str(&format!("q /GS0 gs {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Sp{i} Do Q\n")); + } content.push_str(&marks_ops(page.marks, page.rect)); let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration; let pad = if any_marks { 30.0 } else { 6.0 }; @@ -142,30 +249,54 @@ pub fn print_pdf(page: &PrintPage) -> Vec { body.extend_from_slice(&c); body.extend_from_slice(b"\nendstream"); obj(&mut out, &body); - let device = match img.channels { - 1 => "/DeviceGray", - 4 => "/DeviceCMYK", - _ => "/DeviceRGB", - }; - let cs = if img.icc.is_some() { "[/ICCBased 7 0 R]".to_string() } else { device.to_string() }; - let z = deflate(&img.data); - let mut body = format!( - "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", - img.width, - img.height, - z.len() - ) - .into_bytes(); - body.extend_from_slice(&z); - body.extend_from_slice(b"\nendstream"); - obj(&mut out, &body); obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"); - if let Some(icc) = &img.icc { - let z = deflate(icc); - let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", img.channels, z.len()).into_bytes(); + if let Some(img) = &page.image { + let device = match img.channels { + 1 => "/DeviceGray", + 4 => "/DeviceCMYK", + _ => "/DeviceRGB", + }; + let cs = match icc_obj { + Some(n) => format!("[/ICCBased {n} 0 R]"), + None => device.to_string(), + }; + obj(&mut out, &image_object(img.width, img.height, &cs, "", &img.data)); + if let Some(icc) = &img.icc { + let z = deflate(icc); + let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", img.channels, z.len()).into_bytes(); + body.extend_from_slice(&z); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); + } + } + if gs_obj.is_some() { + obj(&mut out, b"<< /Type /ExtGState /OP true /op true /OPM 1 >>"); + } + for (i, p) in page.plates.iter().enumerate() { + // A tint transform from the colorant's density to its alternate: 0 → paper, 1 → `cmyk` + // (an exponential interpolation function with N = 1 is linear). + let cmyk = p.cmyk.map(|v| format!("{:.4}", v.clamp(0.0, 1.0))).join(" "); + let cs = format!("[/Separation {} /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [{cmyk}] /N 1 >>]", pdf_name(&p.name)); + // Stencil masking (PDF 1.3, no transparency): where the plate has no ink, nothing is + // painted at all. A separating RIP sees the same plate either way (unpainted = no ink), + // but a viewer without overprint preview would otherwise paint every zero-ink pixel as + // opaque paper and show only the last plate. An explicit 1-bit mask stream, not a + // colour-key `/Mask [0 0]` range: Quartz (Preview, Quick Look, Safari) draws nothing for + // a colour-key-masked Separation image. + let mask = stencil_mask(p.width, p.height, &p.data); + let z = deflate(&mask); + let mut body = format!( + "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ImageMask true /BitsPerComponent 1 /Filter /FlateDecode /Length {} >>\nstream\n", + p.width, + p.height, + z.len() + ) + .into_bytes(); body.extend_from_slice(&z); body.extend_from_slice(b"\nendstream"); obj(&mut out, &body); + let mask_ref = format!("/Mask {} 0 R ", first_plate + 2 * i); + obj(&mut out, &image_object(p.width, p.height, &cs, &mask_ref, &p.data)); } let xref = out.len(); out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); @@ -176,41 +307,99 @@ pub fn print_pdf(page: &PrintPage) -> Vec { out } +/// The spot plates of `doc`, in channel order (the first channel prints first, underneath). +/// +/// In a Multichannel document every channel is a plate: its spot channels at the ink density +/// they store (1 = solid), an alpha-type channel as the transparent black ink the composite shows +/// it as (1 − value, as `photocraft_compose::multichannel` prints it). Any other document keeps +/// its alpha channels as masks and exports only its spot channels. The alternate colour is the +/// ink colour separated through the CMYK profile in use (`Color::in_mode`); it only previews the +/// plate, as Photoshop's does. Solidity is a preview attribute too and is not written. +fn plates_of(doc: &Document, w: usize, h: usize) -> Vec { + let multichannel = doc.mode == ColorMode::Multichannel; + let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); + let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + doc.channels + .iter() + .filter(|ch| multichannel || ch.spot.is_some()) + .map(|ch| { + let (ink, alpha_type) = match ch.spot { + Some((ink, _)) => (ink, false), + None => (photocraft_color::Color::BLACK, true), + }; + let n = ch.surface.channels().max(1); + let values = ch.surface.read_region(canvas); + let data: Vec = values.chunks(n).map(|px| px.first().copied().unwrap_or(0.0)).map(|v| to8(if alpha_type { 1.0 - v } else { v })).collect(); + SpotPlate { name: ch.name.clone(), cmyk: ink.in_mode(ColorMode::Cmyk).c, width: w as u32, height: h as u32, data } + }) + .collect() +} + /// File › Save As / Save a Copy › PDF (#3401): the flattened document, at its print size /// (pixels ÷ resolution × 72 pt), as a one-page PDF. Layers and transparency are dropped — the /// warning says so — and the embedded profile travels with the image. -pub fn export(doc: &Document) -> std::result::Result { +/// +/// With `spot_plates`, the document's spot channels follow the image as overprinting +/// `/Separation` plates (FILE-215-17), and a Multichannel document, which is nothing but its +/// channels, is written as plates alone. Without it a Multichannel document has nothing to +/// write and is refused. +pub fn export(doc: &Document, spot_plates: bool) -> std::result::Result { let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0)); if w == 0 || h == 0 { return Err(IoError::Unsupported("PDF needs a document with non-zero width and height; nothing was written".into())); } let device = match doc.mode { - ColorMode::Rgb => 3, - ColorMode::Grayscale => 1, - ColorMode::Cmyk => 4, - m => return Err(IoError::Unsupported(format!("PDF saves RGB, Grayscale and CMYK documents; {m:?} needs converting to RGB first (Image > Mode)"))), - }; - let fmt = doc.pixel_format(); - let n = fmt.channels().max(1); - let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); - let surface = photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None); - let values = surface.read_region(canvas); - let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - // Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink - // in CMYK (0 = paper). - let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 }; - let mut data = Vec::with_capacity((w * h).saturating_mul(device)); - for px in values.chunks(n) { - let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0); - for v in px.iter().take(device) { - data.push(to8(v * a + paper * (1.0 - a))); + ColorMode::Rgb => Some(3), + ColorMode::Grayscale => Some(1), + ColorMode::Cmyk => Some(4), + ColorMode::Multichannel if spot_plates && !doc.channels.is_empty() => None, + ColorMode::Multichannel => { + return Err(IoError::Unsupported( + "a Multichannel PDF is its channels as spot plates; with no channels, or spot plates left out, there is nothing to write".into(), + )); } - } - let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: doc.icc_profile.as_ref().map(|p| p.to_vec()) }; + m => { + return Err(IoError::Unsupported(format!( + "PDF saves RGB, Grayscale, CMYK and Multichannel documents; {m:?} needs converting to RGB first (Image > Mode)" + ))); + } + }; let dpi = f64::from(doc.resolution_dpi.max(1.0)); let (pw, ph) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi); - let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None }; - let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; + let mut warnings = Vec::new(); + let image = device.map(|device| { + let fmt = doc.pixel_format(); + let n = fmt.channels().max(1); + let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); + let surface = photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None); + let values = surface.read_region(canvas); + let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + // Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink + // in CMYK (0 = paper). + let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 }; + let mut data = Vec::with_capacity((w * h).saturating_mul(device)); + for px in values.chunks(n) { + let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0); + for v in px.iter().take(device) { + data.push(to8(v * a + paper * (1.0 - a))); + } + } + warnings.push("PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()); + PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: doc.icc_profile.as_ref().map(|p| p.to_vec()) } + }); + let plates = if spot_plates { plates_of(doc, w, h) } else { Vec::new() }; + if !plates.is_empty() { + let names: Vec<&str> = plates.iter().map(|p| p.name.as_str()).collect(); + warnings.push(format!( + "{} spot plate{} written as overprinting Separation colorants ({}), 8-bit; their preview colours are the inks separated to CMYK", + plates.len(), + if plates.len() == 1 { "" } else { "s" }, + names.join(", ") + )); + } else if doc.channels.iter().any(|ch| ch.spot.is_some()) { + warnings.push("spot channels were not written: spot plates were left out".into()); + } + let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None, plates }; if !doc.metadata.text.is_empty() { warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into()); } diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 1807b7adc08..91049f90a2e 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -2,7 +2,7 @@ use super::*; use photocraft_color::{PixelFormat, SampleType}; -use photocraft_doc::{Layer, LayerContent, Size}; +use photocraft_doc::{AlphaChannel, Layer, LayerContent, Size}; use photocraft_geom::Rect; use photocraft_raster::Surface; @@ -68,7 +68,7 @@ fn check_structure(pdf: &[u8]) { #[test] fn a_flat_rgb_document_saves_as_one_page_pdf() { let d = doc(ColorMode::Rgb); - let out = export(&d).unwrap(); + let out = export(&d, true).unwrap(); let pdf = &out.bytes; check_structure(pdf); assert!(has(pdf, "/MediaBox [0 0 4.00 2.00]"), "page = image size at 72 pt/in"); @@ -85,7 +85,7 @@ fn layers_composite_over_white_before_the_page() { let mut d = doc(ColorMode::Rgb); let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); d.layers.push(Layer::new("Half red", LayerContent::Raster(solid(fmt, 1, 0, 3, 2, &[1.0, 0.0, 0.0, 0.5])))); - let out = export(&d).unwrap(); + let out = export(&d, true).unwrap(); let img = stream_after(&out.bytes, "/Subtype /Image"); // Pixels 1-2 of row 0: 0.5 red over white = (1.0, 0.5, 0.5); elsewhere plain white. assert_eq!(&img[3..6], &[255, 128, 128], "the blend lands: {:?}", &img[3..6]); @@ -94,10 +94,10 @@ fn layers_composite_over_white_before_the_page() { #[test] fn greyscale_and_cmyk_pages_keep_their_channels() { - let g = export(&doc(ColorMode::Grayscale)).unwrap(); + let g = export(&doc(ColorMode::Grayscale), true).unwrap(); assert!(has(&g.bytes, "/ColorSpace /DeviceGray"), "gray is DeviceGray"); assert_eq!(stream_after(&g.bytes, "/Subtype /Image"), vec![255; 4 * 2], "one sample per pixel"); - let c = export(&doc(ColorMode::Cmyk)).unwrap(); + let c = export(&doc(ColorMode::Cmyk), true).unwrap(); assert!(has(&c.bytes, "/ColorSpace /DeviceCMYK"), "cmyk is DeviceCMYK"); assert_eq!(stream_after(&c.bytes, "/Subtype /Image"), vec![0; 4 * 2 * 4], "zero ink over the whole page"); } @@ -109,7 +109,7 @@ fn the_page_measures_at_the_document_resolution() { let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))]; d.resolution_dpi = 300.0; - let out = export(&d).unwrap(); + let out = export(&d, true).unwrap(); assert!(has(&out.bytes, "/MediaBox [0 0 72.00 36.00]"), "300 px at 300 dpi is one inch"); } @@ -117,7 +117,7 @@ fn the_page_measures_at_the_document_resolution() { fn an_embedded_profile_travels_as_iccbased() { let mut d = doc(ColorMode::Rgb); d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8])); - let out = export(&d).unwrap(); + let out = export(&d, true).unwrap(); assert!(has(&out.bytes, "[/ICCBased 7 0 R]"), "the image refers to the profile"); assert_eq!(stream_after(&out.bytes, "/N 3 /Alternate"), vec![1, 2, 3, 4, 5, 6, 7, 8], "the profile bytes survive"); } @@ -125,7 +125,155 @@ fn an_embedded_profile_travels_as_iccbased() { #[test] fn other_modes_are_refused_with_an_actionable_error() { let d = doc(ColorMode::Lab); - let e = export(&d).unwrap_err().to_string(); + let e = export(&d, true).unwrap_err().to_string(); assert!(e.contains("RGB") && e.contains("Mode"), "{e}"); assert!(crate::export(&d, "x.pdf", &crate::ExportOptions::default()).is_err()); } + +// ---- Spot plates (FILE-215-17) ---- + +/// A grayscale channel surface over the 4×2 test canvas, one value per pixel. +fn channel(vals: &[f32]) -> Surface { + let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); + s.write_region(Rect::new(0, 0, 4, 2), vals); + s +} + +fn spot(name: &str, color: photocraft_color::Color, vals: &[f32]) -> AlphaChannel { + AlphaChannel { spot: Some((color, 0.0)), ..AlphaChannel::new(name, channel(vals)) } +} + +/// The content stream (object 4), inflated, as text. +fn content(pdf: &[u8]) -> String { + String::from_utf8(stream_after(pdf, "4 0 obj")).unwrap() +} + +#[test] +fn spot_channels_follow_the_image_as_overprinting_separation_plates() { + let mut d = doc(ColorMode::Rgb); + let under: Vec = vec![1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]; + let red: Vec = vec![0.0, 0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + d.channels.push(spot("Underbase White", photocraft_color::Color::WHITE, &under)); + d.channels.push(spot("PANTONE 185 C", photocraft_color::Color::rgb(0.89, 0.09, 0.22), &red)); + let out = export(&d, true).unwrap(); + let pdf = &out.bytes; + check_structure(pdf); + // The composite is still the first image, in its own colour space. + assert!(has(pdf, "/Width 4 /Height 2 /ColorSpace /DeviceRGB"), "the flattened composite stays"); + assert_eq!(stream_after(pdf, "/Subtype /Image"), vec![255u8; 4 * 2 * 3]); + // One Separation XObject per channel, named after it, with a DeviceCMYK tint transform. + assert!( + has( + pdf, + "/ColorSpace [/Separation /Underbase#20White /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0.0000 0.0000 0.0000 0.0000] /N 1 >>]" + ), + "white ink previews as no ink" + ); + assert!(has(pdf, "/Separation /PANTONE#20185#20C /DeviceCMYK"), "the second plate"); + // 1 = solid ink, as the channel stores it: the plate is the channel, 8-bit, not inverted. + assert_eq!(stream_after(pdf, "/Separation /Underbase#20White"), vec![255, 255, 255, 255, 0, 0, 0, 0]); + assert_eq!(stream_after(pdf, "/Separation /PANTONE#20185#20C"), vec![0, 128, 255, 0, 0, 0, 0, 0]); + // Overprint is on for the plates, so each paints only its own colorant; zero-ink samples are + // stencil-masked (unpainted) by a 1-bit mask written just before each plate, never a soft mask. + assert!(has(pdf, "/Type /ExtGState /OP true /op true /OPM 1"), "overprint state"); + assert!( + has( + pdf, + "/DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0.0000 0.0000 0.0000 0.0000] /N 1 >>] /BitsPerComponent 8 /Mask 8 0 R /Filter" + ), + "the first plate (object 9) refers to its mask (object 8)" + ); + assert!(has(pdf, "/Separation /PANTONE#20185#20C /DeviceCMYK") && has(pdf, "/Mask 10 0 R"), "the second plate's mask"); + assert_eq!(stream_after(pdf, "/ImageMask true"), vec![0x00, 0xF0], "row 0 all ink: no bits; row 1 no ink: 4 bits set, padded"); + assert!(!has(pdf, "/SMask"), "no transparency"); + assert!(!has(pdf, "/Width 4 /Height 2 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Mask"), "the composite is not masked"); + let c = content(pdf); + let (im, p0, p1) = ( + c.find("/Im0 Do").unwrap(), + c.find("/GS0 gs 4.000 0 0 2.000 0.000 0.000 cm /Sp0 Do").unwrap(), + c.find("/GS0 gs 4.000 0 0 2.000 0.000 0.000 cm /Sp1 Do").unwrap(), + ); + assert!(im < p0 && p0 < p1, "image, then the plates in channel order (underbase first): {c}"); + assert!(out.warnings.iter().any(|w| w.contains("2 spot plates") && w.contains("Underbase White, PANTONE 185 C")), "{:?}", out.warnings); + // An alpha channel of an RGB document is a mask, not a plate. + d.channels.push(AlphaChannel::new("Mask", channel(&[1.0; 8]))); + let out = export(&d, true).unwrap(); + assert!(!has(&out.bytes, "/Separation /Mask"), "alpha channels stay out of RGB plates"); + assert!(has(&out.bytes, "/Sp1 "), "the two spot plates remain"); + assert!(!has(&out.bytes, "/Sp2 ")); +} + +#[test] +fn a_multichannel_document_is_its_plates_alone() { + let mut d = Document::new("m.pdf", Size { width: 4, height: 2 }, ColorMode::Multichannel, SampleType::F32); + d.resolution_dpi = 72.0; + d.channels.push(spot("Cyan", photocraft_color::Color::rgb(0.0, 1.0, 1.0), &[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])); + d.channels.push(spot("Black Ink", photocraft_color::Color::BLACK, &[0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])); + // An alpha-type channel of a Multichannel document prints as black ink where it is + // unselected (1 − value), as the composite shows it. + d.channels.push(AlphaChannel::new("Alpha 1", channel(&[1.0, 1.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0]))); + let out = export(&d, true).unwrap(); + let pdf = &out.bytes; + check_structure(pdf); + assert!(!has(pdf, "/Im0"), "no composite image"); + assert!(has(pdf, "/MediaBox [0 0 4.00 2.00]")); + assert_eq!(stream_after(pdf, "/Separation /Cyan"), vec![255, 0, 0, 0, 0, 0, 0, 0]); + // The alternate is the ink separated through the CMYK profile in use: a rich black here, + // whatever its CMY, with the black ink near solid. + let marker = "/Separation /Black#20Ink /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 ["; + let at = pdf.windows(marker.len()).position(|w| w == marker.as_bytes()).expect("the black plate's tint transform") + marker.len(); + let c1 = std::str::from_utf8(&pdf[at..at + 32]).unwrap().split(']').next().unwrap().to_string(); + let k: f32 = c1.split_whitespace().nth(3).unwrap().parse().unwrap(); + assert!(k > 0.85, "black ink's K alternate: {c1}"); + assert_eq!(stream_after(pdf, "/Separation /Alpha#201"), vec![0, 0, 255, 128, 0, 0, 0, 0], "alpha-type: ink = 1 − value"); + let c = content(pdf); + assert!(c.find("/Sp0 Do").unwrap() < c.find("/Sp1 Do").unwrap() && c.find("/Sp1 Do").unwrap() < c.find("/Sp2 Do").unwrap()); + assert!(!out.warnings.iter().any(|w| w.contains("flattened")), "nothing was flattened: {:?}", out.warnings); + // Without plates there is nothing to write. + let e = export(&d, false).unwrap_err().to_string(); + assert!(e.contains("Multichannel") && e.contains("spot plates"), "{e}"); + d.channels.clear(); + assert!(export(&d, true).is_err(), "no channels, nothing to write"); +} + +#[test] +fn plate_names_are_escaped_as_pdf_names() { + let mut d = doc(ColorMode::Grayscale); + let ink = photocraft_color::Color::rgb(0.2, 0.3, 0.4); + d.channels.push(spot("Black (Ink) #1/ü", ink, &[0.0; 8])); + d.channels.push(spot("", ink, &[0.0; 8])); + let out = export(&d, true).unwrap(); + check_structure(&out.bytes); + assert!(has(&out.bytes, "/Separation /Black#20#28Ink#29#20#231#2F#C3#BC /DeviceCMYK"), "delimiters, #, space and UTF-8 bytes are #xx"); + assert!(has(&out.bytes, "/Separation /Spot /DeviceCMYK"), "an empty name is not the bare /"); +} + +#[test] +fn spot_plates_can_be_left_out_of_a_scripted_save() { + let mut d = doc(ColorMode::Cmyk); + d.channels.push(spot("Varnish", photocraft_color::Color::rgb(0.9, 0.9, 0.6), &[1.0; 8])); + let with = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + assert!(has(&with.bytes, "/Separation /Varnish"), "plates by default"); + let without = crate::export(&d, "out.pdf", &crate::ExportOptions { pdf_spot_plates: false, ..Default::default() }).unwrap(); + assert!( + !has(&without.bytes, "/Separation") && !has(&without.bytes, "/ExtGState") && !has(&without.bytes, "/ImageMask"), + "no plate, no overprint state, no mask" + ); + assert!(has(&without.bytes, "/ColorSpace /DeviceCMYK"), "the composite still saves"); + assert!(without.warnings.iter().any(|w| w.contains("not written")), "{:?}", without.warnings); + check_structure(&without.bytes); + // A plain document never gets the plate warning either way. + let plain = export(&doc(ColorMode::Rgb), true).unwrap(); + assert!(!plain.warnings.iter().any(|w| w.contains("plate")), "{:?}", plain.warnings); +} + +#[test] +fn a_16_bit_plate_is_written_at_8_bits() { + let mut d = Document::new("m.pdf", Size { width: 4, height: 2 }, ColorMode::Multichannel, SampleType::U16); + let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U16, false)); + s.write_region(Rect::new(0, 0, 4, 2), &[0.0, 0.25, 0.5, 1.0, 0.0, 0.0, 0.0, 0.0]); + d.channels.push(AlphaChannel { spot: Some((photocraft_color::Color::BLACK, 0.0)), ..AlphaChannel::new("K", s) }); + let out = export(&d, true).unwrap(); + assert!(has(&out.bytes, "/BitsPerComponent 8")); + assert_eq!(stream_after(&out.bytes, "/Separation /K"), vec![0, 64, 128, 255, 0, 0, 0, 0]); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 473c6fe4ffe..682913454e6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -428,7 +428,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6c9a6b65ba4..8a0e66b4aef 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-24 · **Change:** minor (PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-29 · **Change:** minor (PDF: spot channels as overprinting `/Separation` plates, a Multichannel document as plates alone, FILE-215-17's PDF part; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 **PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. @@ -40,8 +40,8 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Portable Bit Map (PBM/PGM/PPM/PNM/PFM/PAM) | R/W | yes | yes | 8/16/32f | | FITS | R/W (FITS Liberator plug-in) | yes | yes | 8/16/32f gray or RGB, header cards kept; no fpack, no debayer | | Targa | R/W | yes | yes | 8-bit | -| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541) | -| Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | | +| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF); spot channels as overprinting `/Separation` plates after the image, a Multichannel document as its plates alone (FILE-215-17's PDF part) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541). Plates are 8-bit, named after the channel, 1 = solid ink, painted in channel order with `/OP true`; the tint transform's alternate is the ink colour separated to CMYK (preview only); solidity is not written; no printer marks, labels or halftone screens, as Photoshop's PDF has none either (scripts: `pdfSpotPlates: false` leaves the plates out). Ghostscript `tiffsep`/`psdcmyk` split the page into the named plates | +| Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | A spot-plate PDF (above) carries what a DCS 2.0 file carried to a RIP: one named plate per spot channel | | Generic EPS / AI | R (rasterize) | no | no | | | SVG | R (rasterize) | yes, as editable shape layers or a vector smart object | no | Better than Photoshop for editing; gradients approximated (FILE-215-9) | | JPEG 2000 | R/W | no (#1047) | no | | @@ -144,6 +144,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | PDF: spot channels are written as overprinting `/Separation` plates after the flattened image (one 8-bit Flate image XObject per channel, named after it, 1 = solid ink, `/OP true`, channel order, DeviceCMYK alternate from the ink colour), and a Multichannel document saves as its plates alone; `pdfSpotPlates: false` on scripted saves writes the image only. FILE-215-17's PDF Separation part; its RGB/CMYK spot preview stays open | | 2026-10-24 | minor | Layered TIFF: the `LMsk` block in tag 37724 carries Photoshop's default global layer mask (14 bytes) instead of none; with an empty block Photoshop read only the composite (#9095). PSD output unchanged | | 2026-10-24 | minor | Layered TIFF writes the TySh text version and descriptor in PSD big-endian order while retaining container order for the block header, transform matrix, warp section and bounds (#9098); the mixed-order read path remains covered by #4758/#4771. | | 2026-10-23 | minor | PSD: spot channels are stored and read as Photoshop 27.11's PSDs store them (ink 0 = solid; all 7 of its spot PSDs store the 100/25/75/0 % columns as 0/191/64/255), and resource 1053 numbers the extra channels 3, 4, 5, … after 0 for the merged transparency. A PSD with spot channels whose 1057 is exactly what PhotoCraft 0.1.0–0.16.0 wrote, and with no 1053 or one kept from an opened Photoshop file that doesn't list every channel, is read as those versions stored it (straight past the channels that 1053 lists), so it keeps its ink. Multichannel is unchanged (#7415 split, part 4) | diff --git a/docs/gaps.md b/docs/gaps.md index 5c9285c995e..620694a65d2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 181 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (G10: PDF writes spot channels as overprinting `/Separation` plates and a Multichannel document as plates alone, FILE-215-17's PDF Separation part; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 181 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -347,10 +347,14 @@ what an agent can't finish alone. write (FILE-215-10, #2541; a single flattened page now saves via Save As / Save a Copy / CLI, 2026-10-11, #3401), AVIF read (#463) and default-build AVIF write, JPEG XL, JPEG 2000 (#1047), DICOM, EPS/DCS, Pixar, WBMP, MPO/JPS, PICT, Scitex CT, Photoshop - Raw; spot plates beyond PSD and TIFF: spot ink preview in RGB/CMYK documents and PDF Separation + Raw; spot plates beyond PSD, TIFF and PDF: spot ink preview in RGB/CMYK documents (FILE-215-17); .atn, .shc, .csh presets (.asl landed 2026-10-20) (FILE-215-15); C2PA (#1050). - **Detail:** [`file-format-parity.md`](file-format-parity.md). +- **Progress (2026-10-29):** PDF writes spot channels as overprinting `/Separation` plates after + the flattened image, one 8-bit image per channel named after it, and a Multichannel document as + its plates alone, so a RIP or Ghostscript's `tiffsep` separates them as named plates (FILE-215-17's + PDF Separation part; `pdfSpotPlates: false` on scripted saves leaves them out). - **Progress (2026-10-23, #7415 split):** PSD stores and reads spot channels as Photoshop does (ink 0 = solid) and writes their identifiers (1053); PSDs from PhotoCraft 0.1.0–0.16.0, which stored spot ink the other way round, keep their ink. From 3b4ccadbb7481f541d17e44168c835e05e1ccf51 Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Fri, 30 Oct 2026 15:10:21 -0400 Subject: [PATCH 2/8] PDF spot plates: no stencil mask on the plates Illustrator reports an explicit /ImageMask on a Separation image as "An unknown imaging construct was encountered" (verified on six variants: the mask alone triggers it), and Quartz draws nothing for a colour-key-masked one, so the plates go out unmasked: a viewer that ignores overprint shows the last plate opaque, Acrobat's Overprint Preview and any separating RIP show the real result. Ghostscript tiffsep output is byte-identical with and without the mask. Co-Authored-By: Claude Fable 5.1 --- crates/io/src/pdf.rs | 69 ++++++++++---------------------------- crates/io/src/pdf/tests.rs | 19 +++-------- 2 files changed, 22 insertions(+), 66 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index a5b6a3e6c54..8dc667dbc69 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -8,9 +8,11 @@ //! //! Spot channels leave as plates (FILE-215-17): one 8-bit image XObject per channel in a //! `/Separation` colour space named after the channel, painted over the composite with overprint -//! on and its zero-ink samples stencil-masked, so a RIP or a separating rasteriser (Ghostscript -//! `tiffsep`, `psdcmyk`) keeps each one as its own named plate instead of mixing it into CMYK, and -//! a plain viewer still shows every plate's ink. Multi-page PDF, layer-preserving PDF and PDF +//! on, so a RIP or a separating rasteriser (Ghostscript `tiffsep`, `psdcmyk`) keeps each one as +//! its own named plate instead of mixing it into CMYK. The plates carry no mask: a viewer that +//! ignores overprint shows the last plate opaque, Acrobat's Overprint Preview and any separating +//! RIP show the real result, and an explicit image mask makes Illustrator report "An unknown +//! imaging construct was encountered". Multi-page PDF, layer-preserving PDF and PDF //! import stay open (FILE-215-10). use std::io::Write as _; @@ -146,12 +148,11 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String { s } -/// An image XObject dictionary and its Flate-compressed samples, as one object body. `extra` -/// is spliced into the dictionary (e.g. a stencil mask reference). -fn image_object(width: u32, height: u32, colour_space: &str, extra: &str, data: &[u8]) -> Vec { +/// An image XObject dictionary and its Flate-compressed samples, as one object body. +fn image_object(width: u32, height: u32, colour_space: &str, data: &[u8]) -> Vec { let z = deflate(data); let mut body = format!( - "<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace {colour_space} /BitsPerComponent 8 {extra}/Filter /FlateDecode /Length {} >>\nstream\n", + "<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace {colour_space} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", z.len() ) .into_bytes(); @@ -160,29 +161,10 @@ fn image_object(width: u32, height: u32, colour_space: &str, extra: &str, data: body } -/// The stencil mask of a plate: one bit per sample, rows padded to a byte, set (masked out, not -/// painted) where the plate has no ink. -fn stencil_mask(width: u32, height: u32, data: &[u8]) -> Vec { - let (w, h) = (width as usize, height as usize); - let stride = w.div_ceil(8); - let mut out = vec![0u8; stride.saturating_mul(h)]; - for (y, row) in data.chunks(w.max(1)).take(h).enumerate() { - for (x, &v) in row.iter().enumerate() { - if v == 0 - && let Some(b) = out.get_mut(y * stride + x / 8) - { - *b |= 0x80 >> (x % 8); - } - } - } - out -} - /// A one-page PDF. /// /// Objects: 1 catalog, 2 pages, 3 page, 4 contents, 5 font, then the image, its ICC profile, -/// the overprint ExtGState and, per plate, its stencil mask then its image XObject, each only -/// when present. +/// the overprint ExtGState and one image XObject per plate, each only when present. pub fn print_pdf(page: &PrintPage) -> Vec { let mut out: Vec = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); let mut offsets: Vec = Vec::new(); @@ -204,9 +186,8 @@ pub fn print_pdf(page: &PrintPage) -> Vec { let image_obj = take(page.image.is_some()); let icc_obj = take(page.image.as_ref().is_some_and(|i| i.icc.is_some())); let gs_obj = take(!page.plates.is_empty()); - // Per plate: the stencil mask at `first_plate + 2i`, the plate image right after it. let first_plate = next; - let plate_objs: Vec = (0..page.plates.len()).map(|i| first_plate + 2 * i + 1).collect(); + let plate_objs: Vec = (0..page.plates.len()).map(|i| first_plate + i).collect(); obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>"); obj(&mut out, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); @@ -260,7 +241,7 @@ pub fn print_pdf(page: &PrintPage) -> Vec { Some(n) => format!("[/ICCBased {n} 0 R]"), None => device.to_string(), }; - obj(&mut out, &image_object(img.width, img.height, &cs, "", &img.data)); + obj(&mut out, &image_object(img.width, img.height, &cs, &img.data)); if let Some(icc) = &img.icc { let z = deflate(icc); let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", img.channels, z.len()).into_bytes(); @@ -272,31 +253,17 @@ pub fn print_pdf(page: &PrintPage) -> Vec { if gs_obj.is_some() { obj(&mut out, b"<< /Type /ExtGState /OP true /op true /OPM 1 >>"); } - for (i, p) in page.plates.iter().enumerate() { + for p in &page.plates { // A tint transform from the colorant's density to its alternate: 0 → paper, 1 → `cmyk` // (an exponential interpolation function with N = 1 is linear). let cmyk = p.cmyk.map(|v| format!("{:.4}", v.clamp(0.0, 1.0))).join(" "); let cs = format!("[/Separation {} /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [{cmyk}] /N 1 >>]", pdf_name(&p.name)); - // Stencil masking (PDF 1.3, no transparency): where the plate has no ink, nothing is - // painted at all. A separating RIP sees the same plate either way (unpainted = no ink), - // but a viewer without overprint preview would otherwise paint every zero-ink pixel as - // opaque paper and show only the last plate. An explicit 1-bit mask stream, not a - // colour-key `/Mask [0 0]` range: Quartz (Preview, Quick Look, Safari) draws nothing for - // a colour-key-masked Separation image. - let mask = stencil_mask(p.width, p.height, &p.data); - let z = deflate(&mask); - let mut body = format!( - "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ImageMask true /BitsPerComponent 1 /Filter /FlateDecode /Length {} >>\nstream\n", - p.width, - p.height, - z.len() - ) - .into_bytes(); - body.extend_from_slice(&z); - body.extend_from_slice(b"\nendstream"); - obj(&mut out, &body); - let mask_ref = format!("/Mask {} 0 R ", first_plate + 2 * i); - obj(&mut out, &image_object(p.width, p.height, &cs, &mask_ref, &p.data)); + // No mask on the plate: where it has no ink it paints "0" of its own colorant, which a + // separating RIP reads as no ink and overprint keeps the other plates under. (A stencil + // or colour-key mask would let plain viewers show every plate, but Illustrator reports + // an explicit image mask as an unknown imaging construct, and Quartz draws nothing for a + // colour-key-masked Separation image.) + obj(&mut out, &image_object(p.width, p.height, &cs, &p.data)); } let xref = out.len(); out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 91049f90a2e..ddc5735bb1f 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -173,18 +173,10 @@ fn spot_channels_follow_the_image_as_overprinting_separation_plates() { // 1 = solid ink, as the channel stores it: the plate is the channel, 8-bit, not inverted. assert_eq!(stream_after(pdf, "/Separation /Underbase#20White"), vec![255, 255, 255, 255, 0, 0, 0, 0]); assert_eq!(stream_after(pdf, "/Separation /PANTONE#20185#20C"), vec![0, 128, 255, 0, 0, 0, 0, 0]); - // Overprint is on for the plates, so each paints only its own colorant; zero-ink samples are - // stencil-masked (unpainted) by a 1-bit mask written just before each plate, never a soft mask. + // Overprint is on for the plates, so each paints only its own colorant; the plates carry no + // mask of any kind (plain viewers show the last plate opaque; a RIP separates them). assert!(has(pdf, "/Type /ExtGState /OP true /op true /OPM 1"), "overprint state"); - assert!( - has( - pdf, - "/DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0.0000 0.0000 0.0000 0.0000] /N 1 >>] /BitsPerComponent 8 /Mask 8 0 R /Filter" - ), - "the first plate (object 9) refers to its mask (object 8)" - ); - assert!(has(pdf, "/Separation /PANTONE#20185#20C /DeviceCMYK") && has(pdf, "/Mask 10 0 R"), "the second plate's mask"); - assert_eq!(stream_after(pdf, "/ImageMask true"), vec![0x00, 0xF0], "row 0 all ink: no bits; row 1 no ink: 4 bits set, padded"); + assert!(!has(pdf, "/Mask") && !has(pdf, "/ImageMask"), "no stencil or colour-key mask"); assert!(!has(pdf, "/SMask"), "no transparency"); assert!(!has(pdf, "/Width 4 /Height 2 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Mask"), "the composite is not masked"); let c = content(pdf); @@ -255,10 +247,7 @@ fn spot_plates_can_be_left_out_of_a_scripted_save() { let with = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); assert!(has(&with.bytes, "/Separation /Varnish"), "plates by default"); let without = crate::export(&d, "out.pdf", &crate::ExportOptions { pdf_spot_plates: false, ..Default::default() }).unwrap(); - assert!( - !has(&without.bytes, "/Separation") && !has(&without.bytes, "/ExtGState") && !has(&without.bytes, "/ImageMask"), - "no plate, no overprint state, no mask" - ); + assert!(!has(&without.bytes, "/Separation") && !has(&without.bytes, "/ExtGState"), "no plate, no overprint state, no mask"); assert!(has(&without.bytes, "/ColorSpace /DeviceCMYK"), "the composite still saves"); assert!(without.warnings.iter().any(|w| w.contains("not written")), "{:?}", without.warnings); check_structure(&without.bytes); From 7b9a2d878d8e4388904d9595a11f6a0ca540b79b Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Fri, 30 Oct 2026 15:46:06 -0400 Subject: [PATCH 3/8] PDF spot plates: describe each plate's ink colour and solidity in XMP The catalog's /Metadata packet (the document's own, when it has one) gains an rdf:Description under http://ns.getartcraft.com/photocraft/spot-plates/1.0/ (pcsp): an rdf:Seq in paint order with each plate's index, name (the Separation colorant name), ink colour as Lab D50 and sRGB hex, and solidity 0-100. A converter can rebuild Photoshop spot channels with the real ink colour, which the Separation colour space's CMYK alternate cannot carry. The plates are unchanged (Ghostscript tiffsep output pixel-identical). A document's XMP now travels into its PDF as into the other flat formats (XmpEmbed). Schema in docs/file-format-parity.md. Co-Authored-By: Claude Fable 5.1 --- crates/io/src/lib.rs | 3 +- crates/io/src/pdf.rs | 123 +++++++++++++++++++++++++++++++++++-- crates/io/src/pdf/tests.rs | 64 +++++++++++++++++++ docs/file-format-parity.md | 26 +++++++- 4 files changed, 207 insertions(+), 9 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 8b75e0a909d..45423b2263c 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -596,7 +596,8 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & return ora::export(doc); } if ext == "pdf" { - return pdf::export(doc, opts.pdf_spot_plates); + let xmp = if opts.xmp == XmpEmbed::All { doc.metadata.xmp.as_deref() } else { None }; + return pdf::export_with(doc, opts.pdf_spot_plates, xmp); } if ext == photocraft_format::EXTENSION { let doc = named_for_file(doc, name_or_ext); diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 8dc667dbc69..1afb7debe37 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -40,6 +40,11 @@ pub struct SpotPlate { /// The alternate colour (`/DeviceCMYK`, 1 = full ink) of the tint transform: how a viewer /// previews the ink. A RIP prints the plate, not this. pub cmyk: [f32; 4], + /// The ink colour as CIE L*a*b* (D50) and as encoded sRGB, and the solidity (0..1), for the + /// XMP description a converter reads to rebuild the spot channel (see [`plates_xmp`]). + pub lab: [f32; 3], + pub srgb: [f32; 3], + pub solidity: f32, pub width: u32, pub height: u32, pub data: Vec, @@ -66,6 +71,8 @@ pub struct PrintPage { pub description: Option, pub label: Option, pub plates: Vec, + /// The XMP packet for the catalog's `/Metadata` stream, if any. + pub xmp: Option, } fn pdf_string(s: &str) -> String { @@ -164,7 +171,8 @@ fn image_object(width: u32, height: u32, colour_space: &str, data: &[u8]) -> Vec /// A one-page PDF. /// /// Objects: 1 catalog, 2 pages, 3 page, 4 contents, 5 font, then the image, its ICC profile, -/// the overprint ExtGState and one image XObject per plate, each only when present. +/// the overprint ExtGState, one image XObject per plate and the XMP metadata stream, each only +/// when present. pub fn print_pdf(page: &PrintPage) -> Vec { let mut out: Vec = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); let mut offsets: Vec = Vec::new(); @@ -186,10 +194,11 @@ pub fn print_pdf(page: &PrintPage) -> Vec { let image_obj = take(page.image.is_some()); let icc_obj = take(page.image.as_ref().is_some_and(|i| i.icc.is_some())); let gs_obj = take(!page.plates.is_empty()); - let first_plate = next; - let plate_objs: Vec = (0..page.plates.len()).map(|i| first_plate + i).collect(); + let plate_objs: Vec = page.plates.iter().filter_map(|_| take(true)).collect(); + let xmp_obj = take(page.xmp.is_some()); - obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>"); + let metadata = xmp_obj.map(|n| format!(" /Metadata {n} 0 R")).unwrap_or_default(); + obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{metadata} >>").as_bytes()); obj(&mut out, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); let mut xobjects = String::new(); if let Some(n) = image_obj { @@ -265,6 +274,14 @@ pub fn print_pdf(page: &PrintPage) -> Vec { // colour-key-masked Separation image.) obj(&mut out, &image_object(p.width, p.height, &cs, &p.data)); } + if let Some(xmp) = &page.xmp { + // Unfiltered, as the XMP specification asks of a packet in a PDF, so a reader can find it + // by scanning for the packet header. + let mut body = format!("<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n", xmp.len()).into_bytes(); + body.extend_from_slice(xmp.as_bytes()); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); + } let xref = out.len(); out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); for o in &offsets { @@ -274,6 +291,82 @@ pub fn print_pdf(page: &PrintPage) -> Vec { out } +/// `s` as XML character data. +fn xml_text(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + '"' => o.push_str("""), + c => o.push(c), + } + } + o +} + +/// The XMP namespace of the spot-plate description. +pub const SPOT_PLATES_NS: &str = "http://ns.getartcraft.com/photocraft/spot-plates/1.0/"; + +/// The XMP packet of a spot-plate PDF: the document's own packet (`doc_xmp`, if any) with one +/// `rdf:Description` added under [`SPOT_PLATES_NS`] that lists the plates in page order, so a +/// converter can rebuild each spot channel with its real ink colour, which the Separation +/// colour space's CMYK alternate cannot carry: +/// +/// ```xml +/// +/// +/// +/// +/// 0 +/// Underbase White +/// 100.00 +/// 0.00 +/// 0.00 +/// #FFFFFF +/// 100 +/// +/// +/// +/// +/// ``` +/// +/// An alpha-type channel of a Multichannel document lists as black with solidity 0. +fn plates_xmp(doc_xmp: Option<&str>, plates: &[SpotPlate]) -> String { + let mut d = format!(" \n \n \n"); + // Two decimals, never "-0.00". + let two = |v: f32| { + let v = (v * 100.0).round() / 100.0; + if v == 0.0 { 0.0 } else { v } + }; + for (i, p) in plates.iter().enumerate() { + let hex = p.srgb.map(|v| format!("{:02X}", (v.clamp(0.0, 1.0) * 255.0).round() as u8)).concat(); + d.push_str(&format!( + " \n {i}\n {}\n {:.2}\n {:.2}\n {:.2}\n #{hex}\n {}\n \n", + xml_text(&p.name), + two(p.lab[0]), + two(p.lab[1]), + two(p.lab[2]), + (p.solidity * 100.0).round() as u32 + )); + } + d.push_str(" \n \n \n"); + // Into the document's packet when it has one, before its ``; else a packet of its own. + if let Some(xmp) = doc_xmp + && let Some(at) = xmp.rfind("") + { + let mut out = String::with_capacity(xmp.len() + d.len()); + out.push_str(&xmp[..at]); + out.push_str(&d); + out.push_str(&xmp[at..]); + return out; + } + format!( + "\n\n \n{d} \n\n" + ) +} + /// The spot plates of `doc`, in channel order (the first channel prints first, underneath). /// /// In a Multichannel document every channel is a plate: its spot channels at the ink density @@ -297,7 +390,17 @@ fn plates_of(doc: &Document, w: usize, h: usize) -> Vec { let n = ch.surface.channels().max(1); let values = ch.surface.read_region(canvas); let data: Vec = values.chunks(n).map(|px| px.first().copied().unwrap_or(0.0)).map(|v| to8(if alpha_type { 1.0 - v } else { v })).collect(); - SpotPlate { name: ch.name.clone(), cmyk: ink.in_mode(ColorMode::Cmyk).c, width: w as u32, height: h as u32, data } + let srgb = ink.to_rgb(); + SpotPlate { + name: ch.name.clone(), + cmyk: ink.in_mode(ColorMode::Cmyk).c, + lab: photocraft_color::convert::srgb_to_lab(srgb), + srgb, + solidity: ch.spot.map_or(0.0, |(_, s)| s.clamp(0.0, 1.0)), + width: w as u32, + height: h as u32, + data, + } }) .collect() } @@ -311,6 +414,13 @@ fn plates_of(doc: &Document, w: usize, h: usize) -> Vec { /// channels, is written as plates alone. Without it a Multichannel document has nothing to /// write and is refused. pub fn export(doc: &Document, spot_plates: bool) -> std::result::Result { + export_with(doc, spot_plates, doc.metadata.xmp.as_deref()) +} + +/// [`export`] with the XMP packet to embed (`doc_xmp`: the document's, or `None` when the save +/// embeds no metadata). With spot plates the packet gains their description ([`plates_xmp`]); +/// without plates it is written as it is, and nothing when there is none. +pub fn export_with(doc: &Document, spot_plates: bool, doc_xmp: Option<&str>) -> std::result::Result { let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0)); if w == 0 || h == 0 { return Err(IoError::Unsupported("PDF needs a document with non-zero width and height; nothing was written".into())); @@ -366,7 +476,8 @@ pub fn export(doc: &Document, spot_plates: bool) -> std::result::Result String { + let start = pdf.windows(9).position(|w| w == b""; + let end = pdf[start..].windows(tail.len()).position(|w| w == tail).expect("packet end") + start + tail.len(); + String::from_utf8(pdf[start..end].to_vec()).unwrap() +} + +#[test] +fn the_plates_are_described_in_xmp_with_their_ink_colour_and_solidity() { + let mut d = Document::new("m.pdf", Size { width: 4, height: 2 }, ColorMode::Multichannel, SampleType::F32); + let ink = photocraft_color::Color::rgb(0.2, 0.3, 0.4); + d.channels.push(AlphaChannel { spot: Some((ink, 0.35)), ..AlphaChannel::new("Black (Ink) #1/ü & ", channel(&[1.0; 8])) }); + d.channels.push(spot("Underbase White", photocraft_color::Color::WHITE, &[0.0; 8])); + let out = export(&d, true).unwrap(); + let pdf = &out.bytes; + check_structure(pdf); + assert!(has(pdf, "/Type /Catalog /Pages 2 0 R /Metadata "), "the catalog points at the metadata stream"); + assert!(has(pdf, "/Type /Metadata /Subtype /XML /Length "), "an unfiltered XMP stream"); + let xmp = xmp_of(pdf); + assert!(xmp.contains("xmlns:pcsp=\"http://ns.getartcraft.com/photocraft/spot-plates/1.0/\""), "{xmp}"); + let lab = photocraft_color::convert::srgb_to_lab([0.2, 0.3, 0.4]); + let want = format!( + "\n 0\n Black (Ink) #1/ü & <x>\n {:.2}\n {:.2}\n {:.2}\n #334D66\n 35\n ", + lab[0], lab[1], lab[2] + ); + assert!(xmp.contains(&want), "first plate:\n{xmp}"); + assert!(xmp.contains("1\n Underbase White\n 100.00\n 0.00\n 0.00\n #FFFFFF\n 0"), "second plate:\n{xmp}"); + // The order is the plates' paint order, which is the Separation names' order in the page. + let pos = |needle: &str| pdf.windows(needle.len()).position(|w| w == needle.as_bytes()).expect(needle); + assert!(pos("/Separation /Black#20#28Ink") < pos("/Separation /Underbase#20White")); + // One packet, well-formed enough for an XML parser. + assert_eq!(xmp.matches("").unwrap() + 12], Default::default()).is_ok(), "{xmp}"); +} + +#[test] +fn the_plate_description_joins_the_documents_own_packet() { + let mut d = doc(ColorMode::Rgb); + d.channels.push(spot("Varnish", photocraft_color::Color::rgb(0.9, 0.9, 0.6), &[1.0; 8])); + d.metadata.xmp = Some(std::sync::Arc::from( + "\n\n \n Job 1\n \n\n", + )); + let out = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + let xmp = xmp_of(&out.bytes); + assert_eq!(xmp.matches("Job 1") && xmp.contains("Varnish"), "{xmp}"); + assert!(xmp.find("").unwrap() < xmp.find("").unwrap() && xmp.find("").unwrap() < xmp.rfind("").unwrap()); + // A save that embeds no metadata drops the document's packet but still describes the plates. + let none = crate::export(&d, "out.pdf", &crate::ExportOptions { xmp: crate::XmpEmbed::None, ..Default::default() }).unwrap(); + let xmp = xmp_of(&none.bytes); + assert!(!xmp.contains("dc:title") && xmp.contains("Varnish"), "{xmp}"); + // Without plates the document's packet travels as it is, and a document without one has no stream. + d.channels.clear(); + let plain = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + assert!(has(&plain.bytes, "Job 1") && !has(&plain.bytes, "pcsp:"), "the document packet alone"); + d.metadata.xmp = None; + let bare = export(&d, true).unwrap(); + assert!(!has(&bare.bytes, "/Metadata") && !has(&bare.bytes, " **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-29 · **Change:** minor (PDF: spot channels as overprinting `/Separation` plates, a Multichannel document as plates alone, FILE-215-17's PDF part; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-30 · **Change:** minor (PDF: spot plates described in XMP for converters, document XMP embedded; PDF: spot channels as overprinting `/Separation` plates, a Multichannel document as plates alone, FILE-215-17's PDF part; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 **PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. @@ -40,7 +40,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Portable Bit Map (PBM/PGM/PPM/PNM/PFM/PAM) | R/W | yes | yes | 8/16/32f | | FITS | R/W (FITS Liberator plug-in) | yes | yes | 8/16/32f gray or RGB, header cards kept; no fpack, no debayer | | Targa | R/W | yes | yes | 8-bit | -| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF); spot channels as overprinting `/Separation` plates after the image, a Multichannel document as its plates alone (FILE-215-17's PDF part) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541). Plates are 8-bit, named after the channel, 1 = solid ink, painted in channel order with `/OP true`; the tint transform's alternate is the ink colour separated to CMYK (preview only); solidity is not written; no printer marks, labels or halftone screens, as Photoshop's PDF has none either (scripts: `pdfSpotPlates: false` leaves the plates out). Ghostscript `tiffsep`/`psdcmyk` split the page into the named plates | +| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF); spot channels as overprinting `/Separation` plates after the image, a Multichannel document as its plates alone (FILE-215-17's PDF part) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541). Plates are 8-bit, named after the channel, 1 = solid ink, painted in channel order with `/OP true`; the tint transform's alternate is the ink colour separated to CMYK (preview only); solidity is not written; no printer marks, labels or halftone screens, as Photoshop's PDF has none either (scripts: `pdfSpotPlates: false` leaves the plates out); each plate's ink colour (Lab D50, sRGB) and solidity are described in the catalog's XMP packet (see Spot-plate PDF metadata below), and the document's own XMP travels in the same packet. Ghostscript `tiffsep`/`psdcmyk` split the page into the named plates | | Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | A spot-plate PDF (above) carries what a DCS 2.0 file carried to a RIP: one named plate per spot channel | | Generic EPS / AI | R (rasterize) | no | no | | | SVG | R (rasterize) | yes, as editable shape layers or a vector smart object | no | Better than Photoshop for editing; gradients approximated (FILE-215-9) | @@ -140,10 +140,32 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Curves `.acv`, Levels `.alv`, other adjustment presets | R/W | not audited | | | C2PA Content Credentials | R/W | no | #1050 | +## Spot-plate PDF metadata + +A PDF with spot plates (see Photoshop PDF above) carries, in the catalog's `/Metadata` XMP packet +(the document's own packet when it has one), one `rdf:Description` under the namespace +`http://ns.getartcraft.com/photocraft/spot-plates/1.0/` (prefix `pcsp`), so a converter can +rebuild each spot channel with its real ink colour, which the `/Separation` colour space's CMYK +alternate cannot carry. `pcsp:plates` is an `rdf:Seq` in paint order, one `rdf:li` +(`rdf:parseType="Resource"`) per plate: + +| Property | Value | +|---|---| +| `pcsp:index` | 0-based position in the sequence, the order the plates are painted (the first is underneath) | +| `pcsp:name` | the channel name, exactly the Separation colorant name (XML-escaped, UTF-8) | +| `pcsp:labL`, `pcsp:labA`, `pcsp:labB` | the ink colour as CIE L\*a\*b\*, D50, two decimals | +| `pcsp:srgb` | the same colour as encoded sRGB, `#RRGGBB` | +| `pcsp:solidity` | 0–100, Photoshop's Spot Channel Options › Solidity (0 for an alpha-type channel of a Multichannel document, which lists as black) | + +The packet is unfiltered, so it can be found by scanning for ` Date: Fri, 30 Oct 2026 18:00:58 -0400 Subject: [PATCH 4/8] PDF spot plates: say where solidity goes The plates_of doc and the file-format-parity PDF row still said solidity "is not written"; since the XMP description it is carried as pcsp:solidity. Both now say it does not change the plate image or tint transform and that only the XMP description carries it. Co-Authored-By: Claude Fable 5.1 --- crates/io/src/pdf.rs | 3 ++- docs/file-format-parity.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 1afb7debe37..3c127a29b4a 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -374,7 +374,8 @@ fn plates_xmp(doc_xmp: Option<&str>, plates: &[SpotPlate]) -> String { /// it as (1 − value, as `photocraft_compose::multichannel` prints it). Any other document keeps /// its alpha channels as masks and exports only its spot channels. The alternate colour is the /// ink colour separated through the CMYK profile in use (`Color::in_mode`); it only previews the -/// plate, as Photoshop's does. Solidity is a preview attribute too and is not written. +/// plate, as Photoshop's does. Solidity is a preview attribute too: it is not part of the plate +/// image or its tint transform, and only the XMP description ([`plates_xmp`]) carries it. fn plates_of(doc: &Document, w: usize, h: usize) -> Vec { let multichannel = doc.mode == ColorMode::Multichannel; let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5bbc14573fa..115553b24a8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -40,7 +40,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Portable Bit Map (PBM/PGM/PPM/PNM/PFM/PAM) | R/W | yes | yes | 8/16/32f | | FITS | R/W (FITS Liberator plug-in) | yes | yes | 8/16/32f gray or RGB, header cards kept; no fpack, no debayer | | Targa | R/W | yes | yes | 8-bit | -| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF); spot channels as overprinting `/Separation` plates after the image, a Multichannel document as its plates alone (FILE-215-17's PDF part) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541). Plates are 8-bit, named after the channel, 1 = solid ink, painted in channel order with `/OP true`; the tint transform's alternate is the ink colour separated to CMYK (preview only); solidity is not written; no printer marks, labels or halftone screens, as Photoshop's PDF has none either (scripts: `pdfSpotPlates: false` leaves the plates out); each plate's ink colour (Lab D50, sRGB) and solidity are described in the catalog's XMP packet (see Spot-plate PDF metadata below), and the document's own XMP travels in the same packet. Ghostscript `tiffsep`/`psdcmyk` split the page into the named plates | +| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF); spot channels as overprinting `/Separation` plates after the image, a Multichannel document as its plates alone (FILE-215-17's PDF part) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541). Plates are 8-bit, named after the channel, 1 = solid ink, painted in channel order with `/OP true`; the tint transform's alternate is the ink colour separated to CMYK (preview only); solidity does not change the plate image or tint transform and is carried only in the XMP description; no printer marks, labels or halftone screens, as Photoshop's PDF has none either (scripts: `pdfSpotPlates: false` leaves the plates out); each plate's ink colour (Lab D50, sRGB) and solidity are described in the catalog's XMP packet (see Spot-plate PDF metadata below), and the document's own XMP travels in the same packet. Ghostscript `tiffsep`/`psdcmyk` split the page into the named plates | | Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | A spot-plate PDF (above) carries what a DCS 2.0 file carried to a RIP: one named plate per spot channel | | Generic EPS / AI | R (rasterize) | no | no | | | SVG | R (rasterize) | yes, as editable shape layers or a vector smart object | no | Better than Photoshop for editing; gradients approximated (FILE-215-9) | From b7ea677ebaeb86430eff29b10a224bea5c051eed Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Fri, 30 Oct 2026 18:13:31 -0400 Subject: [PATCH 5/8] PDF spot plates: find the packet's RDF end tag however it is spelled plates_xmp merged the plate description only before a literal ``; a document packet that binds another prefix to RDF, or has whitespace before the `>`, lost its own XMP to a plate-only packet. rdf_end now finds the last RDF end tag in any spelling, and a packet with no RDF element at all is kept as it is rather than replaced. One test for both cases. Co-Authored-By: Claude Fable 5.1 --- crates/io/src/pdf.rs | 28 ++++++++++++++++++++++++---- crates/io/src/pdf/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 3c127a29b4a..915894d0f09 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -306,6 +306,23 @@ fn xml_text(s: &str) -> String { o } +/// Where the RDF element of an XMP packet ends: the start of its last `` end tag, +/// whatever prefix the packet binds to RDF and with any whitespace before the `>`. +fn rdf_end(xmp: &str) -> Option { + let mut before = xmp.len(); + while let Some(at) = xmp[..before].rfind("').unwrap_or(rest.len()); + let name = &rest[..name_len]; + let local = name.rsplit(':').next().unwrap_or(name); + if local == "RDF" && rest[name_len..].trim_start().starts_with('>') { + return Some(at); + } + before = at; + } + None +} + /// The XMP namespace of the spot-plate description. pub const SPOT_PLATES_NS: &str = "http://ns.getartcraft.com/photocraft/spot-plates/1.0/"; @@ -352,10 +369,13 @@ fn plates_xmp(doc_xmp: Option<&str>, plates: &[SpotPlate]) -> String { )); } d.push_str(" \n \n \n"); - // Into the document's packet when it has one, before its ``; else a packet of its own. - if let Some(xmp) = doc_xmp - && let Some(at) = xmp.rfind("") - { + // Into the document's packet when it has one, before the end tag of its RDF element; else a + // packet of its own. A packet with no RDF element has nowhere for the description to go and is + // kept as it is rather than replaced. + if let Some(xmp) = doc_xmp { + let Some(at) = rdf_end(xmp) else { + return xmp.to_owned(); + }; let mut out = String::with_capacity(xmp.len() + d.len()); out.push_str(&xmp[..at]); out.push_str(&d); diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index bc942425aa4..062db12eb8b 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -330,3 +330,23 @@ fn the_plate_description_joins_the_documents_own_packet() { assert!(!has(&bare.bytes, "/Metadata") && !has(&bare.bytes, "` of the end tag. + d.metadata.xmp = Some(std::sync::Arc::from( + "\n\n \n Job 2\n \n\n", + )); + let out = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + let xmp = xmp_of(&out.bytes); + assert_eq!(xmp.matches("Job 2") && xmp.contains("Varnish"), "{xmp}"); + assert!(xmp.find("").unwrap() < xmp.rfind("").unwrap(), "the plates are inside the RDF element: {xmp}"); + // A packet with no RDF element is kept as it is; the plates go undescribed rather than the packet lost. + let no_rdf = "\nkept\n"; + d.metadata.xmp = Some(std::sync::Arc::from(no_rdf)); + let out = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + assert_eq!(xmp_of(&out.bytes), no_rdf); +} From f1ac57616cdd1147fdcb2bde84a44e3fd74b54aa Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Fri, 30 Oct 2026 18:25:00 -0400 Subject: [PATCH 6/8] PDF spot plates: join the RDF element as XML, and bind rdf in the description The plate description is inserted where roxmltree finds the packet's RDF element (by namespace, not spelling), before its end tag or by expanding a self-closing one; an end tag spelled out in a comment no longer misleads it, and a packet that does not parse or has no RDF element is kept as it is. The description declares xmlns:rdf itself, so a packet that binds another prefix to RDF stays valid namespaced XML. The test parses every fixture back and checks the plates sit in an rdf:Description inside the RDF element. Co-Authored-By: Claude Fable 5.1 --- crates/io/src/pdf.rs | 72 +++++++++++++++++++++++++------------- crates/io/src/pdf/tests.rs | 55 +++++++++++++++++++++-------- 2 files changed, 88 insertions(+), 39 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 915894d0f09..fca9771baa8 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -306,21 +306,30 @@ fn xml_text(s: &str) -> String { o } -/// Where the RDF element of an XMP packet ends: the start of its last `` end tag, -/// whatever prefix the packet binds to RDF and with any whitespace before the `>`. -fn rdf_end(xmp: &str) -> Option { - let mut before = xmp.len(); - while let Some(at) = xmp[..before].rfind("').unwrap_or(rest.len()); - let name = &rest[..name_len]; - let local = name.rsplit(':').next().unwrap_or(name); - if local == "RDF" && rest[name_len..].trim_start().starts_with('>') { - return Some(at); - } - before = at; +/// The RDF namespace every XMP packet's `rdf:RDF` element is in. +const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + +/// Where a description joins an XMP packet's RDF element, found as XML rather than by its +/// spelling, so the prefix the packet binds to RDF, whitespace in its end tag and markup in +/// comments make no difference: the byte offset of the element's end tag (`closed` false), or of +/// the `/>` of a self-closing element (`closed` true) together with its qualified name, so the +/// caller can expand it. None when the packet does not parse or has no RDF element. +fn rdf_insertion(xmp: &str) -> Option<(usize, Option<&str>)> { + // roxmltree does not take a byte order mark ahead of the prolog; offsets below are into `xmp`. + let bom = xmp.strip_prefix('\u{feff}').map_or(0, |_| '\u{feff}'.len_utf8()); + let body = &xmp[bom..]; + let doc = crate::xml::parse(body, roxmltree::ParsingOptions::default()).ok()?; + let rdf = doc.descendants().find(|n| n.is_element() && n.tag_name().namespace() == Some(RDF_NS) && n.tag_name().name() == "RDF")?; + let range = rdf.range(); + let text = body.get(range.clone())?; + if let Some(open) = text.strip_suffix("/>") { + // ``: the qualified name follows the `<`, up to whitespace or the `/`. + let name = open.get(1..)?; + let end = name.find(|c: char| c.is_whitespace() || c == '/').unwrap_or(name.len()); + return Some((bom + range.end - 2, Some(&name[..end]))); } - None + // The end tag is the last thing in the element's own range. + Some((bom + range.start + text.rfind(" +/// /// /// /// @@ -351,7 +361,8 @@ pub const SPOT_PLATES_NS: &str = "http://ns.getartcraft.com/photocraft/spot-plat /// /// An alpha-type channel of a Multichannel document lists as black with solidity 0. fn plates_xmp(doc_xmp: Option<&str>, plates: &[SpotPlate]) -> String { - let mut d = format!(" \n \n \n"); + // The description binds `rdf` itself: the packet it joins may bind another prefix to RDF. + let mut d = format!(" \n \n \n"); // Two decimals, never "-0.00". let two = |v: f32| { let v = (v * 100.0).round() / 100.0; @@ -369,21 +380,34 @@ fn plates_xmp(doc_xmp: Option<&str>, plates: &[SpotPlate]) -> String { )); } d.push_str(" \n \n \n"); - // Into the document's packet when it has one, before the end tag of its RDF element; else a - // packet of its own. A packet with no RDF element has nowhere for the description to go and is - // kept as it is rather than replaced. + // Into the document's packet when it has one, inside its RDF element; else a packet of its + // own. A packet that does not parse or has no RDF element has nowhere for the description to + // go and is kept as it is rather than replaced. if let Some(xmp) = doc_xmp { - let Some(at) = rdf_end(xmp) else { + let Some((at, self_closing)) = rdf_insertion(xmp) else { return xmp.to_owned(); }; - let mut out = String::with_capacity(xmp.len() + d.len()); + let mut out = String::with_capacity(xmp.len() + d.len() + 16); out.push_str(&xmp[..at]); - out.push_str(&d); - out.push_str(&xmp[at..]); + match self_closing { + // `` becomes `` + the description + ``. + Some(name) => { + out.push_str(">\n"); + out.push_str(&d); + out.push_str(" '); + out.push_str(&xmp[at + 2..]); + } + None => { + out.push_str(&d); + out.push_str(&xmp[at..]); + } + } return out; } format!( - "\n\n \n{d} \n\n" + "\n\n \n{d} \n\n" ) } diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 062db12eb8b..e504e9aff63 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -332,21 +332,46 @@ fn the_plate_description_joins_the_documents_own_packet() { } #[test] -fn the_plate_description_finds_the_rdf_end_tag_however_it_is_spelled() { +fn the_plate_description_joins_the_rdf_element_however_the_packet_spells_it() { + const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; let mut d = doc(ColorMode::Rgb); d.channels.push(spot("Varnish", photocraft_color::Color::rgb(0.9, 0.9, 0.6), &[1.0; 8])); - // Another prefix bound to RDF, and whitespace before the `>` of the end tag. - d.metadata.xmp = Some(std::sync::Arc::from( - "\n\n \n Job 2\n \n\n", - )); - let out = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); - let xmp = xmp_of(&out.bytes); - assert_eq!(xmp.matches("Job 2") && xmp.contains("Varnish"), "{xmp}"); - assert!(xmp.find("").unwrap() < xmp.rfind("").unwrap(), "the plates are inside the RDF element: {xmp}"); - // A packet with no RDF element is kept as it is; the plates go undescribed rather than the packet lost. - let no_rdf = "\nkept\n"; - d.metadata.xmp = Some(std::sync::Arc::from(no_rdf)); - let out = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); - assert_eq!(xmp_of(&out.bytes), no_rdf); + // The packet must parse as namespaced XML with the plates a description inside its RDF element. + let plates_in_rdf = |xmp: &str| { + let tree = crate::xml::parse(xmp.trim_start_matches('\u{feff}'), roxmltree::ParsingOptions::default()).unwrap_or_else(|e| panic!("{e}: {xmp}")); + let plates = tree + .descendants() + .find(|n| n.tag_name().namespace() == Some(crate::pdf::SPOT_PLATES_NS) && n.tag_name().name() == "plates") + .unwrap_or_else(|| panic!("no pcsp:plates: {xmp}")); + let description = plates.parent_element().unwrap(); + assert_eq!((description.tag_name().namespace(), description.tag_name().name()), (Some(RDF), "Description"), "{xmp}"); + let rdf = description.parent_element().unwrap(); + assert_eq!((rdf.tag_name().namespace(), rdf.tag_name().name()), (Some(RDF), "RDF"), "{xmp}"); + assert_eq!(xmp.matches("\n\n"; + let tail = "\n\n"; + let title = "Job 2"; + for (packet, what) in [ + // Another prefix bound to RDF, whitespace before the `>` of the end tag, a leading byte order mark. + (format!("\u{feff}{head} \n {title}\n {tail}"), "prefix, whitespace and BOM"), + // An end tag spelled out inside a comment is not the element's end. + (format!("{head} \n \n {}\n {tail}", title.replace("r:", "rdf:")), "comment"), + // A self-closing RDF element is expanded around the description. + (format!("{head} {tail}"), "self-closing"), + ] { + d.metadata.xmp = Some(std::sync::Arc::from(packet.as_str())); + let out = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + let xmp = xmp_of(&out.bytes); + plates_in_rdf(&xmp); + assert_eq!(xmp.contains("Job 2"), what != "self-closing", "{what}: {xmp}"); + assert!(xmp.contains("Varnish"), "{what}: {xmp}"); + } + // A packet with no RDF element, or that is not XML, is kept as it is: the plates go undescribed + // rather than the document's metadata lost. + for kept in [format!("{head}kept{tail}"), format!("{head}{tail}")] { + d.metadata.xmp = Some(std::sync::Arc::from(kept.as_str())); + let out = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap(); + assert_eq!(xmp_of(&out.bytes), kept); + } } From 7bf102a3e3e4f26995c3a3db1164d140d4cd5a90 Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Sat, 31 Oct 2026 15:12:43 -0400 Subject: [PATCH 7/8] PDF: say that pdfSpotPlates false refuses a Multichannel document, and what XmpEmbed::None leaves out The option's doc on ExportOptions, the command spec strings, the control-protocol doc.save row and the parity row all said `false` writes the image only; a Multichannel document has no image, so the exporter refuses it, and the docs now say so. XmpEmbed::None omits the document's own packet and free-form text, not the metadata a format writes about the file itself, such as the PDF spot-plate description. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/file_cmds.rs | 8 ++++---- crates/io/src/lib.rs | 7 +++++-- docs/control-protocol.md | 2 +- docs/file-format-parity.md | 2 +- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 096344e0170..56675111da6 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -243,7 +243,7 @@ pub fn specs() -> Vec { "Save a Copy…", &["File"], Some("Cmd+Alt+S"), - r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone)}"##, + r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)}"##, native_doc, save_a_copy ), @@ -306,7 +306,7 @@ pub fn specs() -> Vec { "Batch…", &["File", "Automate"], None, - r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, batch ), @@ -315,7 +315,7 @@ pub fn specs() -> Vec { "Image Processor…", &["File", "Scripts"], None, - r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, image_processor ), @@ -343,7 +343,7 @@ pub fn specs() -> Vec { "Layers to Files…", &["File", "Export"], None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, native_doc, layers_to_files ), diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 12cdfb14a36..b1f2fffed47 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -204,7 +204,8 @@ pub enum XmpEmbed { /// Embed the document's whole XMP packet and free-form text. #[default] All, - /// Embed no XMP or free-form text. + /// Leave the document's own XMP packet and free-form text out. Metadata a format writes + /// about the file itself, such as a PDF's spot-plate description, is still written. None, } @@ -244,7 +245,9 @@ pub struct ExportOptions { pub read_linked_files: bool, /// PDF: write the document's spot channels as overprinting `/Separation` plates after the /// flattened image, and a Multichannel document as its plates alone (FILE-215-17). On by - /// default; `false` writes the flattened image only (`"pdfSpotPlates": false`). + /// default; `false` (`"pdfSpotPlates": false`) writes the flattened image only, so an RGB, + /// Grayscale or CMYK document loses its plates and a Multichannel document, which has no + /// image to write, is refused. pub pdf_spot_plates: bool, } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b5c196a2a4d..0d3885c015e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -440,7 +440,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index b9c28a0373e..e70116282fe 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -40,7 +40,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Portable Bit Map (PBM/PGM/PPM/PNM/PFM/PAM) | R/W | yes | yes | 8/16/32f | | FITS | R/W (FITS Liberator plug-in) | yes | yes | 8/16/32f gray or RGB, header cards kept; no fpack, no debayer | | Targa | R/W | yes | yes | 8-bit | -| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF); spot channels as overprinting `/Separation` plates after the image, a Multichannel document as its plates alone (FILE-215-17's PDF part) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541). Plates are 8-bit, named after the channel, 1 = solid ink, painted in channel order with `/OP true`; the tint transform's alternate is the ink colour separated to CMYK (preview only); solidity does not change the plate image or tint transform and is carried only in the XMP description; no printer marks, labels or halftone screens, as Photoshop's PDF has none either (scripts: `pdfSpotPlates: false` leaves the plates out); each plate's ink colour (Lab D50, sRGB) and solidity are described in the catalog's XMP packet (see Spot-plate PDF metadata below), and the document's own XMP travels in the same packet. Ghostscript `tiffsep`/`psdcmyk` split the page into the named plates | +| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF); spot channels as overprinting `/Separation` plates after the image, a Multichannel document as its plates alone (FILE-215-17's PDF part) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541). Plates are 8-bit, named after the channel, 1 = solid ink, painted in channel order with `/OP true`; the tint transform's alternate is the ink colour separated to CMYK (preview only); solidity does not change the plate image or tint transform and is carried only in the XMP description; no printer marks, labels or halftone screens, as Photoshop's PDF has none either (scripts: `pdfSpotPlates: false` leaves the plates out and refuses a Multichannel document, which has nothing else to write); each plate's ink colour (Lab D50, sRGB) and solidity are described in the catalog's XMP packet (see Spot-plate PDF metadata below), and the document's own XMP travels in the same packet. Ghostscript `tiffsep`/`psdcmyk` split the page into the named plates | | Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | A spot-plate PDF (above) carries what a DCS 2.0 file carried to a RIP: one named plate per spot channel | | Generic EPS / AI | R (rasterize) | no | no | | | SVG | R (rasterize) | yes, as editable shape layers or a vector smart object | no | Better than Photoshop for editing; gradients approximated (FILE-215-9) | From 2f5c4fc650ba49efb840f7ff5e7cd8f986bb7fa5 Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Thu, 5 Nov 2026 19:59:58 -0500 Subject: [PATCH 8/8] Review: comma before pdfSpotPlates in file.layersToFiles; XMP offsets via get() file.layersToFiles' params doc lost the comma between ddsMipmaps and pdfSpotPlates in a merge; the other three spec strings had it. plates_xmp and rdf_insertion slice the document's XMP packet with str::get rather than indexing. The offsets come from the parsed XML and land on char boundaries, but a document-supplied packet must never panic, so an offset off a boundary now keeps the packet as it is, like one that does not parse or has no RDF element. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/file_cmds.rs | 2 +- crates/io/src/pdf.rs | 21 ++++++++++++--------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index d858e906714..69176ff8779 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -384,7 +384,7 @@ pub fn specs() -> Vec { "Layers to Files…", &["File", "Export"], None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, native_doc, layers_to_files ), diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 1cf3df1264e..3e5f3ea233a 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -334,7 +334,7 @@ const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; fn rdf_insertion(xmp: &str) -> Option<(usize, Option<&str>)> { // roxmltree does not take a byte order mark ahead of the prolog; offsets below are into `xmp`. let bom = xmp.strip_prefix('\u{feff}').map_or(0, |_| '\u{feff}'.len_utf8()); - let body = &xmp[bom..]; + let body = xmp.get(bom..)?; let doc = crate::xml::parse(body, roxmltree::ParsingOptions::default()).ok()?; let rdf = doc.descendants().find(|n| n.is_element() && n.tag_name().namespace() == Some(RDF_NS) && n.tag_name().name() == "RDF")?; let range = rdf.range(); @@ -343,7 +343,7 @@ fn rdf_insertion(xmp: &str) -> Option<(usize, Option<&str>)> { // ``: the qualified name follows the `<`, up to whitespace or the `/`. let name = open.get(1..)?; let end = name.find(|c: char| c.is_whitespace() || c == '/').unwrap_or(name.len()); - return Some((bom + range.end - 2, Some(&name[..end]))); + return Some((bom + range.end - 2, Some(name.get(..end)?))); } // The end tag is the last thing in the element's own range. Some((bom + range.start + text.rfind(", plates: &[SpotPlate]) -> String { d.push_str(" \n \n \n"); // Into the document's packet when it has one, inside its RDF element; else a packet of its // own. A packet that does not parse or has no RDF element has nowhere for the description to - // go and is kept as it is rather than replaced. + // go and is kept as it is rather than replaced; so is one whose insertion offset falls off a + // char boundary, which the parser never yields but a document-supplied packet must not panic. if let Some(xmp) = doc_xmp { let Some((at, self_closing)) = rdf_insertion(xmp) else { return xmp.to_owned(); }; + // A self-closing element's tail skips its `/>`. + let tail_at = if self_closing.is_some() { at + 2 } else { at }; + let (Some(head), Some(tail)) = (xmp.get(..at), xmp.get(tail_at..)) else { + return xmp.to_owned(); + }; let mut out = String::with_capacity(xmp.len() + d.len() + 16); - out.push_str(&xmp[..at]); + out.push_str(head); match self_closing { // `` becomes `` + the description + ``. Some(name) => { @@ -414,13 +420,10 @@ fn plates_xmp(doc_xmp: Option<&str>, plates: &[SpotPlate]) -> String { out.push_str(" '); - out.push_str(&xmp[at + 2..]); - } - None => { - out.push_str(&d); - out.push_str(&xmp[at..]); } + None => out.push_str(&d), } + out.push_str(tail); return out; } format!(