Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Color Lookup: warn when it opens without its usable table (part of #1763) (#6322)

Ahmed Hosny7b99c329234a
diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs
index cd34ab341..fc4526eed 100644
--- a/crates/automation/src/files.rs
+++ b/crates/automation/src/files.rs
@@ -19,7 +19,8 @@ pub struct Opened {
/// Decode a document that was read through a filesystem capability.
pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<Opened, AutomationError> {
if Path::new(name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case(photocraft_format::EXTENSION)) {
- return Ok(Opened { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new(), source_read_only: false });
+ let document = photocraft_format::load_from_bytes(bytes)?;
+ return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false });
}
let r = photocraft_io::import(name, bytes)?;
Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only })
@@ -29,7 +30,8 @@ pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<Opened, AutomationError> {
/// natively; everything else goes through `photocraft-io` (PSD, PNG, …).
pub fn open(path: &Path) -> Result<Opened, AutomationError> {
if path.is_dir() {
- return Ok(Opened { document: photocraft_format::load_path(path)?, warnings: Vec::new(), source_read_only: false });
+ let document = photocraft_format::load_path(path)?;
+ return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false });
}
let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 3543cd359..02381d983 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -69,7 +69,7 @@ pub mod vector_map;
pub use photocraft_codecs::DpxBits;
use photocraft_codecs::{CodecError, EncodeOptions};
-use photocraft_doc::Document;
+use photocraft_doc::{Adjustment, Document, Layer, LayerContent};
use photocraft_psd::{PsdError, PsdFile};
pub use adjust_map::ADJUSTMENT_KEYS;
@@ -140,6 +140,34 @@ pub(crate) fn unequal_resolution_warning(x: f64, y: f64) -> Option<String> {
.then(|| format!("the vertical resolution ({y:.2} ppi) differs from the horizontal ({x:.2} ppi); the document keeps {x:.2} ppi for both"))
}
+/// Warnings about a loaded document's layers that render without their stored effect, for
+/// sources that carry no import warnings of their own (a crafted `.pcraft`): a Color Lookup
+/// whose table can't be applied silently renders as the identity instead (#1763).
+pub fn open_warnings(doc: &Document) -> Vec<String> {
+ let mut out = Vec::new();
+ // Iterative, so no document's nesting can make this recurse.
+ let mut stack: Vec<&Layer> = doc.layers.iter().rev().collect();
+ while let Some(l) = stack.pop() {
+ if let LayerContent::Adjustment(Adjustment::ColorLookup { name: _, size, lut, .. }) = &l.content {
+ match lut.as_deref().zip(photocraft_doc::adjust::lut3d_len(*size)) {
+ Some((table, len)) if table.len() >= len => {}
+ Some((table, len)) => out.push(format!(
+ "layer \"{}\": its Color Lookup table has {} values, but a {size}³ lookup needs {len}; the layer renders without the lookup",
+ l.name,
+ table.len()
+ )),
+ None => {
+ out.push(format!("layer \"{}\": its Color Lookup has no usable table for a {size}³ lookup; the layer renders without the lookup", l.name))
+ }
+ }
+ }
+ if let Some(children) = l.children() {
+ stack.extend(children.iter().rev());
+ }
+ }
+ out
+}
+
/// Result of [`export`].
#[derive(Debug, Clone)]
pub struct ExportResult {
@@ -276,7 +304,8 @@ pub fn import_with_svg_group_depth_and_interrupt(
fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, max_group_depth: usize) -> Result<ImportResult, IoError> {
// A declared native extension must reach its loader so malformed bundles retain format errors.
if has_extension(name, photocraft_format::EXTENSION) || photocraft_format::is_pcraft(bytes) {
- return Ok(ImportResult { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new(), source_read_only: false, preview_only: false });
+ let document = photocraft_format::load_from_bytes(bytes)?;
+ return Ok(ImportResult { warnings: open_warnings(&document), document, source_read_only: false, preview_only: false });
}
if is_psd(bytes) {
// A merged image the import reads is decoded with the parse: a ZIP one is inflated once.
diff --git a/crates/io/tests/adjust_warnings.rs b/crates/io/tests/adjust_warnings.rs
index 9b91f40bc..c5bba0182 100644
--- a/crates/io/tests/adjust_warnings.rs
+++ b/crates/io/tests/adjust_warnings.rs
@@ -5,6 +5,8 @@ use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Adjustment, Document, Layer, LayerContent};
use photocraft_geom::Size;
use photocraft_io::*;
+use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor};
+use photocraft_raster::Surface;
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);
@@ -40,3 +42,70 @@ fn readable_adjustments_open_without_warnings() {
assert!(!warnings.iter().any(|w| w.contains("Teal Look")), "{warnings:?}");
}
}
+
+/// The raw bytes of a `clrL` block laid out the way Photoshop writes it (Adobe spec): version 1,
+/// then a version 16 descriptor carrying a small `.cube` LUT file (its entry for red maps to
+/// cyan, so the table is not the identity).
+fn photoshop_clr_l_block() -> Vec<u8> {
+ let cube = b"LUT_3D_SIZE 2\n0 0 0\n0 1 1\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";
+ let en = |t: &str, val: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(val) };
+ let text = |t: &str| Value::Text(UnicodeString::new_nul(t));
+ let desc = Descriptor::new("null")
+ .with("NM ", text("Frost"))
+ .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE"))
+ .with("LUT3DFileName", text("frost.cube"))
+ .with("LUT3DFileData", Value::RawData(cube.to_vec()));
+ let mut raw = vec![0, 1];
+ raw.extend(VersionedDescriptor::new(desc).to_bytes());
+ assert_eq!(&raw[..6], &[0, 1, 0, 0, 0, 16], "version 1, then the descriptor's version 16");
+ raw
+}
+
+#[test]
+fn photoshop_layout_color_lookup_round_trips_through_psb() {
+ // A kept-raw `clrL` block in Photoshop's layout survives a PSB round trip and reopens as a
+ // working Color Lookup, with no warning naming the layer (#1763).
+ let raw = photoshop_clr_l_block();
+ let opts = ExportOptions { force_psb: true, ..Default::default() };
+ let (doc, warnings) = reopen(Adjustment::Unsupported { psd_key: "clrL".into(), raw: raw.clone() }, "x.psb", &opts);
+ assert!(warnings.iter().all(|w| !w.contains("Teal Look")), "{warnings:?}");
+ let LayerContent::Adjustment(Adjustment::ColorLookup { name, size, lut: Some(table), tetrahedral: false, dither: false }) = &doc.layers[0].content else {
+ panic!("{:?}", doc.layers[0].content)
+ };
+ assert_eq!(name, "frost.cube");
+ assert_eq!(*size, 2);
+ let want: Vec<f32> = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0].into();
+ assert_eq!(table.as_slice(), want.as_slice());
+ // The exporter wrote the block verbatim (the importer keeps it for saving; the block writer
+ // pads to Photoshop's four-byte alignment, which the spec requires).
+ let kept = doc.layers[0].psd_blocks.iter().find(|(k, _)| k == b"clrL").map(|(_, d)| d.as_slice());
+ let Some(kept) = kept else { panic!("{:?}", doc.layers[0].psd_blocks) };
+ assert!(kept.starts_with(&raw) && kept[raw.len()..].iter().all(|&b| b == 0), "{kept:?}");
+ // The reopened lookup really applies: a red backdrop renders as the table's cyan.
+ let mut d = doc;
+ let mut bg = Surface::new(d.pixel_format());
+ bg.fill_rect(d.bounds(), &[1.0, 0.0, 0.0, 1.0]);
+ d.layers.insert(0, Layer::new("bg", LayerContent::Raster(bg)));
+ let px = photocraft_compose::flatten(&d).px[0];
+ assert!(px[0] < 0.05 && (px[1] - 1.0).abs() < 0.05 && (px[2] - 1.0).abs() < 0.05, "{px:?}");
+}
+
+#[test]
+fn short_color_lookup_table_warns_on_open() {
+ // A stored table shorter than size³×3 renders as the identity; opening must say so, naming
+ // the layer (#1763).
+ let short = Adjustment::ColorLookup { name: "t.cube".into(), size: 3, lut: Some(std::sync::Arc::new(vec![0.5; 7])), tetrahedral: false, dither: false };
+ let (doc, warnings) = reopen(short, "x.pcraft", &ExportOptions::default());
+ assert!(matches!(&doc.layers[0].content, LayerContent::Adjustment(Adjustment::ColorLookup { .. })), "{:?}", doc.layers[0].content);
+ let w: Vec<&String> = warnings.iter().filter(|w| w.contains("Teal Look")).collect();
+ assert_eq!(w.len(), 1, "{warnings:?}");
+ assert!(w[0].contains("Color Lookup") && w[0].contains("7 values") && w[0].contains("81"), "{}", w[0]);
+ // A table long enough for its size opens without the note.
+ let ok = Adjustment::ColorLookup { name: "t.cube".into(), size: 2, lut: Some(std::sync::Arc::new(vec![0.5; 24])), tetrahedral: false, dither: false };
+ let (_, warnings) = reopen(ok, "x.pcraft", &ExportOptions::default());
+ assert!(warnings.iter().all(|w| !w.contains("Teal Look")), "{warnings:?}");
+ // A missing table renders as the identity too.
+ let none = Adjustment::ColorLookup { name: "t.cube".into(), size: 2, lut: None, tetrahedral: false, dither: false };
+ let (_, warnings) = reopen(none, "x.pcraft", &ExportOptions::default());
+ assert!(warnings.iter().any(|w| w.contains("Teal Look") && w.contains("no usable table")), "{warnings:?}");
+}