Merge #16653 into the merge queue batch

Layers to Files: Include ICC Profile checkbox and iccProfile param
This commit is contained in:
David Mann committed 2026-11-27 12:08:37 +01:00
commit ca09020a6c
9 files changed
+254 -4

No files matched your search

+5 -1
View File
@@ -434,7 +434,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),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##,
r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"iccProfile":bool? (Include ICC Profile: false, no profile in any file; true, the document's profile, or its mode's working profile when it has none, PSD included, and none in a CMYK document's PNG; unset, as before),"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
),
@@ -576,3 +576,7 @@ mod aces_exr_tests {
}
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "file_cmds/layers_to_files_icc_tests.rs"]
mod layers_to_files_icc_tests;
+19 -1
View File
@@ -62,7 +62,10 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&
// Callers outside `Session::execute` (headless workspace exports) carry the session's gate
// into `encode`, so a PSD embeds no file a linked smart object names.
let _authorization = crate::jobs::render_authorization_scope(s.authorize);
let save = SaveOpts::from_params(s, p, cmd)?;
let mut save = SaveOpts::from_params(s, p, cmd)?;
// Include ICC Profile (#13973); unset, each file embeds what it did before.
let icc = super::save::tiff_bool_param(p, "iccProfile", cmd)?;
save.embed_icc = icc;
let d = s.active().ok_or(EngineError::NoDocument)?;
if layers_to_files_needs_more_layers(&d.doc) {
return Err(EngineError::Other("Layers to Files needs a document with multiple layers.".into()));
@@ -109,6 +112,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&
// The prefix is optional; only the layer name needs the empty-name fallback.
let prefix_part = if prefix.is_empty() { String::new() } else { part(&prefix) };
let name = format!("{prefix_part}_{:04}_{}.{format}", index, part(&l.name));
let save = include_icc(&mut one, &format, icc, save);
let (bytes, _warnings) = encode(&one, &name, save)?;
write(&name, &bytes)?;
report.files.push(name);
@@ -116,6 +120,20 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&
Ok(report)
}
/// Include ICC Profile for one layer file: off, no profile; on, the document's profile, or the one
/// its colours are taken to be in when it has none (PSD included), except that a CMYK document's
/// PNG (written as RGB) carries none, as measured. Unset changes nothing. Off only leaves the
/// profile out of the file (`save.embed_icc`): the document keeps it, since its colours (a CMYK
/// document's conversion to RGB) are read through it.
fn include_icc(one: &mut Document, format: &str, icc: Option<bool>, mut save: SaveOpts) -> SaveOpts {
match icc {
Some(true) if format == "png" && one.mode == ColorMode::Cmyk => save.embed_icc = Some(false),
Some(true) if one.icc_profile.is_none() => one.icc_profile = Some(crate::color_cmds::working_profile(one.mode).to_bytes()),
_ => {}
}
save
}
/// Adjustment layers that can be represented as an RGB-only LUT, in document stack order.
/// A LUT has no spatial coordinates, so masks and clipping geometry are deliberately stripped
/// at bake time. Group adjustments need their enclosing group's compositing semantics and are
@@ -0,0 +1,183 @@
//! Layers to Files: Include ICC Profile (#13973). `iccProfile: false` writes no profile in PNG,
//! JPEG, TIFF or PSD files; `true` embeds the document's profile (a CMYK document's JPEG its CMYK
//! profile, its PNG none); unset keeps what the export wrote before.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
fn session(mode: &str, depth: u32) -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 8, "height": 6, "mode": mode, "depth": depth, "background": "backgroundColor", "backgroundColor": [0.8, 0.1, 0.1]}))
.unwrap();
// One normal layer: Layers to Files refuses a Background-only document (#13968).
s.execute("layer.new.layerFromBackground", json!({})).unwrap();
s
}
/// The colour space of each written file's embedded profile (`None`: no profile), by extension.
fn profiles(s: &mut Session, format: &str, extra: Value) -> Vec<(String, Option<String>)> {
let dir = tempfile::tempdir().unwrap();
let mut p = json!({"dir": dir.path().to_string_lossy(), "prefix": "t", "format": format});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute("file.export.layersToFiles", p).unwrap();
r["files"]
.as_array()
.unwrap()
.iter()
.map(|f| {
let path = f.as_str().unwrap();
let bytes = std::fs::read(path).unwrap();
let doc = photocraft_io::import(path, &bytes).unwrap().document;
let space = doc.icc_profile.map(|icc| String::from_utf8_lossy(icc.get(16..20).unwrap()).trim().to_string());
(format!("{:?}", doc.mode), space)
})
.collect()
}
const FORMATS: [&str; 4] = ["png", "jpg", "tif", "psd"];
/// RGB and CMYK documents at 8 and 16 bits.
const DOCS: [(&str, u32); 4] = [("rgb", 8), ("rgb", 16), ("cmyk", 8), ("cmyk", 16)];
fn one(s: &mut Session, format: &str, extra: Value) -> (String, Option<String>) {
let files = profiles(s, format, extra);
assert_eq!(files.len(), 1, "{format}: one layer, one file");
files.into_iter().next().unwrap()
}
#[test]
fn off_writes_no_profile() {
for (mode, depth) in DOCS {
let mut s = session(mode, depth);
for format in FORMATS {
assert_eq!(one(&mut s, format, json!({"iccProfile": false})).1, None, "{mode}{depth} {format}");
}
}
}
#[test]
fn on_embeds_the_documents_profile() {
for depth in [8, 16] {
let mut s = session("rgb", depth);
for format in FORMATS {
assert_eq!(one(&mut s, format, json!({"iccProfile": true})), ("Rgb".into(), Some("RGB".into())), "rgb{depth} {format}");
}
}
// The document's own profile, not a stand-in, when it has one.
let mut s = session("rgb", 8);
let own = crate::color_cmds::working_profile(ColorMode::Rgb).to_bytes();
let dir = tempfile::tempdir().unwrap();
let r = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "jpg", "iccProfile": true})).unwrap();
let path = r["files"][0].as_str().unwrap();
let embedded = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document.icc_profile;
assert_eq!(embedded.as_deref(), Some(&*own));
}
#[test]
fn a_cmyk_documents_jpeg_keeps_its_cmyk_profile_and_its_png_has_none() {
for depth in [8, 16] {
let mut s = session("cmyk", depth);
let on = json!({"iccProfile": true});
assert_eq!(one(&mut s, "jpg", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} jpg");
assert_eq!(one(&mut s, "tif", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} tif");
assert_eq!(one(&mut s, "psd", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} psd");
assert_eq!(one(&mut s, "png", on), ("Rgb".into(), None), "cmyk{depth} png");
}
}
#[test]
fn unset_keeps_what_the_export_wrote_before() {
// As main wrote them before the param: flat RGB files and a CMYK document's PNG carry the
// RGB working profile; PSD files and CMYK JPEG and TIFF files carry none.
let rgb = Some("RGB".to_string());
for depth in [8, 16] {
let mut s = session("rgb", depth);
let got: Vec<_> = FORMATS.iter().map(|f| one(&mut s, f, json!({})).1).collect();
assert_eq!(got, vec![rgb.clone(), rgb.clone(), rgb.clone(), None], "rgb{depth}");
let mut s = session("cmyk", depth);
let got: Vec<_> = FORMATS.iter().map(|f| one(&mut s, f, json!({})).1).collect();
assert_eq!(got, vec![rgb.clone(), None, None, None], "cmyk{depth}");
// `null` is unset too.
assert_eq!(one(&mut s, "png", json!({"iccProfile": null})).1, rgb, "cmyk{depth} null");
}
}
#[test]
fn a_bad_value_is_an_error_and_writes_nothing() {
let mut s = session("rgb", 8);
for bad in [json!("no"), json!(0), json!([false]), json!({})] {
let dir = tempfile::tempdir().unwrap();
let r = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "png", "iccProfile": bad}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}");
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "{bad}: nothing written");
}
assert_eq!(s.active().unwrap().doc.icc_profile, None, "the document is untouched");
}
/// The pixels of each written file, decoded (RGBA, 0..1), and whether it carries a profile.
fn pixels(s: &mut Session, format: &str, extra: Value) -> Vec<(Vec<[f32; 4]>, bool)> {
let dir = tempfile::tempdir().unwrap();
let mut p = json!({"dir": dir.path().to_string_lossy(), "prefix": "t", "format": format});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute("file.export.layersToFiles", p).unwrap();
r["files"]
.as_array()
.unwrap()
.iter()
.map(|f| {
let path = f.as_str().unwrap();
let doc = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document;
let icc = doc.icc_profile.is_some();
(photocraft_compose::flatten(&doc).px.to_vec(), icc)
})
.collect()
}
#[test]
fn off_keeps_a_cmyk_documents_own_profile_for_its_colours() {
// A CMYK document tagged with a profile other than the built-in coated one, whose layer
// needs compositing (50 % opacity): its colours are converted through its own profile
// whether or not the file carries it (CodeRabbit on #16653).
for depth in [8, 16] {
let mut s = session("cmyk", depth);
s.execute("edit.assignProfile", json!({"profile": "coated-fogra39"})).unwrap();
s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap();
let on = pixels(&mut s, "png", json!({"iccProfile": true}));
let off = pixels(&mut s, "png", json!({"iccProfile": false}));
let unset = pixels(&mut s, "png", json!({}));
assert_eq!(off[0].0, on[0].0, "cmyk{depth}: the same pixels with iccProfile false and true");
assert_eq!(off[0].0, unset[0].0, "cmyk{depth}: the same pixels with iccProfile false and unset");
for format in FORMATS {
assert!(pixels(&mut s, format, json!({"iccProfile": false})).iter().all(|(_, icc)| !icc), "cmyk{depth} {format}: no profile");
}
let layered = pixels(&mut s, "tif", json!({"iccProfile": false, "tiffLayers": true}));
assert!(layered.iter().all(|(_, icc)| !icc), "cmyk{depth} layered tif: no profile");
assert!(s.active().unwrap().doc.icc_profile.is_some(), "the document keeps its profile");
}
}
/// An Indexed Color document with an RGB profile: `iccProfile: false` writes no profile in any file,
/// the PSD included, which is written over its colour table (CodeRabbit on #16653), and the
/// layered TIFF; `true` keeps it in the PSD.
#[test]
fn an_indexed_documents_files_follow_the_setting() {
let mut s = session("rgb", 8);
s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap();
// The conversion flattens: a normal layer again (#13968).
s.execute("layer.new.layerFromBackground", json!({})).unwrap();
let doc = &s.active().unwrap().doc;
assert_eq!(doc.mode, ColorMode::Indexed);
assert!(doc.icc_profile.is_some(), "the document keeps its profile");
assert!(doc.layers.iter().any(|l| !doc.is_background(l.id)), "a layer to export");
for format in ["png", "jpg", "tif", "psd", "bmp"] {
assert!(profiles(&mut s, format, json!({"iccProfile": false})).iter().all(|(_, icc)| icc.is_none()), "indexed {format}: no profile");
}
let layered = profiles(&mut s, "tif", json!({"iccProfile": false, "tiffLayers": true}));
assert!(layered.iter().all(|(_, icc)| icc.is_none()), "indexed layered tif: no profile");
assert_eq!(one(&mut s, "psd", json!({"iccProfile": true})).1, Some("RGB".into()), "indexed psd: the profile");
}
+1
View File
@@ -1276,6 +1276,7 @@ fn export_stages_with_renderer(
document_path: opts.document_path.clone(),
read_linked_files: opts.read_linked_files,
stage_on_scratch_from: Some(psd_export::STAGE_DOCUMENTS_FROM),
embed_icc: opts.encode.embed_icc,
..Default::default()
};
// The preview is rendered first, while only the document is in memory: its full-size
+4
View File
@@ -80,6 +80,9 @@ pub struct PsdExportOptions {
/// pixel bytes (layers and composite) reach this and spilling is on (`None`: never). The
/// save then holds the file model's structure, not a second copy of its pixels (#5333).
pub stage_on_scratch_from: Option<u64>,
/// Write the document's ICC profile (resource 1039). Off leaves it out of the file only: the
/// document's colours are still read through it (a CMYK document's layers and merged image).
pub embed_icc: bool,
}
impl Default for PsdExportOptions {
@@ -93,6 +96,7 @@ impl Default for PsdExportOptions {
document_path: None,
read_linked_files: true,
stage_on_scratch_from: None,
embed_icc: true,
}
}
}
+6 -2
View File
@@ -66,7 +66,11 @@ fn document_to_psd_sized_with_patterns(
if doc.mode == ColorMode::Multichannel {
return crate::multichannel_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns);
}
if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? {
if let Some(mut file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? {
// An Indexed document's RGB profile is written there too; Include ICC Profile off leaves it out.
if !opts.embed_icc {
file.0.resources.retain(|r| r.id != ids::ICC_PROFILE);
}
return Ok(file);
}
let fmt = doc.pixel_format();
@@ -149,7 +153,7 @@ fn export_supported_document(
ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()),
ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()),
];
if let Some(icc) = &doc.icc_profile {
if let Some(icc) = doc.icc_profile.as_ref().filter(|_| opts.embed_icc) {
resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec()));
}
if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() {
+33
View File
@@ -862,3 +862,36 @@ fn a_type_layer_without_a_writable_tysh_drops_its_imported_block() {
assert!(!written.blocks.iter().any(|b| b.key == *b"TySh"), "the stale imported TySh is dropped");
assert!(warnings.iter().any(|w| w.contains("no TySh data")), "{warnings:?}");
}
/// `embed_icc: false` leaves the ICC profile resource out of the file (the document keeps it);
/// on (the default), the file carries it.
#[test]
fn embed_icc_off_writes_no_profile_resource() {
let mut doc = Document::new("icc", photocraft_geom::Size::new(4, 4), ColorMode::Rgb, SampleType::U8);
doc.layers.push(Layer::raster("Layer 1", doc.pixel_format()));
doc.icc_profile = Some(std::sync::Arc::new(craft_cms::Builtin::Srgb.profile().to_bytes().to_vec()));
let has = |opts: &PsdExportOptions| document_to_psd_with(&doc, opts).unwrap().0.resources.iter().any(|r| r.id == ids::ICC_PROFILE);
assert!(has(&PsdExportOptions::default()));
assert!(!has(&PsdExportOptions { embed_icc: false, ..Default::default() }));
assert!(doc.icc_profile.is_some());
}
/// An Indexed Color document is written over its colour table (`palette_map`): `embed_icc: false`
/// leaves its RGB profile out there too, as PSD and as PSB (CodeRabbit on #16653).
#[test]
fn embed_icc_off_writes_no_profile_resource_for_an_indexed_document() {
let white = photocraft_color::Color::rgba(1.0, 1.0, 1.0, 1.0);
let mut doc = Document::with_background("indexed", photocraft_geom::Size::new(4, 4), ColorMode::Rgb, SampleType::U8, white);
doc.mode = ColorMode::Indexed;
doc.color_table = Some(photocraft_doc::ColorTable { colors: vec![[255, 255, 255], [0, 0, 0]], transparent: None });
doc.icc_profile = Some(std::sync::Arc::new(craft_cms::Builtin::Srgb.profile().to_bytes().to_vec()));
for force_psb in [false, true] {
let written = |embed_icc| document_to_psd_with(&doc, &PsdExportOptions { embed_icc, force_psb, ..Default::default() }).unwrap().0;
let on = written(true);
assert_eq!(on.header.color_mode, PsdMode::Indexed, "psb {force_psb}");
assert!(on.resources.iter().any(|r| r.id == ids::ICC_PROFILE), "psb {force_psb}: on");
let off = written(false);
assert_eq!((off.header.color_mode, off.header.version == Version::Psb), (PsdMode::Indexed, force_psb));
assert!(!off.resources.iter().any(|r| r.id == ids::ICC_PROFILE), "psb {force_psb}: off");
}
}
+1
View File
@@ -368,6 +368,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
read_linked_files: opts.read_linked_files,
// The layered TIFF reads the merged image's bytes directly: they stay in memory.
stage_on_scratch_from: None,
embed_icc: opts.encode.embed_icc,
};
// TIFF has no palette, bitmap or duotone layout: the PSD model of an Indexed Color, Bitmap
// or Duotone document is made in its pixel format (RGB or Grayscale), which the PSD exporter
@@ -305,6 +305,8 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec<Param
Param::new("visibleOnly", tl!("Visible Layers Only"), ParamKind::bool(true)),
choice("format", tl!("File Type"), export_formats(), "png"),
export_quality(),
// Shown for every file type (#13973).
Param::new("iccProfile", tl!("Include ICC Profile"), ParamKind::bool(true)),
Param::new("trim", tl!("Trim Layers"), ParamKind::bool(false)),
])
}