Merge pull request #10384 from ingling/pdf-spot-plates

PDF: spot channels as overprinting Separation plates (FILE-215-17)
This commit is contained in:
Tanish Manku authored and GitHub committed 2026-11-11 00:15:13 -07:00
commit 0fc597634a
11 files changed
+884 -156

No files matched your search

+2
View File
@@ -168,9 +168,11 @@ 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 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,
pcraft_full_composite: photocraft_engine::file_cmds::pcraft_full_composite_param(&p, "doc.save")
.map_err(|e| bad(e.to_string()))?
.unwrap_or(false),
+6
View File
@@ -217,6 +217,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<bool>,
/// .pcraft: request the flattened document at its canvas size as `composite/full.png`.
/// The save may omit it; check the manifest's `full_composite` member. Off by default.
#[serde(default, rename = "pcraftFullComposite")]
@@ -1213,6 +1217,7 @@ impl PhotocraftMcp {
p.tiff_layers.then_some("tiffLayers"),
p.pcraft_full_composite.is_some().then_some("pcraftFullComposite"),
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()
@@ -1255,6 +1260,7 @@ impl PhotocraftMcp {
tiff_layers: p.tiff_layers,
tiff_transparency: p.tiff_transparency,
tga_bits,
pdf_spot_plates: p.pdf_spot_plates.unwrap_or(true),
pcraft_full_composite: p.pcraft_full_composite.unwrap_or(false),
..Default::default()
};
+6 -6
View File
@@ -66,8 +66,8 @@ use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatte
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, maximize_compatibility_param, pcraft_full_composite_param, tga_bits_param, tiff_bool_param,
tiff_compression_param, tiff_would_write_layers,
dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, maximize_compatibility_param, pcraft_full_composite_param, pdf_spot_plates_param,
tga_bits_param, tiff_bool_param, tiff_compression_param, tiff_would_write_layers,
};
mod batch_naming;
@@ -279,7 +279,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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),"tiffTransparency":bool? (TIFF: Save Transparency; off composites over white; unset, kept unless the document has alpha or spot channels),"tiffPyramid":bool=false (TIFF: Save Image Pyramid, half-size copies after the image),"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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pcraftFullComposite":bool? (.pcraft: request the flattened document at its canvas size as composite/full.png; it may be omitted; check the manifest's full_composite member; unset, Preferences › File Handling)}"##,
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),"tiffTransparency":bool? (TIFF: Save Transparency; off composites over white; unset, kept unless the document has alpha or spot channels),"tiffPyramid":bool=false (TIFF: Save Image Pyramid, half-size copies after the image),"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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"pcraftFullComposite":bool? (.pcraft: request the flattened document at its canvas size as composite/full.png; it may be omitted; check the manifest's full_composite member; unset, Preferences › File Handling)}"##,
native_doc,
save_a_copy
),
@@ -365,7 +365,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
&["File", "Automate"],
None,
r##"{"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (for a named action),"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),"source":"folder|open"="folder" (open runs on live documents),"input":folder|[paths] (folder source),"errorLog":path? (blank disables it),"suppressOpenOptions":bool=false (use caller RAW defaults and fully supported prior XMP without a dialog; unsupported prior settings or unanswerable profile questions fail the input),"suppressWarnings":bool=false (apply caller opening policy without profile questions; import diagnostics remain in notices),"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; ordinary outputs are flat; namingComponents can retain subfolders when flatOutput is false),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only; put every result directly under output, dropping its subfolder path; duplicate output names make later results error entries),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}/{NAME}/{Name}, {serial}/{serial:1..4}, {letter}/{LETTER}, {date} and date formats, {ext}/{EXT}; template determines the whole filename),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"calledActions":[{"name","steps"}…]? (internal action references; default: the session's; a named source is selected from the caller)} → {files, errors, stopped?, skipped?, errorLog?, documents?} (structured naming, includeNonImages and Save and Close refuse duplicate results; ordinary native templates keep the later result)"##,
r##"{"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (for a named action),"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),"source":"folder|open"="folder" (open runs on live documents),"input":folder|[paths] (folder source),"errorLog":path? (blank disables it),"suppressOpenOptions":bool=false (use caller RAW defaults and fully supported prior XMP without a dialog; unsupported prior settings or unanswerable profile questions fail the input),"suppressWarnings":bool=false (apply caller opening policy without profile questions; import diagnostics remain in notices),"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; ordinary outputs are flat; namingComponents can retain subfolders when flatOutput is false),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only; put every result directly under output, dropping its subfolder path; duplicate output names make later results error entries),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}/{NAME}/{Name}, {serial}/{serial:1..4}, {letter}/{LETTER}, {date} and date formats, {ext}/{EXT}; template determines the whole filename),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"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"}…]? (internal action references; default: the session's; a named source is selected from the caller)} → {files, errors, stopped?, skipped?, errorLog?, documents?} (structured naming, includeNonImages and Save and Close refuse duplicate results; ordinary native templates keep the later result)"##,
native,
batch
),
@@ -374,7 +374,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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"?,"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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"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"?,"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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"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
),
@@ -402,7 +402,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility)} → {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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"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
),
+15
View File
@@ -36,6 +36,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
@@ -60,6 +63,7 @@ impl Default for SaveOpts {
preserve_alpha: false,
tiff_pyramid: false,
dds: photocraft_io::DdsOptions::default(),
pdf_spot_plates: true,
image_previews: true,
psd_maximize_compatibility: true,
pcraft_full_composite: false,
@@ -88,6 +92,7 @@ impl SaveOpts {
preserve_alpha: false,
tiff_pyramid: tiff_bool_param(p, "tiffPyramid", cmd)?.unwrap_or(false),
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: maximize_compatibility_param(p, cmd)?.unwrap_or(file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never),
pcraft_full_composite: pcraft_full_composite_param(p, cmd)?.unwrap_or(file_handling.pcraft_full_composite),
@@ -106,6 +111,15 @@ impl From<Option<f64>> 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<bool> {
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).
@@ -236,6 +250,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> R
tiff_transparency: save.tiff_transparency,
preserve_alpha: save.preserve_alpha,
tga_bits: save.tga_bits,
pdf_spot_plates: save.pdf_spot_plates,
image_previews: save.image_previews,
psd_maximize_compatibility: save.psd_maximize_compatibility,
pcraft_full_composite: save.pcraft_full_composite,
+28
View File
@@ -1684,6 +1684,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]
+11 -2
View File
@@ -384,7 +384,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,
}
@@ -432,6 +433,12 @@ 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` (`"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,
/// `.pcraft`: request the flattened document at its canvas size as `composite/full.png`
/// (Preferences › File Handling › Save Full-Size Composite in .pcraft Files). The save may
/// omit it; check the manifest's `full_composite` member ([`photocraft_format::read_full_composite`]
@@ -454,6 +461,7 @@ impl Default for ExportOptions {
document_path: None,
pcraft_cache: None,
read_linked_files: true,
pdf_spot_plates: true,
pcraft_full_composite: false,
}
}
@@ -1205,7 +1213,8 @@ fn export_stages_with_renderer(
return Ok(res.into());
}
if ext == "pdf" {
let mut res = pdf::export(doc, ctl)?;
let xmp = if opts.xmp == XmpEmbed::All { doc.metadata.xmp.as_deref() } else { None };
let mut res = pdf::export_with(doc, opts.pdf_spot_plates, xmp, ctl)?;
if let Some(r) = renderer {
res.warnings.push("PDF export uses CPU compositor; GPU rendering applies to flat formats".into());
res.warnings.extend(r.drain_diagnostics());
+455 -115
View File
@@ -6,6 +6,14 @@
//! 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).
//!
//! 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, 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". An artboard page carries its own region of every plate.
use std::io::Write as _;
@@ -28,6 +36,24 @@ pub struct PrintImage {
pub icc: Option<Vec<u8>>,
}
/// 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],
/// 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<u8>,
}
/// Printer marks around the image.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Marks {
@@ -36,16 +62,21 @@ 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<PrintImage>,
pub rect: (f64, f64, f64, f64),
pub marks: Marks,
pub description: Option<String>,
pub label: Option<String>,
/// The page's name in the PDF `/PageLabels` tree (Unicode-capable; not drawn on the page).
pub page_label: Option<String>,
pub plates: Vec<SpotPlate>,
}
pub(super) fn pdf_string(s: &str) -> String {
@@ -74,6 +105,25 @@ fn pdf_unicode_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<u8> {
// 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
@@ -119,22 +169,46 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String {
s
}
/// A one-page PDF.
pub fn print_pdf(page: &PrintPage) -> Vec<u8> {
print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default(), &photocraft_raster::Interrupt::NONE).unwrap_or_default()
/// 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<u8> {
let z = deflate(data);
let mut body = format!(
"<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace {colour_space} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n",
z.len()
)
.into_bytes();
body.extend_from_slice(&z);
body.extend_from_slice(b"\nendstream");
body
}
/// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`.
/// A one-page PDF.
pub fn print_pdf(page: &PrintPage) -> Vec<u8> {
print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default(), None, &photocraft_raster::Interrupt::NONE)
.unwrap_or_default()
}
/// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`, after its
/// image and before its plates and marks (the top layers kept as paths and selectable text), and
/// the selection font their text refers to is `/FSelect`. `xmp` is the packet of the catalog's
/// `/Metadata` stream, if any.
///
/// Objects: 1 catalog, 2 pages, then per page its page, contents, image and one XObject per
/// plate; then the shared font, ICC profile, overprint ExtGState and XMP metadata stream, each
/// only when present, the selection font's three objects, and last the page-label tree.
fn print_pdf_pages(
pages: &[PrintPage],
vectors: &[String],
selection_font: &selection::SelectionFont,
xmp: Option<&str>,
ctl: &photocraft_raster::Interrupt,
) -> std::result::Result<Vec<u8>, IoError> {
if ctl.check().is_err() {
return Err(IoError::Cancelled);
}
let Some(first) = pages.first() else { return Ok(Vec::new()) };
if pages.is_empty() {
return Ok(Vec::new());
}
let mut out: Vec<u8> = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec();
let mut offsets: Vec<usize> = Vec::new();
let mut obj = |out: &mut Vec<u8>, body: &[u8]| {
@@ -147,34 +221,79 @@ fn print_pdf_pages(
// A label tree is written only for a non-empty name: an all-empty tree would be `/Nums []`,
// and filtering the first empty name away would start the tree at page index 1, not 0.
let labels_on = pages.iter().any(|p| p.page_label.as_deref().is_some_and(|label| !label.is_empty()));
// 1 catalog, 2 pages, then per page: page, contents, image; then the shared font/ICC/selection.
let font_obj = 3 + n * 3;
let icc = first.image.icc.as_ref();
let icc_obj = icc.map(|_| font_obj + 1);
let selection_base = font_obj + if icc.is_some() { 2 } else { 1 };
// Object numbers, handed out in the order the objects are written.
let mut next = 3usize;
let mut take = |present: bool| {
let o = present.then_some(next);
next += usize::from(present);
o
};
struct PageObjects {
page: usize,
contents: usize,
image: Option<usize>,
plates: Vec<usize>,
}
// Field initialisers run in this order.
let page_objects: Vec<PageObjects> = pages
.iter()
.map(|p| PageObjects {
page: take(true).unwrap_or_default(),
contents: take(true).unwrap_or_default(),
image: take(p.image.is_some()),
plates: p.plates.iter().filter_map(|_| take(true)).collect(),
})
.collect();
let font_obj = take(true).unwrap_or_default();
// The profile is the document's, shared by every page's image.
let icc = pages.iter().find_map(|p| p.image.as_ref().and_then(|i| i.icc.as_ref().map(|icc| (icc, i.channels))));
let icc_obj = take(icc.is_some());
let gs_obj = take(pages.iter().any(|p| !p.plates.is_empty()));
let xmp_obj = take(xmp.is_some());
let selection_base = next;
let selection_objects = selection_font.objects(selection_base);
let labels_obj = labels_on.then_some((selection_base + selection_objects.len()) as u32);
obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{} >>", labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default()).as_bytes());
let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::<Vec<_>>().join(" ");
let labels_obj = labels_on.then_some(selection_base + selection_objects.len());
let metadata = xmp_obj.map(|o| format!(" /Metadata {o} 0 R")).unwrap_or_default();
let page_labels = labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default();
obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{metadata}{page_labels} >>").as_bytes());
let kids = page_objects.iter().map(|p| format!("{} 0 R", p.page)).collect::<Vec<_>>().join(" ");
obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes());
for (i, page) in pages.iter().enumerate() {
let page_obj = 3 + i * 3;
let content_obj = page_obj + 1;
let image_obj = page_obj + 2;
for (i, (page, objects)) in pages.iter().zip(&page_objects).enumerate() {
let (pw, ph) = page.paper;
let (x, y, w, h) = page.rect;
let mut xobjects = String::new();
if let Some(o) = objects.image {
xobjects.push_str(&format!("/Im0 {o} 0 R "));
}
for (k, o) in objects.plates.iter().enumerate() {
xobjects.push_str(&format!("/Sp{k} {o} 0 R "));
}
let ext_gstate = match gs_obj {
Some(o) if !page.plates.is_empty() => format!("/ExtGState << /GS0 {o} 0 R >> "),
_ => String::new(),
};
obj(
&mut out,
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 {image_obj} 0 R >> /Font << /F1 {font_obj} 0 R /FSelect {selection_base} 0 R >> >> /Contents {content_obj} 0 R >>"
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << {xobjects}>> {ext_gstate}/Font << /F1 {font_obj} 0 R /FSelect {selection_base} 0 R >> >> /Contents {} 0 R >>",
objects.contents
)
.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 objects.image.is_some() {
content.push_str(&format!("q {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n"));
}
if let Some(v) = vectors.get(i) {
content.push_str(v);
}
// 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 k in 0..page.plates.len() {
content.push_str(&format!("q /GS0 gs {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Sp{k} 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 };
@@ -189,41 +308,55 @@ fn print_pdf_pages(
body.extend_from_slice(&c);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
let img = &page.image;
let device = match img.channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let cs = match icc_obj {
Some(obj) => format!("[/ICCBased {obj} 0 R]"),
None => 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);
if let Some(img) = &page.image {
let device = match img.channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let cs = match icc_obj {
Some(o) if img.icc.is_some() => format!("[/ICCBased {o} 0 R]"),
_ => device.to_string(),
};
obj(&mut out, &image_object(img.width, img.height, &cs, &img.data));
}
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));
// 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));
}
}
obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>");
if let Some(icc) = icc {
let device = match first.image.channels {
if let Some((icc, channels)) = icc {
let device = match channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let z = deflate(icc);
let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", first.image.channels, z.len()).into_bytes();
let mut body = format!("<< /N {channels} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", 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 >>");
}
if let Some(xmp) = 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);
}
for body in &selection_objects {
obj(&mut out, body);
}
@@ -251,6 +384,172 @@ fn print_pdf_pages(
Ok(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("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
c => o.push(c),
}
}
o
}
/// 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.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();
let text = body.get(range.clone())?;
if let Some(open) = text.strip_suffix("/>") {
// `<r:RDF …/>`: 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.get(..end)?)));
}
// The end tag is the last thing in the element's own range.
Some((bom + range.start + text.rfind("</")?, None))
}
/// 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 painting 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
/// <rdf:Description rdf:about="" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
/// xmlns:pcsp="http://ns.getartcraft.com/photocraft/spot-plates/1.0/">
/// <pcsp:plates>
/// <rdf:Seq>
/// <rdf:li rdf:parseType="Resource">
/// <pcsp:index>0</pcsp:index> <!-- 0-based, the order the plates are painted -->
/// <pcsp:name>Underbase White</pcsp:name> <!-- the Separation colorant name, as the channel is named -->
/// <pcsp:labL>100.00</pcsp:labL> <!-- ink colour, CIE L*a*b*, D50 -->
/// <pcsp:labA>0.00</pcsp:labA>
/// <pcsp:labB>0.00</pcsp:labB>
/// <pcsp:srgb>#FFFFFF</pcsp:srgb> <!-- the same colour as encoded sRGB, for convenience -->
/// <pcsp:solidity>100</pcsp:solidity> <!-- 0–100, Photoshop's Spot Channel Options › Solidity -->
/// </rdf:li>
/// </rdf:Seq>
/// </pcsp:plates>
/// </rdf:Description>
/// ```
///
/// An alpha-type channel of a Multichannel document lists as black with solidity 0. The plates
/// are the document's, the same on every page of an artboard export.
fn plates_xmp(doc_xmp: Option<&str>, plates: &[SpotPlate]) -> String {
// The description binds `rdf` itself: the packet it joins may bind another prefix to RDF.
let mut d = format!(" <rdf:Description rdf:about=\"\" xmlns:rdf=\"{RDF_NS}\" xmlns:pcsp=\"{SPOT_PLATES_NS}\">\n <pcsp:plates>\n <rdf:Seq>\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!(
" <rdf:li rdf:parseType=\"Resource\">\n <pcsp:index>{i}</pcsp:index>\n <pcsp:name>{}</pcsp:name>\n <pcsp:labL>{:.2}</pcsp:labL>\n <pcsp:labA>{:.2}</pcsp:labA>\n <pcsp:labB>{:.2}</pcsp:labB>\n <pcsp:srgb>#{hex}</pcsp:srgb>\n <pcsp:solidity>{}</pcsp:solidity>\n </rdf:li>\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(" </rdf:Seq>\n </pcsp:plates>\n </rdf:Description>\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; 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(head);
match self_closing {
// `<r:RDF …/>` becomes `<r:RDF …>` + the description + `</r:RDF>`.
Some(name) => {
out.push_str(">\n");
out.push_str(&d);
out.push_str(" </");
out.push_str(name);
out.push('>');
}
None => out.push_str(&d),
}
out.push_str(tail);
return out;
}
format!(
"<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"{RDF_NS}\">\n{d} </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>"
)
}
/// The channels of `doc` that leave as plates, in channel order (the first prints first,
/// underneath): every channel of a Multichannel document, the spot channels of any other.
fn plate_channels(doc: &Document) -> impl Iterator<Item = &photocraft_doc::AlphaChannel> {
let multichannel = doc.mode == ColorMode::Multichannel;
doc.channels.iter().filter(move |ch| multichannel || ch.spot.is_some())
}
/// The spot plates of `doc` over `rect` (the canvas, or one artboard's rect), in channel order.
///
/// 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: 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, rect: photocraft_geom::Rect) -> Vec<SpotPlate> {
let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
plate_channels(doc)
.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(rect);
let data: Vec<u8> = values.chunks(n).map(|px| px.first().copied().unwrap_or(0.0)).map(|v| to8(if alpha_type { 1.0 - v } else { v })).collect();
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: rect.width(),
height: rect.height(),
data,
}
})
.collect()
}
/// The vector operators for the contiguous visible top prefix of `doc`, top to bottom, with the
/// indices of the layers they replace, and the selection font covering their text (plus, when a
/// lower candidate is rejected during emission, that layer's unused characters).
@@ -332,17 +631,43 @@ fn rect_pixels(rect: photocraft_geom::Rect) -> u64 {
/// (pixels ÷ resolution × 72 pt). One page per artboard when the document has artboards, else one
/// page for the whole document. Layers and transparency are dropped — the warning says so — and
/// the embedded profile travels with the images.
pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result::Result<ExportResult, IoError> {
///
/// On a whole-document page the topmost simple shape and text layers stay vectors over the
/// flattened rest, with selectable text ([`collect_vectors`]); artboard pages are raster.
///
/// With `spot_plates`, the document's spot channels follow each page's image and vectors as
/// overprinting `/Separation` plates (FILE-215-17), an artboard page carrying its own region of
/// each, 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, ctl: &photocraft_raster::Interrupt) -> std::result::Result<ExportResult, IoError> {
export_with(doc, spot_plates, doc.metadata.xmp.as_deref(), ctl)
}
/// [`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>, ctl: &photocraft_raster::Interrupt) -> std::result::Result<ExportResult, IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
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()));
}
// The composite's channels per pixel; None for a Multichannel document, which has no composite.
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)"))),
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(),
));
}
m => {
return Err(IoError::Unsupported(format!(
"PDF saves RGB, Grayscale, CMYK and Multichannel documents; {m:?} needs converting to RGB first (Image > Mode)"
)));
}
};
let fmt = doc.pixel_format();
let n = fmt.channels().max(1);
@@ -350,12 +675,35 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result
let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 };
let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
let icc = doc.icc_profile.as_ref().map(|p| p.to_vec());
let plate_count = if spot_plates { plate_channels(doc).count() } else { 0 };
// Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink
// in CMYK (0 = paper).
let image_of = |values: &[f32], rect: photocraft_geom::Rect, device: usize| {
let mut data = Vec::with_capacity((rect.width() as usize * rect.height() as usize).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)));
}
}
PrintImage { width: rect.width(), height: rect.height(), channels: device, data, icc: icc.clone() }
};
let page_of = |image: Option<PrintImage>, rect: photocraft_geom::Rect, page_label: Option<String>| {
let (pw, ph) = (f64::from(rect.width()) * 72.0 / dpi, f64::from(rect.height()) * 72.0 / dpi);
let plates = if spot_plates { plates_of(doc, rect) } else { Vec::new() };
PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None, page_label, plates }
};
let mut warnings = Vec::new();
if device.is_some() {
warnings.push("PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into());
}
let artboards = doc.artboards();
if !artboards.is_empty() {
let (pages, vectors, selection_font) = if !artboards.is_empty() {
// Every page's encoded pixels are kept until the PDF is assembled; bound that peak.
const MAX_PDF_EXPORT_BYTES: u64 = 1 << 30;
let page_pixels: u64 = artboards.iter().fold(0u64, |bytes, (_, _, a)| bytes.saturating_add(rect_pixels(a.rect)));
let retained = page_pixels.saturating_mul(device as u64);
// A page keeps `device` bytes a pixel for its composite and one a pixel for each plate.
let retained = page_pixels.saturating_mul((device.unwrap_or(0) + plate_count) as u64);
// One page renders at a time: its f32 composite surface plus the region read back from
// it, both `n` channels at 4 bytes per pixel. The whole-document canvas is never held.
let largest = artboards.iter().map(|(_, _, a)| rect_pixels(a.rect)).max().unwrap_or(0);
@@ -378,86 +726,78 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result
for (id, name, artboard) in &artboards {
ctl.check().map_err(|_| IoError::Cancelled)?;
let rect = artboard.rect;
let (aw, ah) = (rect.width(), rect.height());
if aw == 0 || ah == 0 {
if rect.width() == 0 || rect.height() == 0 {
continue;
}
// A hidden artboard still gets its page, rendered from its own content rather than
// left blank by the group's visibility.
let Some(layer) = doc.layer(*id) else { continue };
let mut group = layer.clone();
group.visible = true;
one.layers.clear();
one.layers.push(group);
// Render only this artboard's rect; the surface never holds the whole document.
let surface = photocraft_compose::composite_to_surface(&one, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None);
let values = surface.read_region(rect);
let mut data = Vec::with_capacity((aw as usize * ah as usize).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)));
}
}
let image = PrintImage { width: aw, height: ah, channels: device, data, icc: icc.clone() };
let (pw, ph) = (f64::from(aw) * 72.0 / dpi, f64::from(ah) * 72.0 / dpi);
pages.push(PrintPage {
paper: (pw, ph),
image,
rect: (0.0, 0.0, pw, ph),
marks: Marks::default(),
description: None,
label: None,
page_label: Some((*name).to_string()),
let image = device.map(|device| {
let mut group = layer.clone();
group.visible = true;
one.layers.clear();
one.layers.push(group);
// Render only this artboard's rect; the surface never holds the whole document.
let surface = photocraft_compose::composite_to_surface(&one, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None);
image_of(&surface.read_region(rect), rect, device)
});
pages.push(page_of(image, rect, Some((*name).to_string())));
}
if pages.is_empty() {
return Err(IoError::Unsupported("PDF: the document's artboards have no area".into()));
}
let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()];
warnings.push(format!("PDF exported {} artboards as {} pages; vector/text layers on artboards are rasterised", artboards.len(), pages.len()));
if !doc.metadata.text.is_empty() {
warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into());
}
let vectors = vec![String::new(); pages.len()];
return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default(), ctl)?, warnings });
}
let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32);
// Simple topmost shapes and text layers can be drawn over the flattened backdrop without changing
// compositing. Stop at the first unsupported visible layer, since it may depend on the
// backdrop (adjustments, blend modes, masks, effects, or clipping).
let (vector_layers, selection_font) = collect_vectors(doc);
let mut backdrop = doc.clone();
for (index, _) in &vector_layers {
if let Some(layer) = backdrop.layers.get_mut(*index) {
layer.visible = false;
(pages, vectors, selection::SelectionFont::default())
} else {
let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32);
// Simple topmost shapes and text layers can be drawn over the flattened backdrop without
// changing compositing. Stop at the first unsupported visible layer, since it may depend
// on the backdrop (adjustments, blend modes, masks, effects, or clipping). A Multichannel
// document has no composite for them to sit on: it is its plates alone.
let (vector_layers, selection_font) = if device.is_some() { collect_vectors(doc) } else { (Vec::new(), selection::SelectionFont::default()) };
let image = device.map(|device| {
let mut backdrop = doc.clone();
for (index, _) in &vector_layers {
if let Some(layer) = backdrop.layers.get_mut(*index) {
layer.visible = false;
}
}
let surface = photocraft_compose::flatten_to_surface(&backdrop, PixelFormat::new(fmt.mode, fmt.sample, true), None);
image_of(&surface.read_region(canvas), canvas, device)
});
// The vector layers, bottom to top, in the document's pixel space (y down), over the
// image and under the plates.
let mut vectors = String::new();
if !vector_layers.is_empty() {
let scale = 72.0 / dpi;
let ph = f64::from(doc.size.height) * scale;
vectors.push_str(&format!("q {scale} 0 0 -{scale} 0 {ph} cm\n"));
for (_, ops) in vector_layers.iter().rev() {
vectors.push_str(ops);
}
vectors.push_str("Q\n");
}
(vec![page_of(image, canvas, None)], vec![vectors], selection_font)
};
// The plates are the document's: every page has the same ones, over its own region.
let plates = pages.first().map(|p| p.plates.as_slice()).unwrap_or_default();
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 surface = photocraft_compose::flatten_to_surface(&backdrop, PixelFormat::new(fmt.mode, fmt.sample, true), None);
let values = surface.read_region(canvas);
// Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink
// in CMYK (0 = paper).
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)));
}
}
let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: icc.clone() };
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, page_label: None };
let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()];
let xmp = if plates.is_empty() { doc_xmp.map(str::to_owned) } else { Some(plates_xmp(doc_xmp, plates)) };
if !doc.metadata.text.is_empty() {
warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into());
}
let scale = 72.0 / dpi;
let mut vectors = format!("q {scale} 0 0 -{scale} 0 {ph} cm\n");
for (_, ops) in vector_layers.iter().rev() {
vectors.push_str(ops);
}
vectors.push_str("Q\n");
Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font, ctl)?, warnings })
Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection_font, xmp.as_deref(), ctl)?, warnings })
}
#[cfg(test)]
+327 -27
View File
@@ -3,7 +3,7 @@
use super::*;
use lopdf::{Object, StringFormat};
use photocraft_color::{PixelFormat, SampleType};
use photocraft_doc::{Artboard, Group, Layer, LayerContent, Size};
use photocraft_doc::{AlphaChannel, Artboard, Group, Layer, LayerContent, Size};
use photocraft_geom::Rect;
use photocraft_raster::{Interrupt, Surface};
@@ -69,7 +69,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, &Interrupt::NONE).unwrap();
let out = export(&d, true, &Interrupt::NONE).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");
@@ -86,7 +86,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, &Interrupt::NONE).unwrap();
let out = export(&d, true, &Interrupt::NONE).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]);
@@ -103,7 +103,7 @@ fn topmost_solid_shape_is_exported_as_a_vector_path() {
..Default::default()
};
d.layers.push(Layer::new("Shape", LayerContent::Shape(shape)));
let out = export(&d, &Interrupt::NONE).unwrap();
let out = export(&d, true, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -129,7 +129,7 @@ fn topmost_text_layer_is_exported_with_selectable_text_and_vector_outlines() {
let baseline = layout.lines.get(cluster.line).expect("a line").baseline;
let origin = text.transform.apply(photocraft_geom::Point::new(f64::from(cluster.x), f64::from(baseline)));
d.layers.push(Layer::new("Text", LayerContent::Text(text)));
let out = export(&d, &Interrupt::NONE).unwrap();
let out = export(&d, true, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -160,7 +160,7 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() {
d.layers.push(Layer::new("Shape", LayerContent::Shape(shape)));
let text = TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() };
d.layers.push(Layer::new("Text", LayerContent::Text(text)));
let out = export(&d, &Interrupt::NONE).unwrap();
let out = export(&d, true, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -174,10 +174,10 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() {
#[test]
fn greyscale_and_cmyk_pages_keep_their_channels() {
let g = export(&doc(ColorMode::Grayscale), &Interrupt::NONE).unwrap();
let g = export(&doc(ColorMode::Grayscale), true, &Interrupt::NONE).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), &Interrupt::NONE).unwrap();
let c = export(&doc(ColorMode::Cmyk), true, &Interrupt::NONE).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");
}
@@ -189,7 +189,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, &Interrupt::NONE).unwrap();
let out = export(&d, true, &Interrupt::NONE).unwrap();
assert!(has(&out.bytes, "/MediaBox [0 0 72.00 36.00]"), "300 px at 300 dpi is one inch");
}
@@ -197,7 +197,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, &Interrupt::NONE).unwrap();
let out = export(&d, true, &Interrupt::NONE).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");
}
@@ -205,11 +205,281 @@ 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, &Interrupt::NONE).unwrap_err().to_string();
let e = export(&d, true, &Interrupt::NONE).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<f32> = vec![1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0];
let red: Vec<f32> = 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, &Interrupt::NONE).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; 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, "/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);
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, &Interrupt::NONE).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, &Interrupt::NONE).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, &Interrupt::NONE).unwrap_err().to_string();
assert!(e.contains("Multichannel") && e.contains("spot plates"), "{e}");
d.channels.clear();
assert!(export(&d, true, &Interrupt::NONE).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, &Interrupt::NONE).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"), "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, &Interrupt::NONE).unwrap();
assert!(!plain.warnings.iter().any(|w| w.contains("plate")), "{:?}", plain.warnings);
}
#[test]
fn vector_layers_sit_between_the_image_and_the_plates() {
use photocraft_doc::TextLayer;
let mut d = doc(ColorMode::Rgb);
d.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { text: "Hi".into(), size_pt: 12.0, ..Default::default() })));
d.channels.push(spot("Varnish", photocraft_color::Color::rgb(0.9, 0.9, 0.6), &[1.0; 8]));
let out = export(&d, true, &Interrupt::NONE).unwrap();
let pdf = &out.bytes;
check_structure(pdf);
let c = content(pdf);
let (im, tx, sp) = (c.find("/Im0 Do").unwrap(), c.find("/ActualText").unwrap(), c.find("/Sp0 Do").unwrap());
assert!(im < tx && tx < sp, "the image, the vector text over it, then the plate overprinting both:\n{c}");
assert!(has(pdf, "/FSelect") && has(pdf, "/Separation /Varnish"));
// The text left the raster backdrop for the vector plane.
assert_eq!(stream_after(pdf, "/Subtype /Image"), vec![255u8; 4 * 2 * 3]);
// A Multichannel document has no composite for vectors to sit on: plates alone, no vector block.
let mut m = Document::new("m.pdf", Size { width: 4, height: 2 }, ColorMode::Multichannel, SampleType::F32);
m.resolution_dpi = 72.0;
m.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { text: "Hi".into(), size_pt: 12.0, ..Default::default() })));
m.channels.push(spot("K", photocraft_color::Color::BLACK, &[1.0; 8]));
let c = content(&export(&m, true, &Interrupt::NONE).unwrap().bytes);
assert!(!c.contains("/ActualText") && c.contains("/Sp0 Do"), "{c}");
}
#[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, &Interrupt::NONE).unwrap();
assert!(has(&out.bytes, "/BitsPerComponent 8"));
assert_eq!(stream_after(&out.bytes, "/Separation /K"), vec![0, 64, 128, 255, 0, 0, 0, 0]);
}
// ---- Spot-plate XMP description ----
/// The XMP packet (the catalog's /Metadata stream), as text.
fn xmp_of(pdf: &[u8]) -> String {
let start = pdf.windows(9).position(|w| w == b"<?xpacket").expect("a packet");
let tail = b"<?xpacket end=\"w\"?>";
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/ü & <x>", channel(&[1.0; 8])) });
d.channels.push(spot("Underbase White", photocraft_color::Color::WHITE, &[0.0; 8]));
let out = export(&d, true, &Interrupt::NONE).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!(
"<rdf:li rdf:parseType=\"Resource\">\n <pcsp:index>0</pcsp:index>\n <pcsp:name>Black (Ink) #1/ü &amp; &lt;x&gt;</pcsp:name>\n <pcsp:labL>{:.2}</pcsp:labL>\n <pcsp:labA>{:.2}</pcsp:labA>\n <pcsp:labB>{:.2}</pcsp:labB>\n <pcsp:srgb>#334D66</pcsp:srgb>\n <pcsp:solidity>35</pcsp:solidity>\n </rdf:li>",
lab[0], lab[1], lab[2]
);
assert!(xmp.contains(&want), "first plate:\n{xmp}");
assert!(xmp.contains("<pcsp:index>1</pcsp:index>\n <pcsp:name>Underbase White</pcsp:name>\n <pcsp:labL>100.00</pcsp:labL>\n <pcsp:labA>0.00</pcsp:labA>\n <pcsp:labB>0.00</pcsp:labB>\n <pcsp:srgb>#FFFFFF</pcsp:srgb>\n <pcsp:solidity>0</pcsp:solidity>"), "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("<?xpacket begin").count(), 1);
assert!(crate::xml::parse(&xmp[xmp.find("<x:xmpmeta").unwrap()..xmp.rfind("</x:xmpmeta>").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(
"<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:title>Job 1</dc:title></rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>",
));
let out = crate::export(&d, "out.pdf", &crate::ExportOptions::default()).unwrap();
let xmp = xmp_of(&out.bytes);
assert_eq!(xmp.matches("<?xpacket begin").count(), 1, "one packet, not two");
assert!(xmp.contains("<dc:title>Job 1</dc:title>") && xmp.contains("<pcsp:name>Varnish</pcsp:name>"), "{xmp}");
assert!(xmp.find("<dc:title>").unwrap() < xmp.find("<pcsp:plates>").unwrap() && xmp.find("<pcsp:plates>").unwrap() < xmp.rfind("</rdf:RDF>").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("<pcsp:name>Varnish</pcsp:name>"), "{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, "<dc:title>Job 1</dc:title>") && !has(&plain.bytes, "pcsp:"), "the document packet alone");
d.metadata.xmp = None;
let bare = export(&d, true, &Interrupt::NONE).unwrap();
assert!(!has(&bare.bytes, "/Metadata") && !has(&bare.bytes, "<?xpacket"), "no metadata stream");
check_structure(&bare.bytes);
}
#[test]
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]));
// 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("<?xpacket begin").count(), 1, "one packet, not two: {xmp}");
};
let head = "<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n";
let tail = "\n</x:xmpmeta>\n<?xpacket end=\"w\"?>";
let title = "<r:Description r:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:title>Job 2</dc:title></r:Description>";
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} <r:RDF xmlns:r=\"{RDF}\">\n {title}\n </r:RDF >{tail}"), "prefix, whitespace and BOM"),
// An end tag spelled out inside a comment is not the element's end.
(format!("{head} <rdf:RDF xmlns:rdf=\"{RDF}\">\n <!-- </rdf:RDF> -->\n {}\n </rdf:RDF>{tail}", title.replace("r:", "rdf:")), "comment"),
// A self-closing RDF element is expanded around the description.
(format!("{head} <r:RDF xmlns:r=\"{RDF}\"/>{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("<dc:title>Job 2</dc:title>"), what != "self-closing", "{what}: {xmp}");
assert!(xmp.contains("<pcsp:name>Varnish</pcsp:name>"), "{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}<x:note>kept</x:note>{tail}"), format!("{head}<rdf:RDF xmlns:rdf=\"{RDF}\"><unclosed>{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);
}
}
#[test]
fn unicode_text_over_a_photo_extracts_through_a_pdf_reader() {
let mut d = doc(ColorMode::Rgb);
@@ -227,7 +497,7 @@ fn unicode_text_over_a_photo_extracts_through_a_pdf_reader() {
..Default::default()
}),
));
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), text);
assert!(has(&pdf, "/Subtype /Image"));
@@ -267,7 +537,7 @@ fn text_with_compositing_or_a_profile_stays_in_the_raster_backdrop() {
_ => d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4])),
}
d.layers.push(layer);
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(!content.contains("/ActualText"), "case {case} must retain the raster composite");
assert!(stream_after(&pdf, "/Subtype /Image").iter().any(|v| *v != 255), "case {case} must retain visible text");
@@ -305,7 +575,7 @@ fn text_outside_the_vector_prefix_does_not_consume_the_selection_font() {
"Top text",
LayerContent::Text(TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() }),
));
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), "Hi", "case {case}: only the top text is selectable");
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
@@ -356,7 +626,7 @@ fn a_text_layer_refused_at_emission_keeps_the_upper_vectors_and_stays_raster() {
..Default::default()
}),
));
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(content.contains("/ActualText <FEFF0048"), "the upper text stays vector:\n{content}");
@@ -378,7 +648,7 @@ fn multiline_text_keeps_its_paragraph_breaks_in_the_selection() {
use photocraft_doc::TextLayer;
let mut d = doc(ColorMode::Rgb);
d.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { text: "A\nB".into(), size_pt: 12.0, ..Default::default() })));
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), "A\nB", "the paragraph break survives selection");
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
@@ -390,7 +660,7 @@ fn leading_newline_stays_in_the_first_selection_span() {
use photocraft_doc::TextLayer;
let mut d = doc(ColorMode::Rgb);
d.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { text: "\nA".into(), size_pt: 12.0, ..Default::default() })));
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(content.contains("/ActualText <FEFF000A0041>"), "the first span retains the leading newline:\n{content}");
}
@@ -398,7 +668,6 @@ fn leading_newline_stays_in_the_first_selection_span() {
#[test]
/// Each artboard becomes one labelled page, in document order.
fn artboards_export_as_one_page_each() {
use photocraft_doc::{Artboard, Group};
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let mut d = Document::new("pages.pdf", Size { width: 40, height: 30 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
@@ -407,7 +676,7 @@ fn artboards_export_as_one_page_each() {
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new("Page", LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).unwrap();
let out = export(&d, true, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
let pages = parsed.get_pages();
@@ -438,21 +707,52 @@ fn artboard_doc(names: &[&str]) -> Document {
d
}
/// The decompressed samples of page `id`'s first image XObject (`/Im0`).
fn page_image(pdf: &lopdf::Document, id: lopdf::ObjectId) -> Vec<u8> {
/// The decompressed samples of page `id`'s image XObject `name` (`Im0` the composite, `Sp0`…
/// the plates).
fn page_xobject(pdf: &lopdf::Document, id: lopdf::ObjectId, name: &[u8]) -> Vec<u8> {
let page = pdf.get_dictionary(id).expect("page dictionary");
let resources = page.get(b"Resources").expect("page resources").as_dict().expect("resources dictionary");
let xobjects = resources.get(b"XObject").expect("xobjects").as_dict().expect("xobject dictionary");
let image = xobjects.get(b"Im0").expect("Im0").as_reference().expect("image reference");
let image = xobjects.get(name).expect("named XObject").as_reference().expect("image reference");
pdf.get_object(image).expect("image object").as_stream().expect("image stream").decompressed_content().expect("image samples")
}
/// The decompressed samples of page `id`'s first image XObject (`/Im0`).
fn page_image(pdf: &lopdf::Document, id: lopdf::ObjectId) -> Vec<u8> {
page_xobject(pdf, id, b"Im0")
}
/// An artboard page carries its own region of every spot plate, after its image and with
/// overprint on; the plates are the document's, described once in the catalog's XMP.
#[test]
fn artboard_pages_carry_their_region_of_each_plate() {
let mut d = artboard_doc(&["Front", "Back"]);
// The 4x2 canvas, row-major: ink on the second board (x 2..4) only.
d.channels.push(spot("PANTONE 185 C", photocraft_color::Color::rgb(0.89, 0.09, 0.22), &[0.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0, 0.5]));
let out = export(&d, true, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
let ids: Vec<_> = parsed.get_pages().values().copied().collect();
assert_eq!(ids.len(), 2);
assert_eq!(page_xobject(&parsed, ids[0], b"Sp0"), vec![0, 0, 0, 0], "the first board's region has no ink");
assert_eq!(page_xobject(&parsed, ids[1], b"Sp0"), vec![255, 128, 255, 128], "the second board's region of the plate");
assert_eq!(page_image(&parsed, ids[1]).len(), 2 * 2 * 3, "the board's composite stays");
let count = |needle: &str| out.bytes.windows(needle.len()).filter(|w| *w == needle.as_bytes()).count();
assert_eq!(count("/Separation /PANTONE#20185#20C"), 2, "one plate XObject per page");
assert_eq!(count("/Type /ExtGState /OP true"), 1, "one shared overprint state");
let c = content(&out.bytes);
assert!(c.find("/Im0 Do").unwrap() < c.find("/GS0 gs 2.000 0 0 2.000 0.000 0.000 cm /Sp0 Do").unwrap(), "image, then the plate: {c}");
assert!(has(&out.bytes, "/PageLabels"), "the boards still name their pages");
assert_eq!(xmp_of(&out.bytes).matches("<pcsp:name>PANTONE 185 C</pcsp:name>").count(), 1, "one description for the document");
assert!(out.warnings.iter().any(|w| w.contains("1 spot plate written")), "{:?}", out.warnings);
}
/// A named artboard gives every page a `/PageLabels` entry, and an empty name gets an empty
/// label dictionary rather than inheriting the previous name.
#[test]
fn page_labels_name_every_page_and_an_empty_name_does_not_inherit() {
let d = artboard_doc(&["A", "", "C"]);
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
let labels = parsed
@@ -478,7 +778,7 @@ fn page_labels_name_every_page_and_an_empty_name_does_not_inherit() {
#[test]
fn an_all_empty_artboard_names_document_has_no_page_labels_tree() {
let d = artboard_doc(&["", "", ""]);
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert!(parsed.catalog().unwrap().get(b"PageLabels").is_err(), "no names means no /PageLabels");
@@ -498,7 +798,7 @@ fn overlapping_artboards_export_only_their_own_pixels() {
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(Rect::new(0, 0, 2, 2))), frame_stroke: None };
d.layers.push(Layer::new(name, LayerContent::Group(group)));
}
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let pdf = export(&d, true, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
let pages = parsed.get_pages();
let images = pages.values().map(|id| page_image(&parsed, *id)).collect::<Vec<_>>();
@@ -520,7 +820,7 @@ fn sparse_canvas_artboards_export_without_a_false_memory_limit() {
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new("Page", LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).expect("two 2x2 boards on a 9000x9000 canvas must fit the export budget");
let out = export(&d, true, &Interrupt::NONE).expect("two 2x2 boards on a 9000x9000 canvas must fit the export budget");
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
assert_eq!(parsed.get_pages().len(), 2);
}
@@ -541,7 +841,7 @@ fn seven_us_letter_artboards_export_without_a_false_memory_limit() {
let group = Group { children: Vec::new(), expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new(format!("Letter {}", index + 1), LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).expect("seven US Letter pages at 300 dpi fit the export budget");
let out = export(&d, true, &Interrupt::NONE).expect("seven US Letter pages at 300 dpi fit the export budget");
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
assert_eq!(parsed.get_pages().len(), 7);
}
+1 -1
View File
@@ -501,7 +501,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?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). 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?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, 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; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). 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?}` |
+26 -3
View File
@@ -1,6 +1,6 @@
# File-format parity
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** minor (Fujifilm compressed RAF (lossless and lossy, X-Trans and Bayer) decodes instead of falling back to the embedded JPEG preview, #7377; Camera Raw: an `.xmp` sidecar's crop crops the opened raw, and `crs:RawFileName` is no longer named as unsupported, #9985; CLI `--metadata none|all` for `convert`, `run --out` and `batch`: `none` leaves the document XMP and free-form text out of flat exports, as Export As's Metadata: None, `all` the default, #9466; Hasselblad 3FR/FFF, the X2D II 100C, decodes; scripted PSD/PSB saves take `maximizeCompatibility`, and the CLI `--no-maximize-compatibility`, #8064; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; 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; Line truncated
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **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; Fujifilm compressed RAF (lossless and lossy, X-Trans and Bayer) decodes instead of falling back to the embedded JPEG preview, #7377; Camera Raw: an `.xmp` sidecar's crop crops the opened raw, and `crs:RawFileName` is no longer named as unsupported, #9985; CLI `--metadata none|all` for `convert`, `run --out` and `batch`: `none` leaves the document XMP and free-form text out of flat exports, as Export As's Metadata: None, `all` the default, #9466; Hasselblad 3FR/FFF, the X2D II 100C, decodes; scripted PSD/PSB saves take `maximizeCompatibility`, and the CLI `--no-maximize-compatibility`, #8064; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; 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 PhotosLine truncated
**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 | yes, raster pages (craft-pdf; up to 16 pages, 8192 px per side, 64M px per page) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF) | Read renders each page as a raster artboard: no editable text/vector layers yet (craft-pdf `interpret` is the follow-up), no PDF forms or annotations; write is still one flattened page, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10) |
| Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | |
| Photoshop PDF | R/W | yes, raster pages (craft-pdf; up to 16 pages, 8192 px per side, 64M px per page) | 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) | Read renders each page as a raster artboard: no editable text/vector layers yet (craft-pdf `interpret` is the follow-up), no PDF forms or annotations; write is still one flattened page, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10). Plates are 8-bit, named after the channel, 1 = solid ink, painted in channel order with `/OP true`; an artboard page carries its own region of each plate; 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 a 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 | |
@@ -141,6 +141,27 @@ 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 `<?xpacket begin`. Readers such as
pdf.js, pdf-lib, pikepdf and exiftool expose it as the document XMP. The plates themselves are
unchanged by the description; it is PDF 1.4 metadata that PDF/X-1a allows.
## Embedded vectors in PSD smart objects (2026-10-22)
Embedded SVG and PDF-compatible AI/PDF/EPS payloads can use an explicit VectorCraft editor choice, including nested PSB contents. AI/PDF/EPS working copies retain their format on save-back; a separate source-bound SVG display preview does not replace the native payload. Placement, shared instances, masks and Undo/Redo use existing smart-object transactions, with native bytes and previews persisted through .pcraft and PSD/PSB saves. Unsupported editor features may still change; standalone EPS/DCS import and lossless Adobe round-trip compatibility remain unverified. See [workflow, safety and validation limits](embedded-vector-editing.md). No corpus floor or parity percentage is changed.
@@ -162,6 +183,8 @@ The original reference entry retains its source date and historical totals; curr
| 2026-11-01 | minor | `.atn`: 23 newer measured forms mapped, including explicit Link/Unlink, Smart Object file operations, Make Type to Shape, radius-only Shape Blur, Artboard from Group and the Crop Photos parent; supported in batch 13; Link Layers keeps the measured toggle. Artboard forms with unmeasured settings and generated Crop helper steps remain kept. |
| 2026-11-01 | minor | Recorded direct Gradient Map and Lab-range Replace Color load, play and retain their measured settings on save; unsupported forms remain preserved (part of #10607). |
| 2026-11-02 | minor | TIFF Options on Save As and Save a Copy (#8827): Image Compression (None, LZW, ZIP), Save Image Pyramid (half-size levels marked reduced-resolution, down to 64 px, alpha-weighted; +45 ms on a 30 MP RGB/8 save), Save Transparency (on: transparency kept ahead of alpha and spot channels, `MTrn` in a layered file; off: matted on white) and Discard Layers and Save a Copy. Scripts, `doc.save`, MCP `save` and the CLI (`--tiff-transparency`, `--tiff-pyramid`) take the same answers. JPEG compression, Pixel Order and Byte Order not offered |
| 2026-10-30 | minor | PDF: the spot plates are described in the catalog's XMP packet (`pcsp` namespace: index, name, Lab D50, sRGB, solidity per plate), merged into the document's own packet, so a converter can rebuild the spot channels with their real ink colours; a document's XMP now travels into its PDF as into the other flat formats (`XmpEmbed`) |
| 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-11-01 | minor | `.atn`: event reference [atn.md](atn.md): the 117 supported events, and measured keys, defaults, ranges and enum values for 101 events not mapped yet |
| 2026-10-31 | minor | `.atn` Group B: four Render events load, play and save; 120 supported and 97 unmapped. Supported-table columns corrected against the event registry; the original 117/101 reference entry remains historical. |
| 2026-10-31 | minor | `.atn`: Pinch (`Pnch`), Polar Coordinates (`Plr `), Spherize (`Sphr`), Twirl (`Twrl`), Wave (`Wave`) and ZigZag (`ZgZg`) map to `filter.distort.*` with every key in recorded order; out-of-range values clamped and missing keys given Photoshop's defaults on import; a Wave scaled below 100 % stays a Photoshop step (the command has no scale); Shear still kept verbatim (#10605) |
+7 -2
View File
@@ -1,6 +1,6 @@
# Where PhotoCraft falls short of Photoshop
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (G9: Column Size preference and Image Size / Canvas Size Columns unit, #6214: 8 of 199 preferences do nothing; G14: Fujifilm compressed RAF decodes, #7377; G5: Warp mode edits Photoshop's Cylinder warp, #4112: the Warp menu lists it, five handles set its seven values as in the reference, and a smart object's stored cylinder opens in Warp mode as one; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; 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; 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 longeLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **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; G9: Column Size preference and Image Size / Canvas Size Columns unit, #6214: 8 of 199 preferences do nothing; G14: Fujifilm compressed RAF decodes, #7377; G5: Warp mode edits Photoshop's Cylinder warp, #4112: the Warp menu lists it, five handles set its seven values as in the reference, and a smart object's stored cylinder opens in Warp mode as one; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; 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; 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 swLine truncated
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
@@ -415,13 +415,18 @@ 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: PDF Separation (FILE-215-17); .atn,
Raw; spot plates beyond PSD, TIFF and PDF: the spot ink preview's ink order at overlaps and its
look at solidity 0.5 and 1 against reference files (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-30, #10249):** visible spot channels of RGB and CMYK documents print over
the canvas composite as inks (the Multichannel overprint formula, in Channels panel order), open
visible, and print in the PSD thumbnail; flatten, export and the merged image stay free of them.
Open: ink order at overlaps and the look at solidity 0.5 and 1 against reference files.
- **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.