PhotoCraft: An open-source, photo editor written by scratch in pure Rust
PSD: open an adjustment layer of an unknown type as an unsupported adjustment (#6575)
David Manned4e94a47934
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 8ba30d83c..d13c17633 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -599,8 +599,16 @@ impl Ex {let keep = keep|| (matches!(a, photocraft_doc::Adjustment::GradientMap { .. })&& raw.iter_mut().any(|(k, d)| k == b"grdm" && adjust_map::retarget_gradient_map(d, a, channels)));+ // An adjustment type no mapper knows (#6575) is its block: kept verbatim, and+ // never written a second time beside a stale copy.+ let own = match a {+ photocraft_doc::Adjustment::Unsupported { psd_key, .. } => Some(psd_key.as_bytes()),+ _ => None,+ };+ let keep =+ keep || matches!(a, photocraft_doc::Adjustment::Unsupported { raw: r, .. } if raw.iter().any(|(k, d)| own == Some(&k[..]) && d == r));if !keep {- raw.retain(|(k, _)| !adjust_map::ADJUSTMENT_KEYS.contains(&k) && k != b"CgEd");+ raw.retain(|(k, _)| !adjust_map::ADJUSTMENT_KEYS.contains(&k) && k != b"CgEd" && own != Some(&k[..]));let w = adjust_map::write(a);if w.is_empty() {self.warnings.push(format!("layer \"{}\": {} adjustment is not yet written to PSD", l.name, a.label()));diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex 12307f32b..cdafe04cd 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -465,6 +465,15 @@ impl Ctx<'_> {LayerContent::Raster(self.record_surface(rec, &name))}}+ } else if let Some(k) = unknown_adjustment_key(rec) {+ // An adjustment type no mapper knows: kept verbatim like an unreadable one, not+ // opened as an empty pixel layer without a word (#6575).+ let key = String::from_utf8_lossy(&k).into_owned();+ self.warn(format!(+ "layer \"{name}\": its adjustment settings could not be read (unknown adjustment type \"{key}\"); the layer is kept as saved but has no effect"+ ));+ let raw = rec.block(&k).map(|b| b.data.clone()).unwrap_or_default();+ LayerContent::Adjustment(photocraft_doc::Adjustment::Unsupported { psd_key: key, raw })} else {LayerContent::Raster(self.record_surface(rec, &name))};@@ -595,6 +604,33 @@ pub(crate) fn group_depth(file: &PsdFile) -> usize {depth}+/// Additional-layer-information keys (Adobe PSD spec, plus `cust`, `vowv` and `SoLE` seen in+/// Photoshop's files) that are not an adjustment of their own: names, ids, locks, effects,+/// masks, metadata, and the fill, type, placed and shape content read before.+const LAYER_INFO_KEYS: [&[u8; 4]; 50] = [+ b"luni", b"lyid", b"lnsr", b"lsct", b"lsdk", b"lspf", b"lclr", b"iOpa", b"clbl", b"infx", b"knko", b"tsly", b"lmgm", b"vmgm", b"brst", b"shmd", b"fxrp",+ b"lfx2", b"lfxs", b"lmfx", b"lrFX", b"lyvr", b"sn2P", b"cust", b"CgEd", b"vmsk", b"vsms", b"vogk", b"vowv", b"vstk", b"vscg", b"artb", b"artd", b"abdd",+ b"FMsk", b"PxSc", b"PxSD", b"cinf", b"ffxi", b"shpa", b"anFX", b"SoCo", b"GdFl", b"PtFl", b"TySh", b"tySh", b"SoLd", b"SoLE", b"PlLd", b"plLd",+];++/// The key of an adjustment layer whose type no mapper knows (#6575), e.g. Photoshop 4's+/// `hue ` or a type newer than PhotoCraft. Photoshop writes every adjustment layer without+/// pixels and with "pixel data irrelevant" set (every one in the corpus; pixel, type and smart+/// layers never have it). Such a record that is not a group and carries exactly one block that+/// is neither a known layer-information key nor a known adjustment is that adjustment. More than+/// one candidate is a guess, so the layer stays an (empty) pixel layer, as before; either way no+/// pixels can be lost and the block is saved back verbatim.+fn unknown_adjustment_key(rec: &LayerRecord) -> Option<[u8; 4]> {+ let marked = rec.flags.bit4_useful() && rec.flags.pixel_data_irrelevant();+ if !marked || !rec.rect.is_empty() || rec.block(b"lsct").is_some() || rec.block(b"lsdk").is_some() {+ return None;+ }+ let mut unknown = rec.blocks.iter().filter(|b| !LAYER_INFO_KEYS.contains(&&b.key) && !ADJUSTMENT_KEYS.contains(&&b.key));+ let only = unknown.next()?;+ // A key that isn't four printable ASCII bytes names no adjustment (nor saves back as one).+ (unknown.next().is_none() && only.key.iter().all(|c| c.is_ascii_graphic() || *c == b' ')).then_some(only.key)+}+fn preserved_blocks(rec: &LayerRecord) -> Vec<([u8; 4], Arc<Vec<u8>>)> {rec.blocks.iter().filter(|b| !REGENERATED.contains(&&b.key)).map(|b| (b.key, Arc::new(b.data.clone()))).collect()}diff --git a/crates/io/tests/psd_unknown_adjustment.rs b/crates/io/tests/psd_unknown_adjustment.rsnew file mode 100644index 000000000..5a7981c5c--- /dev/null+++ b/crates/io/tests/psd_unknown_adjustment.rs@@ -0,0 +1,106 @@+//! An adjustment layer whose key PhotoCraft doesn't know (an older or newer adjustment type)+//! opens as an unsupported adjustment with a warning and saves its block back unchanged, instead+//! of opening silently as an empty pixel layer (#6575). Pixel layers that merely carry an unknown+//! block stay pixel layers.++use photocraft_doc::{Adjustment, Document, LayerContent};+use photocraft_io::*;+use photocraft_psd::testgen;+use photocraft_psd::{ChannelData, Compression, LayerFlags, LayerRecord, PsdFile, Rect, TaggedBlock, Version};++/// A layer record as Photoshop writes an adjustment layer: no pixels, "pixel data irrelevant"+/// set, the adjustment block first, then the usual metadata.+fn adjustment_record(name: &str, blocks: Vec<TaggedBlock>) -> LayerRecord {+ let mut flags = LayerFlags::default();+ flags.set_pixel_data_irrelevant(true);+ let mut all = blocks;+ all.extend([TaggedBlock::unicode_name(name), TaggedBlock::layer_id(77)]);+ LayerRecord { name: name.as_bytes().to_vec(), flags, blocks: all, ..Default::default() }+}++fn open(f: &PsdFile) -> (Document, Vec<String>) {+ let bytes = f.to_bytes().expect("write psd");+ let imp = import("x.psd", &bytes).expect("import");+ (imp.document, imp.warnings)+}++fn save(d: &Document) -> PsdFile {+ let r = export(d, "x.psd", &ExportOptions::default()).expect("export");+ PsdFile::from_bytes(&r.bytes).expect("reparse")+}++fn content<'a>(d: &'a Document, name: &str) -> &'a LayerContent {+ &d.layers.iter().find(|l| l.name == name).unwrap_or_else(|| panic!("layer {name}")).content+}++fn record<'a>(f: &'a PsdFile, name: &str) -> &'a LayerRecord {+ f.layers().iter().find(|r| r.name() == name).unwrap_or_else(|| panic!("record {name}"))+}++#[test]+fn unknown_adjustment_key_opens_as_unsupported_and_saves_verbatim() {+ // `hue ` is the Photoshop 4 Hue/Saturation block (in the spec, never mapped); `zNew` stands+ // for an adjustment type newer than PhotoCraft.+ for key in [*b"hue ", *b"zNew"] {+ let data = vec![0, 2, 1, 2, 3, 4, 5, 6];+ let mut f = testgen::small(Version::Psd, Compression::Raw);+ f.layers_mut().push(adjustment_record("Mystery", vec![TaggedBlock::new(key, data.clone())]));+ let (d, warnings) = open(&f);+ let k = String::from_utf8_lossy(&key).into_owned();+ assert!(+ matches!(content(&d, "Mystery"), LayerContent::Adjustment(Adjustment::Unsupported { psd_key, raw }) if *psd_key == k && *raw == data),+ "{k}: {:?}",+ content(&d, "Mystery")+ );+ let w: Vec<&String> = warnings.iter().filter(|w| w.contains("Mystery")).collect();+ assert_eq!(w.len(), 1, "{k}: {warnings:?}");+ assert!(w[0].contains(&format!("\"{k}\"")) && w[0].contains("no effect"), "{k}: {}", w[0]);++ // Saved back: the block exactly once, byte-identical, still an adjustment record.+ let g = save(&d);+ let r = record(&g, "Mystery");+ let same: Vec<&TaggedBlock> = r.blocks.iter().filter(|b| b.key == key).collect();+ assert_eq!(same.len(), 1, "{k}: {:?}", r.blocks.iter().map(TaggedBlock::key_str).collect::<Vec<_>>());+ assert_eq!(same[0].data, data, "{k}");+ assert!(r.flags.bit4_useful() && r.flags.pixel_data_irrelevant(), "{k}");+ assert!(r.rect.is_empty(), "{k}");+ // And it reopens the same way.+ let (d2, _) = open(&g);+ assert_eq!(content(&d2, "Mystery"), content(&d, "Mystery"), "{k}");+ }+}++#[test]+fn pixel_layers_with_unknown_blocks_stay_pixel_layers() {+ let extra = || TaggedBlock::new(*b"zNew", vec![9, 8, 7, 6]);+ let mut f = testgen::small(Version::Psd, Compression::Raw);+ // A normal pixel layer (pixels, flag clear) carrying an unknown block.+ f.layers_mut()[0].blocks.push(extra());+ // Flagged but with pixels: never dropped for an adjustment.+ let plane = |id: i16| ChannelData { id, compression: Some(Compression::Raw), data: vec![200; 4] };+ let mut painted = adjustment_record("painted", vec![extra()]);+ painted.rect = Rect::from_xywh(0, 0, 2, 2);+ painted.channels = (-1..3).map(plane).collect();+ f.layers_mut().push(painted);+ // No pixels and an unknown block, but not marked "pixel data irrelevant": an empty pixel layer.+ let mut unflagged = adjustment_record("unflagged", vec![extra()]);+ unflagged.flags = LayerFlags::default();+ f.layers_mut().push(unflagged);+ // Two unknown blocks: which one is the adjustment is a guess, so nothing is guessed.+ f.layers_mut().push(adjustment_record("ambiguous", vec![extra(), TaggedBlock::new(*b"zOth", vec![1, 1, 1, 1])]));+ let (d, warnings) = open(&f);+ for name in ["a", "painted", "unflagged", "ambiguous"] {+ assert!(matches!(content(&d, name), LayerContent::Raster(_)), "{name}: {:?}", content(&d, name));+ assert!(!warnings.iter().any(|w| w.contains(&format!("\"{name}\""))), "{name}: {warnings:?}");+ }+ let LayerContent::Raster(s) = content(&d, "painted") else { unreachable!() };+ assert!(!s.content_bounds().is_empty(), "painted keeps its pixels");+ // The unknown block is still kept verbatim on save, once.+ let g = save(&d);+ for name in ["a", "painted", "unflagged", "ambiguous"] {+ let r = record(&g, name);+ let kept: Vec<&TaggedBlock> = r.blocks.iter().filter(|b| &b.key == b"zNew").collect();+ assert_eq!(kept.len(), 1, "{name}");+ assert_eq!(kept[0].data, vec![9, 8, 7, 6], "{name}");+ }+}