PhotoCraft: An open-source, photo editor written by scratch in pure Rust
PSD import: warn when an adjustment layer can't be read (#1925)
kayrockscreenprinting8b29d6c2cd51
diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rsindex 6a025f98b..4ea5c2787 100644--- a/crates/io/src/adjust_map.rs+++ b/crates/io/src/adjust_map.rs@@ -106,6 +106,38 @@ pub enum Channels {Other,}+/// The menu name of the adjustment a PSD key holds (for messages).+pub fn label(key: &[u8; 4]) -> &'static str {+ match key {+ b"levl" => "Levels",+ b"curv" => "Curves",+ b"hue2" => "Hue/Saturation",+ b"brit" => "Brightness/Contrast",+ b"nvrt" => "Invert",+ b"thrs" => "Threshold",+ b"post" => "Posterize",+ b"expA" => "Exposure",+ b"vibA" => "Vibrance",+ b"blnc" => "Color Balance",+ b"mixr" => "Channel Mixer",+ b"grdm" => "Gradient Map",+ b"phfl" => "Photo Filter",+ b"selc" => "Selective Color",+ b"blwh" => "Black & White",+ b"clrL" => "Color Lookup",+ _ => "adjustment",+ }+}++/// Why [`parse`] keeps a block as [`Adjustment::Unsupported`], when there is more to say than+/// "it could not be read" (so far: Color Lookup).+pub fn unreadable_reason(key: &[u8; 4], data: &[u8]) -> Option<String> {+ match key {+ b"clrL" => read_lookup(data).err(),+ _ => None,+ }+}+/// Parses an adjustment block. `cged` is the optional `CgEd` block data/// (modern brightness/contrast parameters). Levels/Curves store the/// composite record first, then one per document channel (see [`Channels`]).@@ -346,23 +378,31 @@ fn desc_enum<'a>(d: &'a Descriptor, key: &str) -> Option<&'a [u8]> {/// the format named by `LUTFormat`). Profile-based lookups (abstract / device link) have no/// table and stay [`Adjustment::Unsupported`].fn parse_lookup(d: &[u8]) -> Option<Adjustment> {- if be16(d, 0)? != 1 {- return None;+ read_lookup(d).ok()+}++/// [`parse_lookup`] with the reason a block can't be read.+fn read_lookup(d: &[u8]) -> Result<Adjustment, String> {+ match be16(d, 0) {+ Some(1) => {}+ Some(v) => return Err(format!("unknown version {v}")),+ None => return Err("the block is truncated".into()),}- let (v, _) = VersionedDescriptor::parse_prefix(d.get(2..)?).ok()?;+ let (v, _) = VersionedDescriptor::parse_prefix(d.get(2..).unwrap_or_default()).map_err(|e| format!("unreadable settings ({e})"))?;let desc = v.descriptor;- let bytes = match desc.get("LUT3DFileData")? {- Value::RawData(b) if !b.is_empty() => b,- _ => return None,+ let bytes = match desc.get("LUT3DFileData") {+ Some(Value::RawData(b)) if !b.is_empty() => b,+ Some(_) => return Err("its LUT data is empty".into()),+ None => return Err("it uses a colour profile (abstract or device link), not a LUT file, which isn't supported yet".into()),};- let ext = match desc_enum(&desc, "LUTFormat") {- Some(b"LUTFormat3DL") => "x.3dl",- Some(b"LUTFormatLOOK") => "x.look",- _ => "x.cube",+ let (ext, format) = match desc_enum(&desc, "LUTFormat") {+ Some(b"LUTFormat3DL") => ("x.3dl", "3DL"),+ Some(b"LUTFormatLOOK") => ("x.look", "LOOK"),+ _ => ("x.cube", "CUBE"),};- let lut = photocraft_cms::lutfile::parse(ext, bytes).ok()?;+ let lut = photocraft_cms::lutfile::parse(ext, bytes).map_err(|e| format!("its {format} LUT can't be read ({e})"))?;let name = desc_text(&desc, "LUT3DFileName").or_else(|| desc_text(&desc, "NM ")).unwrap_or_default();- Some(Adjustment::ColorLookup {+ Ok(Adjustment::ColorLookup {name,size: lut.size as u32,lut: Some(std::sync::Arc::new(lut.data)),@@ -860,6 +900,18 @@ mod tests {let mut p = vec![0, 1];p.extend(VersionedDescriptor::new(Descriptor::new("null").with("lookupType", en("colorLookupType", "abstractProfile"))).to_bytes());assert!(matches!(parse(b"clrL", &p, None, Channels::Rgb), Adjustment::Unsupported { .. }));+ // Each way a lookup can't be read has a reason for the import warning (#1763).+ assert_eq!(unreadable_reason(b"clrL", &d), None);+ assert!(unreadable_reason(b"clrL", &p).unwrap().contains("colour profile"));+ assert!(unreadable_reason(b"clrL", &[0]).unwrap().contains("truncated"));+ assert!(unreadable_reason(b"clrL", &[0, 2, 0, 0]).unwrap().contains("version 2"));+ assert!(unreadable_reason(b"clrL", &[0, 1, 9]).unwrap().contains("unreadable settings"));+ let bad = Descriptor::new("null").with("LUTFormat", en("LUTFormatType", "LUTFormat3DL")).with("LUT3DFileData", Value::RawData(b"not a lut".to_vec()));+ let mut b = vec![0, 1];+ b.extend(VersionedDescriptor::new(bad).to_bytes());+ assert!(matches!(parse(b"clrL", &b, None, Channels::Rgb), Adjustment::Unsupported { .. }));+ assert!(unreadable_reason(b"clrL", &b).unwrap().contains("3DL LUT can't be read"), "{:?}", unreadable_reason(b"clrL", &b));+ assert_eq!(label(b"clrL"), "Color Lookup");assert!(matches!(parse(b"clrL", &[0, 1, 9], None, Channels::Rgb), Adjustment::Unsupported { .. }));assert!(matches!(parse(b"selc", &[0, 1, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. }));}diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex fd8816437..d9a507a8b 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -270,7 +270,7 @@ impl Ctx<'_> {let content = if let Some(k) = adj_key {let data = rec.block(k).map(|b| b.data.clone()).unwrap_or_default();let cged = rec.block(b"CgEd").map(|b| &b.data[..]);- LayerContent::Adjustment(adjust_map::parse(+ let adj = adjust_map::parse(k,&data,cged,@@ -281,7 +281,17 @@ impl Ctx<'_> {ColorMode::Lab => adjust_map::Channels::Lab,_ => adjust_map::Channels::Other,},- ))+ );+ // Kept verbatim for saving, but it renders as nothing: say so rather than open the+ // layer silently without its effect (#1763).+ if matches!(adj, photocraft_doc::Adjustment::Unsupported { .. }) {+ let why = adjust_map::unreadable_reason(k, &data).map(|r| format!(" ({r})")).unwrap_or_default();+ self.warn(format!(+ "layer \"{name}\": its {} settings could not be read{why}; the layer is kept as saved but has no effect",+ adjust_map::label(k)+ ));+ }+ LayerContent::Adjustment(adj)} else if rec.block(b"TySh").is_some() {// Typed model from TySh/EngineData (photocraft-text); Photoshop's pixels stay the cache.let data = rec.block(b"TySh").map(|b| b.data.clone()).unwrap_or_default();diff --git a/crates/io/tests/adjust_warnings.rs b/crates/io/tests/adjust_warnings.rsnew file mode 100644index 000000000..9b91f40bc--- /dev/null+++ b/crates/io/tests/adjust_warnings.rs@@ -0,0 +1,42 @@+//! Opening a file whose adjustment layer can't be read warns, naming the layer and the reason,+//! instead of opening it silently without its effect (#1763).++use photocraft_color::{ColorMode, SampleType};+use photocraft_doc::{Adjustment, Document, Layer, LayerContent};+use photocraft_geom::Size;+use photocraft_io::*;++fn reopen(adj: Adjustment, path: &str, opts: &ExportOptions) -> (Document, Vec<String>) {+ let mut d = Document::new("a", Size::new(16, 16), ColorMode::Rgb, SampleType::U8);+ d.layers.push(Layer::new("Teal Look", LayerContent::Adjustment(adj)));+ let r = export(&d, path, opts).expect("export");+ let imp = import(path, &r.bytes).expect("import");+ (imp.document, imp.warnings)+}++#[test]+fn unreadable_adjustments_warn_on_open() {+ // A Color Lookup that uses a profile, not a LUT file: kept verbatim, not applied.+ let profile = Adjustment::Unsupported { psd_key: "clrL".into(), raw: vec![0, 2, 0, 0] };+ for (path, opts) in [("x.psd", ExportOptions::default()), ("x.psb", ExportOptions { force_psb: true, ..Default::default() })] {+ let (doc, warnings) = reopen(profile.clone(), path, &opts);+ assert!(matches!(&doc.layers[0].content, LayerContent::Adjustment(Adjustment::Unsupported { .. })), "{path}");+ let w: Vec<&String> = warnings.iter().filter(|w| w.contains("Teal Look")).collect();+ assert_eq!(w.len(), 1, "{path}: {warnings:?}");+ assert!(w[0].contains("Color Lookup") && w[0].contains("version 2") && w[0].contains("no effect"), "{path}: {}", w[0]);+ }+ // Another kind without a specific reason still names the layer and the adjustment.+ let (_, warnings) = reopen(Adjustment::Unsupported { psd_key: "levl".into(), raw: vec![0, 9] }, "x.psd", &ExportOptions::default());+ assert!(warnings.iter().any(|w| w.contains("Teal Look") && w.contains("Levels settings could not be read;")), "{warnings:?}");+}++#[test]+fn readable_adjustments_open_without_warnings() {+ let lut: Vec<f32> = (0..8).flat_map(|i| [(i & 1) as f32, ((i >> 1) & 1) as f32, ((i >> 2) & 1) as f32]).collect();+ let lookup = Adjustment::ColorLookup { name: "id.cube".into(), size: 2, lut: Some(std::sync::Arc::new(lut)), tetrahedral: false, dither: false };+ for adj in [lookup, Adjustment::Invert] {+ let (doc, warnings) = reopen(adj, "x.psd", &ExportOptions::default());+ assert!(!matches!(&doc.layers[0].content, LayerContent::Adjustment(Adjustment::Unsupported { .. })));+ assert!(!warnings.iter().any(|w| w.contains("Teal Look")), "{warnings:?}");+ }+}