mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge PR #8367: Layers: per-layer XMP metadata (layer.xmpMetadata), stored as the reference app stores it
docs/file-format-parity.md: kept main's PSD row (45 smart filters) and added the PR's layer XMP packet phrase.
This commit is contained in:
commit
bf1000302d
15 files changed
+507
-3
No files matched your search
@@ -659,6 +659,10 @@ pub struct Layer {
|
||||
pub advanced: AdvancedBlending,
|
||||
/// Layer › Video Layers frame stack (None for a normal layer).
|
||||
pub video: Option<VideoData>,
|
||||
/// The layer's own XMP packet (Photoshop's `layer.xmpMetadata.rawData`), where scripts and
|
||||
/// embedding apps keep data about the layer under their own namespaces. Copied by
|
||||
/// [`Layer::duplicate`], as in Photoshop. PSD `shmd` › `cust` › `layerXMP`.
|
||||
pub xmp: Option<Arc<str>>,
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
@@ -692,6 +696,7 @@ impl Layer {
|
||||
blend_if: BlendIf::default(),
|
||||
advanced: AdvancedBlending::default(),
|
||||
video: None,
|
||||
xmp: None,
|
||||
}
|
||||
}
|
||||
pub fn raster(name: impl Into<String>, format: PixelFormat) -> Self {
|
||||
|
||||
@@ -1524,6 +1524,7 @@ fn build() -> Vec<CommandSpec> {
|
||||
v.extend(crate::adjust_cmds::specs());
|
||||
v.extend(crate::layer_menu_cmds::specs());
|
||||
v.extend(crate::layer_label_cmds::specs());
|
||||
v.extend(crate::layer_xmp_cmds::specs());
|
||||
v.extend(crate::mode_cmds::specs());
|
||||
v.extend(crate::multichannel_cmds::specs());
|
||||
v.extend(crate::pattern_cmds::specs());
|
||||
|
||||
@@ -106,6 +106,7 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], instances: &HashMa
|
||||
"bounds": bounds,
|
||||
"selected": selected.contains(&l.id),
|
||||
"linkGroup": l.link_group,
|
||||
"hasXmp": l.xmp.is_some(),
|
||||
});
|
||||
match &l.content {
|
||||
LayerContent::Group(g) => {
|
||||
|
||||
@@ -622,7 +622,7 @@ fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::Al
|
||||
/// compared here: the caller walks into them, so an edit inside a group damages only the
|
||||
/// edited child's extent, not the whole group's. The destructure is exhaustive, so a new
|
||||
/// `Layer` field fails to compile until it is classified: compared, or explicitly ignored
|
||||
/// (name, locks, label, `psd_blocks`, `psd_id`, link group — none of them composite; video
|
||||
/// (name, locks, label, `psd_blocks`, `psd_id`, link group, XMP — none of them composite; video
|
||||
/// bails out earlier in the walk).
|
||||
fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool {
|
||||
let Layer {
|
||||
@@ -647,6 +647,7 @@ fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool {
|
||||
blend_if,
|
||||
advanced,
|
||||
video: _,
|
||||
xmp: _,
|
||||
} = a;
|
||||
*id == b.id
|
||||
&& *visible == b.visible
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! A layer's own XMP packet, as Photoshop scripts reach it through `layer.xmpMetadata.rawData`:
|
||||
//! scripts and embedding apps keep data about a layer there under their own namespaces. It is
|
||||
//! saved in PSD, PSB, layered TIFF and `.pcraft`, and copied when the layer is duplicated.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_doc::LayerId;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::commands::CommandSpec;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const ID: &str = "layer.xmpMetadata";
|
||||
|
||||
/// Largest packet accepted, in UTF-8 bytes. Every history state shares the packet, but a PSD
|
||||
/// stores it as UTF-16 in each layer's record.
|
||||
pub const MAX_LAYER_XMP: usize = 4 << 20;
|
||||
|
||||
fn bad(message: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: ID.into(), msg: message.into() }
|
||||
}
|
||||
|
||||
fn enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
crate::active_layer_of(s).map(|_| ())
|
||||
}
|
||||
|
||||
/// `raw` if it is an XMP packet: well-formed XML (no DTD) whose root is `x:xmpmeta` or
|
||||
/// `rdf:RDF`, without NUL characters (Photoshop stores the packet NUL-terminated).
|
||||
fn check_packet(raw: &str) -> Result<()> {
|
||||
if raw.len() > MAX_LAYER_XMP {
|
||||
return Err(bad(format!("`rawData` is {} bytes; the most a layer holds is {MAX_LAYER_XMP}", raw.len())));
|
||||
}
|
||||
if raw.contains('\0') {
|
||||
return Err(bad("`rawData` can't contain NUL characters"));
|
||||
}
|
||||
let xml = roxmltree::Document::parse(raw).map_err(|e| bad(format!("`rawData` isn't well-formed XML: {e}")))?;
|
||||
let root = xml.root_element().tag_name();
|
||||
let xmp = matches!((root.namespace(), root.name()), (Some("adobe:ns:meta/"), "xmpmeta") | (Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "RDF"));
|
||||
if !xmp {
|
||||
return Err(bad("`rawData` must be an XMP packet: its root element is x:xmpmeta or rdf:RDF"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn xmp_metadata(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let empty = Map::new();
|
||||
let p = match p {
|
||||
Value::Null => &empty,
|
||||
Value::Object(m) => m,
|
||||
_ => return Err(bad("expected an object")),
|
||||
};
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let id = match p.get("layer") {
|
||||
Some(v) => LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?),
|
||||
None => st.active_layer.ok_or_else(|| bad("no active layer"))?,
|
||||
};
|
||||
let current = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?.xmp.clone();
|
||||
let new = match p.get("rawData") {
|
||||
None => return Ok(json!({"layer": id.0, "rawData": current.as_deref(), "changed": false})),
|
||||
Some(Value::Null) => None,
|
||||
Some(Value::String(raw)) => {
|
||||
check_packet(raw)?;
|
||||
Some(raw.as_str())
|
||||
}
|
||||
Some(_) => return Err(bad("`rawData` must be a string (an XMP packet) or null (remove it)")),
|
||||
};
|
||||
let changed = current.as_deref() != new;
|
||||
if changed {
|
||||
let stored: Option<Arc<str>> = new.map(Into::into);
|
||||
s.edit("Layer Metadata", move |doc, _| {
|
||||
doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.xmp = stored;
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(st) = s.active_mut() {
|
||||
// Saved metadata only; no canvas pixels need recompositing.
|
||||
st.last_damage = Some(photocraft_geom::Rect::EMPTY);
|
||||
}
|
||||
}
|
||||
Ok(json!({"layer": id.0, "rawData": new, "changed": changed}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![CommandSpec {
|
||||
id: ID,
|
||||
label: "Layer XMP Metadata",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r#"{"layer":id?,"rawData":string|null?} → {"layer","rawData","changed"} (no layer: the active layer; no rawData: read it; a string sets the layer's XMP packet, null removes it; as Photoshop's layer.xmpMetadata.rawData)"#,
|
||||
enabled,
|
||||
run: xmp_metadata,
|
||||
journal: true,
|
||||
}]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,106 @@
|
||||
use super::*;
|
||||
use photocraft_doc::Layer;
|
||||
|
||||
const PACKET: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:app="http://example.com/app/1.0/"><app:arc>120</app:arc></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
fn fixture(depth: u8) -> (Session, LayerId, LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 4, "height": 4, "depth": depth})).unwrap();
|
||||
let (a, b) = s
|
||||
.edit("Fixture", |doc, _| {
|
||||
let a = Layer::raster("A", doc.pixel_format());
|
||||
let b = Layer::group("B", vec![Layer::raster("Child", doc.pixel_format())]);
|
||||
let ids = (a.id, b.id);
|
||||
doc.layers = vec![a, b];
|
||||
Ok(ids)
|
||||
})
|
||||
.unwrap();
|
||||
s.select_layer(a).unwrap();
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
fn xmp(s: &Session, id: LayerId) -> Option<String> {
|
||||
s.active().unwrap().doc.layer(id).unwrap().xmp.as_deref().map(str::to_string)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_reads_and_removes_as_one_undo_step_each() {
|
||||
for depth in [8, 16, 32] {
|
||||
let (mut s, a, b) = fixture(depth);
|
||||
assert_eq!(s.execute(ID, json!({})).unwrap(), json!({"layer": a.0, "rawData": null, "changed": false}));
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
|
||||
// The active layer by default; a group by id.
|
||||
assert_eq!(s.execute(ID, json!({"rawData": PACKET})).unwrap(), json!({"layer": a.0, "rawData": PACKET, "changed": true}));
|
||||
assert_eq!(s.execute(ID, json!({"layer": b.0, "rawData": PACKET})).unwrap()["changed"], true);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 2);
|
||||
assert_eq!(s.active().unwrap().last_damage, Some(photocraft_geom::Rect::EMPTY));
|
||||
assert_eq!(s.execute(ID, Value::Null).unwrap()["rawData"], PACKET);
|
||||
assert_eq!(crate::inspect::layer(s.active().unwrap().doc.layer(b).unwrap())["hasXmp"], true);
|
||||
|
||||
// Only the packets changed.
|
||||
let mut expected = (*before).clone();
|
||||
for id in [a, b] {
|
||||
expected.layer_mut(id).unwrap().xmp = Some(PACKET.into());
|
||||
}
|
||||
assert_eq!(*s.active().unwrap().doc, expected, "depth {depth}");
|
||||
|
||||
// The same packet again is not an edit.
|
||||
assert_eq!(s.execute(ID, json!({"rawData": PACKET})).unwrap()["changed"], false);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 2);
|
||||
|
||||
assert_eq!(s.execute(ID, json!({"rawData": null})).unwrap(), json!({"layer": a.0, "rawData": null, "changed": true}));
|
||||
assert_eq!(xmp(&s, a), None);
|
||||
assert!(s.undo());
|
||||
assert_eq!(xmp(&s, a).as_deref(), Some(PACKET));
|
||||
assert!(s.undo() && s.undo());
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert!(s.redo());
|
||||
assert_eq!(xmp(&s, a).as_deref(), Some(PACKET));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_a_layer_copies_its_packet() {
|
||||
let (mut s, a, _) = fixture(8);
|
||||
s.execute(ID, json!({"rawData": PACKET})).unwrap();
|
||||
s.execute("layer.duplicate", json!({})).unwrap();
|
||||
let copy = s.active().unwrap().active_layer.unwrap();
|
||||
assert_ne!(copy, a);
|
||||
assert_eq!(xmp(&s, copy).as_deref(), Some(PACKET));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_what_is_not_an_xmp_packet() {
|
||||
let (mut s, a, _) = fixture(8);
|
||||
let refused = |s: &mut Session, p: Value| matches!(s.execute(ID, p), Err(EngineError::BadParams { .. }));
|
||||
for p in [
|
||||
json!([]),
|
||||
json!({"layer": "A"}),
|
||||
json!({"rawData": 7}),
|
||||
json!({"rawData": ""}),
|
||||
json!({"rawData": "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">"}),
|
||||
json!({"rawData": "<html/>"}),
|
||||
json!({"rawData": "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\u{0}</x:xmpmeta>"}),
|
||||
json!({"rawData": "<!DOCTYPE x [<!ENTITY a \"aaaa\">]><x:xmpmeta xmlns:x=\"adobe:ns:meta/\">&a;</x:xmpmeta>"}),
|
||||
json!({"rawData": format!("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">{}</x:xmpmeta>", "a".repeat(MAX_LAYER_XMP))}),
|
||||
] {
|
||||
assert!(refused(&mut s, p.clone()), "{p:.80}");
|
||||
}
|
||||
let r = s.execute(ID, json!({"layer": 999_999_999}));
|
||||
assert!(matches!(r, Err(EngineError::UnknownLayer { .. })), "{r:?}");
|
||||
assert_eq!(xmp(&s, a), None);
|
||||
// A bare RDF root and a packet wrapper are packets.
|
||||
let rdf = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"/>"#;
|
||||
assert_eq!(s.execute(ID, json!({"rawData": rdf})).unwrap()["changed"], true);
|
||||
let wrapped = format!("<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>{PACKET}<?xpacket end=\"w\"?>");
|
||||
assert_eq!(s.execute(ID, json!({"rawData": wrapped})).unwrap()["changed"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_a_document_and_a_layer() {
|
||||
let mut s = Session::new();
|
||||
assert!(matches!(s.execute(ID, json!({})), Err(EngineError::Disabled(..))));
|
||||
assert!(enabled(&s).is_err());
|
||||
}
|
||||
@@ -74,6 +74,7 @@ pub mod layer_menu_cmds;
|
||||
pub mod layer_multi_cmds;
|
||||
pub mod layer_nav_cmds;
|
||||
pub mod layer_style;
|
||||
pub mod layer_xmp_cmds;
|
||||
pub mod lens_cmds;
|
||||
pub mod link_watch;
|
||||
pub mod magnetic_cmds;
|
||||
|
||||
@@ -211,6 +211,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
|
||||
blend_if: l.blend_if.clone(),
|
||||
advanced: l.advanced,
|
||||
video: l.video.as_ref().map(|v| video_m(v, sink)),
|
||||
xmp: l.xmp.as_deref().map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,6 +548,7 @@ impl Loader<'_> {
|
||||
blend_if: m.blend_if.clone(),
|
||||
advanced: m.advanced,
|
||||
video: m.video.as_ref().map(|v| self.video(v)).transpose()?,
|
||||
xmp: m.xmp.as_deref().map(Arc::from),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -242,6 +242,9 @@ pub struct LayerM {
|
||||
pub advanced: photocraft_doc::AdvancedBlending,
|
||||
#[serde(default)]
|
||||
pub video: Option<VideoDataM>,
|
||||
/// The layer's own XMP packet (missing in older files = none).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub xmp: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -731,9 +731,24 @@ impl Ex {
|
||||
let id = self.layer_ids.get(&l.id).copied().unwrap_or(0);
|
||||
crate::comps_map::set_cmls(&mut raw, crate::comps_map::write_cmls(comps, last.as_ref(), l, id));
|
||||
}
|
||||
self.layer_xmp_block(l, &mut raw);
|
||||
regenerated.into_iter().chain(raw).map(|(k, d)| TaggedBlock::new(k, d)).collect()
|
||||
}
|
||||
|
||||
/// Writes the layer's XMP packet into its `shmd` block (created when it has none). Import
|
||||
/// takes the packet out of `shmd`, so a layer without one keeps the block as it was.
|
||||
fn layer_xmp_block(&mut self, l: &Layer, raw: &mut Vec<([u8; 4], Vec<u8>)>) {
|
||||
let Some(xmp) = l.xmp.as_deref() else { return };
|
||||
let pos = raw.iter().position(|(k, _)| k == b"shmd");
|
||||
match photocraft_psd::metadata::put_layer_xmp(pos.map(|i| raw[i].1.as_slice()), xmp) {
|
||||
Ok(data) => match pos {
|
||||
Some(i) => raw[i].1 = data,
|
||||
None => raw.push((*b"shmd", data)),
|
||||
},
|
||||
Err(e) => self.warnings.push(format!("layer \"{}\": its XMP metadata was not saved (its metadata block can't be read: {e})", l.name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps, regenerates or removes the `vmsk`/`vsms` block of a non-shape layer.
|
||||
fn vector_mask_block(&mut self, l: &Layer, raw: &mut Vec<([u8; 4], Vec<u8>)>) {
|
||||
let (w, h) = (self.canvas.width(), self.canvas.height());
|
||||
|
||||
@@ -330,6 +330,19 @@ impl Ctx<'_> {
|
||||
// Blend If lives in the layer record's blending ranges.
|
||||
l.blend_if = crate::blocks::blend_if_from_ranges(&rec.blending_ranges);
|
||||
l.psd_id = rec.layer_id();
|
||||
// The layer's XMP packet (`shmd` › `cust` › `layerXMP`) becomes the field; the rest of
|
||||
// `shmd` stays in `psd_blocks`, where export puts the packet back.
|
||||
if let Some(i) = l.psd_blocks.iter().position(|(k, _)| k == b"shmd")
|
||||
&& let Some((xmp, rest)) = photocraft_psd::metadata::take_layer_xmp(&l.psd_blocks[i].1)
|
||||
{
|
||||
l.xmp = Some(Arc::from(xmp));
|
||||
match rest {
|
||||
Some(data) => l.psd_blocks[i].1 = Arc::new(data),
|
||||
None => {
|
||||
l.psd_blocks.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
let name = l.name.clone();
|
||||
l.mask = self.record_mask(rec, &name);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! A layer's own XMP packet (`Layer::xmp`, PSD `shmd` › `cust` › `layerXMP`) survives every
|
||||
//! layered format and keeps the rest of a Photoshop `shmd` block as it was.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Layer, Size};
|
||||
use photocraft_io::{ExportOptions, export, import};
|
||||
use photocraft_psd::PsdFile;
|
||||
use photocraft_psd::metadata::{layer_xmp, put_layer_xmp};
|
||||
|
||||
const A: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:app="http://example.com/app/1.0/"><app:arc>120</app:arc></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
const G: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:app="http://example.com/app/1.0/"><app:name>Café 🎨</app:name></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
/// `shmd` of a Photoshop 2026 layer without XMP: a `cust` item holding only `layerTime`.
|
||||
const PS_WITHOUT_XMP: &str =
|
||||
"000000013842494d63757374000000000000003400000010000000010000000000086d6574616461746100000001000000096c6179657254696d65646f756241dab643ffd86bec00";
|
||||
|
||||
fn unhex(h: &str) -> Vec<u8> {
|
||||
(0..h.len()).step_by(2).map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap()).collect()
|
||||
}
|
||||
|
||||
fn xmps(d: &Document) -> Vec<(String, Option<String>)> {
|
||||
d.walk().into_iter().map(|(_, _, l)| (l.name.clone(), l.xmp.as_deref().map(str::to_string))).collect()
|
||||
}
|
||||
|
||||
fn layer_shmd<'a>(f: &'a PsdFile, name: &str) -> Option<&'a [u8]> {
|
||||
f.layers().iter().find(|r| r.name() == name).and_then(|r| r.block(b"shmd")).map(|b| b.data.as_slice())
|
||||
}
|
||||
|
||||
fn sample(depth: SampleType) -> Document {
|
||||
let mut doc = Document::new("Layer XMP", Size::new(4, 4), ColorMode::Rgb, depth);
|
||||
let mut a = Layer::raster("A", doc.pixel_format());
|
||||
a.xmp = Some(Arc::from(A));
|
||||
let plain = Layer::raster("Plain", doc.pixel_format());
|
||||
let mut g = Layer::group("G", vec![plain]);
|
||||
g.xmp = Some(Arc::from(G));
|
||||
doc.layers.extend([a, g]);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_xmp_round_trips_through_every_layered_format_and_depth() {
|
||||
let psb = ExportOptions { force_psb: true, ..Default::default() };
|
||||
let tiff = ExportOptions { tiff_layers: true, ..Default::default() };
|
||||
for depth in SampleType::ALL {
|
||||
let doc = sample(depth);
|
||||
for (path, opts) in [("x.psd", &ExportOptions::default()), ("x.psb", &psb), ("x.tif", &tiff), ("x.pcraft", &ExportOptions::default())] {
|
||||
let bytes = export(&doc, path, opts).unwrap().bytes;
|
||||
let back = import(path, &bytes).unwrap().document;
|
||||
assert_eq!(xmps(&back), xmps(&doc), "{path} {depth:?}");
|
||||
}
|
||||
// Stored as Photoshop stores it; a layer without XMP gets no block.
|
||||
let bytes = export(&doc, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
let f = PsdFile::from_bytes(&bytes).unwrap();
|
||||
assert_eq!(layer_shmd(&f, "A").and_then(layer_xmp).as_deref(), Some(A));
|
||||
assert_eq!(layer_shmd(&f, "G").and_then(layer_xmp).as_deref(), Some(G));
|
||||
assert!(layer_shmd(&f, "Plain").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn photoshop_shmd_keeps_its_other_data() {
|
||||
let without = unhex(PS_WITHOUT_XMP);
|
||||
let with = put_layer_xmp(Some(&without), A).unwrap();
|
||||
// A layer as an older PhotoCraft kept it: Photoshop's block verbatim, no field.
|
||||
let mut doc = Document::new("PS", Size::new(2, 2), ColorMode::Rgb, SampleType::U8);
|
||||
let mut l = Layer::raster("L", doc.pixel_format());
|
||||
l.psd_blocks.push((*b"shmd", Arc::new(with.clone())));
|
||||
doc.layers.push(l);
|
||||
let bytes = export(&doc, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
|
||||
// Opening it gives the packet to the field and keeps the rest of the block.
|
||||
let mut back = import("x.psd", &bytes).unwrap().document;
|
||||
let l = &back.layers[0];
|
||||
assert_eq!(l.xmp.as_deref(), Some(A));
|
||||
assert_eq!(l.psd_blocks.iter().find(|(k, _)| k == b"shmd").map(|(_, d)| d.as_slice()), Some(without.as_slice()));
|
||||
|
||||
// Unchanged, the block is written back byte for byte.
|
||||
let again = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
assert_eq!(layer_shmd(&PsdFile::from_bytes(&again).unwrap(), "L"), Some(with.as_slice()));
|
||||
|
||||
// Edited, `layerTime` stays; removed, the block is Photoshop's block without XMP.
|
||||
back.layers[0].xmp = Some(Arc::from(G));
|
||||
let edited = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
assert_eq!(layer_shmd(&PsdFile::from_bytes(&edited).unwrap(), "L"), Some(put_layer_xmp(Some(&without), G).unwrap().as_slice()));
|
||||
back.layers[0].xmp = None;
|
||||
let removed = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
assert_eq!(layer_shmd(&PsdFile::from_bytes(&removed).unwrap(), "L"), Some(without.as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_shmd_is_kept_and_reported() {
|
||||
let mut doc = Document::new("Bad", Size::new(2, 2), ColorMode::Rgb, SampleType::U8);
|
||||
let mut l = Layer::raster("L", doc.pixel_format());
|
||||
l.psd_blocks.push((*b"shmd", Arc::new(vec![0, 0, 0, 9])));
|
||||
l.xmp = Some(Arc::from(A));
|
||||
doc.layers.push(l);
|
||||
let out = export(&doc, "x.psd", &ExportOptions::default()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w.contains("XMP metadata was not saved")), "{:?}", out.warnings);
|
||||
assert_eq!(layer_shmd(&PsdFile::from_bytes(&out.bytes).unwrap(), "L"), Some([0, 0, 0, 9].as_slice()));
|
||||
}
|
||||
@@ -106,6 +106,7 @@ testgen::{all_cases, merged_only, layered, small, sample_descriptor, pattern_pla
|
||||
| PSB 8-byte-length keys | ✓ | ✓ | – | LMsk Lr16 Lr32 Layr Mt16 Mt32 Mtrn Alph FMsk lnk2 FEid FXid PxSD |
|
||||
| Lr16 / Lr32 / Layr layer info | ✓ | ✓ | ✓ | lifted into `layer_info`; re-inserted at its original position |
|
||||
| luni lsct lsdk lyid lnsr clbl infx knko lspf lclr iOpa shmd | ✓ | ✓ | ✓ | `TaggedBlock::parsed()` |
|
||||
| Layer XMP (`shmd` › `cust` › `layerXMP`) | ✓ | ✓ | ✓ | `metadata::layer_xmp` / `take_layer_xmp` / `put_layer_xmp`, laid out as Photoshop 2026 writes it |
|
||||
| ActionDescriptor (all OSTypes) | ✓ | ✓ | ✓ | including references, `ObAr` (best effort), `UnFl`, `Pth `, version-16 wrapper |
|
||||
| Layer tree (groups) | ✓ | ✓ | ✓ | open/closed folders plus bounding dividers; tolerant of malformed nesting |
|
||||
| RGBA8 extraction | ✓ | – | – | RGB / gray / CMYK layers; merged image also supports indexed / bitmap / duotone |
|
||||
|
||||
+158
-1
@@ -1,11 +1,12 @@
|
||||
//! `shmd` (metadata setting) layer block: a list of keyed sub-blocks, such as `cmls` (layer comp
|
||||
//! state, a versioned descriptor), `cust` and `mlst`.
|
||||
//! state, a versioned descriptor), `cust` (the layer's modify time and XMP packet) and `mlst`.
|
||||
//!
|
||||
//! Layout (Adobe PSD spec, "Metadata setting"): u32 count, then per item the signature `8BIM`,
|
||||
//! a 4-byte key, a copy-on-sheet-duplication byte, 3 padding bytes, a u32 length and the data.
|
||||
//! Photoshop pads item data to an even length (the padding is part of the stored length), so
|
||||
//! parsing and writing are exact: `write(parse(b)) == b`.
|
||||
|
||||
use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor};
|
||||
use crate::error::{PsdError, Result};
|
||||
use crate::io::{Reader, WriteExt};
|
||||
|
||||
@@ -71,10 +72,166 @@ pub fn write_shmd(items: &[MetadataItem]) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The `shmd` item that holds a layer's own metadata (its modify time and XMP).
|
||||
const CUST: [u8; 4] = *b"cust";
|
||||
/// Key of a layer's XMP packet in the `cust` descriptor.
|
||||
const LAYER_XMP: &str = "layerXMP";
|
||||
|
||||
// A layer's XMP packet (Photoshop's `layer.xmpMetadata.rawData`), as observed in files Photoshop
|
||||
// 2026 saves: a `TEXT` item `layerXMP` (UTF-16 with a terminating NUL) in the `metadata`
|
||||
// descriptor (version 16, class name a lone NUL) of the `shmd` item `cust`, after the
|
||||
// `layerTime` double that every Photoshop layer has. A layer without XMP has no `layerXMP` item.
|
||||
|
||||
fn pad_even(mut v: Vec<u8>) -> Vec<u8> {
|
||||
if v.len() % 2 == 1 {
|
||||
v.push(0);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The `cust` descriptor of `item`, or `None` when it isn't one.
|
||||
fn cust_descriptor(item: &MetadataItem) -> Option<VersionedDescriptor> {
|
||||
(item.key == CUST).then(|| VersionedDescriptor::parse_prefix(&item.data).ok().map(|(d, _)| d)).flatten()
|
||||
}
|
||||
|
||||
/// The XMP packet stored on a layer whose `shmd` block data is `shmd`, or `None` when it has
|
||||
/// none (or the block can't be read).
|
||||
pub fn layer_xmp(shmd: &[u8]) -> Option<String> {
|
||||
let items = parse_shmd(shmd).ok()?;
|
||||
items.iter().filter_map(cust_descriptor).find_map(|d| match d.descriptor.get(LAYER_XMP) {
|
||||
Some(Value::Text(t)) => Some(t.to_string_lossy()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Splits a layer's XMP packet out of its `shmd` block data: the packet, and the block without
|
||||
/// it (`None` when nothing is left). `None` when the block holds no packet, so the caller keeps
|
||||
/// the original bytes. A `cust` item left empty is dropped, the other items are kept as stored.
|
||||
pub fn take_layer_xmp(shmd: &[u8]) -> Option<(String, Option<Vec<u8>>)> {
|
||||
let mut items = parse_shmd(shmd).ok()?;
|
||||
let (i, mut vd) = items.iter().enumerate().find_map(|(i, it)| cust_descriptor(it).filter(|d| d.descriptor.get(LAYER_XMP).is_some()).map(|d| (i, d)))?;
|
||||
let at = vd.descriptor.items.iter().position(|(k, _)| k.is(LAYER_XMP))?;
|
||||
let xmp = match vd.descriptor.items.remove(at).1 {
|
||||
Value::Text(t) => t.to_string_lossy(),
|
||||
_ => return None,
|
||||
};
|
||||
if vd.descriptor.items.is_empty() {
|
||||
items.remove(i);
|
||||
} else {
|
||||
items[i].data = pad_even(vd.to_bytes());
|
||||
}
|
||||
Some((xmp, (!items.is_empty()).then(|| write_shmd(&items))))
|
||||
}
|
||||
|
||||
/// `shmd` block data (`shmd`, or a new block when `None`) with `xmp` as the layer's XMP packet,
|
||||
/// written as Photoshop writes it: it replaces an existing packet in place, or is appended to
|
||||
/// the `cust` descriptor (a new `cust` item when there is none). An unreadable block is an
|
||||
/// error, so the caller never replaces data it couldn't read.
|
||||
pub fn put_layer_xmp(shmd: Option<&[u8]>, xmp: &str) -> Result<Vec<u8>> {
|
||||
let mut items = match shmd {
|
||||
Some(b) => parse_shmd(b)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let value = Value::Text(UnicodeString::new_nul(xmp));
|
||||
match items.iter().position(|it| it.key == CUST) {
|
||||
Some(i) => {
|
||||
let (mut vd, _) = VersionedDescriptor::parse_prefix(&items[i].data)?;
|
||||
match vd.descriptor.items.iter_mut().find(|(k, _)| k.is(LAYER_XMP)) {
|
||||
Some(entry) => entry.1 = value,
|
||||
None => vd.descriptor.items.push((Id::new(LAYER_XMP), value)),
|
||||
}
|
||||
items[i].data = pad_even(vd.to_bytes());
|
||||
}
|
||||
None => {
|
||||
let d = Descriptor { name: UnicodeString::new_nul(""), class_id: Id::new("metadata"), items: vec![(Id::new(LAYER_XMP), value)] };
|
||||
items.push(MetadataItem::new(CUST, VersionedDescriptor::new(d).to_bytes()));
|
||||
}
|
||||
}
|
||||
Ok(write_shmd(&items))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn unhex(lines: &[&str]) -> Vec<u8> {
|
||||
let h: String = lines.concat();
|
||||
(0..h.len()).step_by(2).map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap()).collect()
|
||||
}
|
||||
|
||||
/// `shmd` of a layer saved by Photoshop 2026 after a script set its XMP to [`PS_PACKET`].
|
||||
const PS_WITH_XMP: &[&str] = &[
|
||||
"000000013842494d63757374000000000000024800000010000000010000000000086d65746164617461000000020000",
|
||||
"00096c6179657254696d65646f756241dab643ffd54363000000086c61796572584d505445585400000100003c007800",
|
||||
"3a0078006d0070006d00650074006100200078006d006c006e0073003a0078003d002200610064006f00620065003a00",
|
||||
"6e0073003a006d006500740061002f0022003e003c007200640066003a00520044004600200078006d006c006e007300",
|
||||
"3a007200640066003d00220068007400740070003a002f002f007700770077002e00770033002e006f00720067002f00",
|
||||
"31003900390039002f00300032002f00320032002d007200640066002d00730079006e007400610078002d006e007300",
|
||||
"230022003e003c007200640066003a004400650073006300720069007000740069006f006e0020007200640066003a00",
|
||||
"610062006f00750074003d0022002200200078006d006c006e0073003a00730061006d0070006c0065003d0022006800",
|
||||
"7400740070003a002f002f006500780061006d0070006c0065002e0063006f006d002f00730061006d0070006c006500",
|
||||
"2f0031002e0030002f0022003e003c00730061006d0070006c0065003a00760061006c00750065003e0061006c007000",
|
||||
"680061002d003100320033003c002f00730061006d0070006c0065003a00760061006c00750065003e003c002f007200",
|
||||
"640066003a004400650073006300720069007000740069006f006e003e003c002f007200640066003a00520044004600",
|
||||
"3e003c002f0078003a0078006d0070006d006500740061003e000000",
|
||||
];
|
||||
/// `shmd` of a layer without XMP in the same file (its own `layerTime` only).
|
||||
const PS_WITHOUT_XMP: &[&str] =
|
||||
&["000000013842494d63757374000000000000003400000010000000010000000000086d6574616461746100000001000000096c6179657254696d65646f756241dab643ffd86bec00"];
|
||||
const PS_PACKET: &str = concat!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">"#,
|
||||
r#"<rdf:Description rdf:about="" xmlns:sample="http://example.com/sample/1.0/"><sample:value>alpha-123</sample:value>"#,
|
||||
r#"</rdf:Description></rdf:RDF></x:xmpmeta>"#
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn reads_photoshop_layer_xmp() {
|
||||
assert_eq!(layer_xmp(&unhex(PS_WITH_XMP)).as_deref(), Some(PS_PACKET));
|
||||
assert_eq!(layer_xmp(&unhex(PS_WITHOUT_XMP)), None);
|
||||
assert!(take_layer_xmp(&unhex(PS_WITHOUT_XMP)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_then_put_is_exact() {
|
||||
let ps = unhex(PS_WITH_XMP);
|
||||
let (xmp, rest) = take_layer_xmp(&ps).unwrap();
|
||||
assert_eq!(xmp, PS_PACKET);
|
||||
let rest = rest.unwrap();
|
||||
// What's left is a layer without XMP, shaped as Photoshop writes one.
|
||||
assert_eq!(rest.len(), unhex(PS_WITHOUT_XMP).len());
|
||||
assert_eq!(layer_xmp(&rest), None);
|
||||
assert_eq!(put_layer_xmp(Some(&rest), &xmp).unwrap(), ps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_replaces_in_place_and_creates_a_block() {
|
||||
let ps = unhex(PS_WITH_XMP);
|
||||
let edited = put_layer_xmp(Some(&ps), "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>").unwrap();
|
||||
assert_eq!(layer_xmp(&edited).as_deref(), Some("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>"));
|
||||
// `layerTime` is kept, still first.
|
||||
let items = parse_shmd(&edited).unwrap();
|
||||
let d = cust_descriptor(&items[0]).unwrap().descriptor;
|
||||
assert!(d.items[0].0.is("layerTime") && d.items[1].0.is(LAYER_XMP) && d.items.len() == 2);
|
||||
|
||||
let fresh = put_layer_xmp(None, PS_PACKET).unwrap();
|
||||
assert_eq!(layer_xmp(&fresh).as_deref(), Some(PS_PACKET));
|
||||
assert_eq!(take_layer_xmp(&fresh), Some((PS_PACKET.to_string(), None)));
|
||||
// Other items (here a layer comp state) stay as they were.
|
||||
let comps = write_shmd(&[MetadataItem::new(*b"cmls", vec![1, 2])]);
|
||||
let both = put_layer_xmp(Some(&comps), PS_PACKET).unwrap();
|
||||
assert_eq!(parse_shmd(&both).unwrap()[0], parse_shmd(&comps).unwrap()[0]);
|
||||
assert_eq!(take_layer_xmp(&both).unwrap().1.unwrap(), comps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_refuses_an_unreadable_block() {
|
||||
assert!(put_layer_xmp(Some(&[0, 0, 0, 9]), PS_PACKET).is_err());
|
||||
let bad_cust = write_shmd(&[MetadataItem::new(CUST, vec![0, 0, 0, 16, 1])]);
|
||||
assert!(put_layer_xmp(Some(&bad_cust), PS_PACKET).is_err());
|
||||
assert_eq!(layer_xmp(&bad_cust), None);
|
||||
assert!(take_layer_xmp(&bad_cust).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_exact() {
|
||||
let items = vec![MetadataItem::new(*b"cmls", vec![1, 2, 3]), MetadataItem { copy: true, ..MetadataItem::new(*b"cust", vec![9; 4]) }];
|
||||
|
||||
@@ -21,7 +21,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.
|
||||
|
||||
| Format | Photoshop | PhotoCraft read | PhotoCraft write | Fidelity and tests |
|
||||
|---|---|---|---|---|
|
||||
| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (45 mapped, among them Clouds, Difference Clouds, Fibers and Lens Flare, plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |
|
||||
| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (45 mapped, among them Clouds, Difference Clouds, Fibers and Lens Flare, plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending, each layer's XMP packet (`layer.xmpMetadata`). Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |
|
||||
| PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); generated 20 MP, 150-layer, 2 GB PSD and 4.4 GB PSB fixtures opened, saved and re-opened by io tests/large_files.rs (FILE-216-2, 2026-10-13; the 4.4 GB PSB opens on Windows); > 4 GB from the app's File › Open on Windows: #375 |
|
||||
| Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) |
|
||||
| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders, including Photoshop mixed-order type blocks (#4758); undecodable type keeps saved pixels (FILE-215-7: extra alpha channels not written) |
|
||||
|
||||
Reference in new issue
Block a user