Skip to content

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

Merge PR #5815: perf(doc): share the XMP packet, Duotone PSD data and unsupported adjustment bytes between snapshots

David Manncab3ef6191f1
diff --cc crates/engine/src/inspect.rs
index f708d856f,6068503ae..e4c93c7cb
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@@ -217,32 -210,6 +217,32 @@@ mod tests
assert!(!adj.to_string().contains('_'), "{adj}");
}
+ /// #6541: an adjustment PhotoCraft keeps but cannot render is reported as such, not as an Invert.
+ #[test]
+ fn an_unsupported_adjustment_layer_is_reported_as_kept_not_rendered() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();
+ s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
+ s.edit("unsupported fixture", |doc, active| {
- let l = Layer::new("Mystery", LayerContent::Adjustment(Adjustment::Unsupported { psd_key: "xyzw".into(), raw: vec![1, 2, 3] }));
++ let l = Layer::new("Mystery", LayerContent::Adjustment(Adjustment::Unsupported { psd_key: "xyzw".into(), raw: vec![1, 2, 3].into() }));
+ let id = l.id;
+ doc.layers.push(l);
+ *active = Some(id);
+ Ok(())
+ })
+ .unwrap();
+ let info = s.execute("document.inspect", json!({})).unwrap();
+ let layers = info["layers"].as_array().unwrap();
+ let unsupported = &layers[0]["adjustment"];
+ assert_eq!(unsupported["kind"], "unsupported", "{unsupported}");
+ assert_eq!(unsupported["unsupported"], json!(true));
+ assert_eq!(unsupported["psdKey"], "xyzw");
+ // A real Invert reports neither flag.
+ let invert = &layers[1]["adjustment"];
+ assert_eq!(invert["kind"], "invert");
+ assert!(invert.get("unsupported").is_none(), "{invert}");
+ }
+
#[test]
fn document_inspect_reports_raster_and_vector_masks_when_nested() {
let cases = [(false, None), (true, None), (false, Some(true)), (false, Some(false)), (true, Some(true))];
diff --cc crates/engine/src/tests.rs
index 0b1b48aa3,f1083b6ac..9e06c966d
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -1763,29 -1613,36 +1763,63 @@@ fn merge_down_on_a_group_merges_the_gro
assert!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(group)).is_some());
}
+/// `restore_layer_selection` puts a multi-layer selection back, drops gone layers, keeps a clean
+/// document clean, and refuses a gone active layer without changing anything.
+#[test]
+fn restore_layer_selection_puts_back_what_still_exists() {
+ let mut s = session_with_doc();
+ let id = |v: Value| LayerId(v["layer"].as_u64().unwrap());
+ let a = id(s.execute("layer.new.layer", json!({})).unwrap());
+ let b = id(s.execute("layer.new.layer", json!({})).unwrap());
+ let gone = LayerId(u64::MAX);
+ s.active_mut().unwrap().saved_revision = s.active().unwrap().revision;
+ s.restore_layer_selection(Some(b), &[a, gone, b], Some(a)).unwrap();
+ let st = s.active().unwrap();
+ assert_eq!((st.active_layer, st.selected_layers(), st.layer_anchor), (Some(b), vec![a, b], Some(a)));
+ assert_eq!(st.saved_revision, st.revision, "selection is not an edit");
+ let snap = |s: &Session| {
+ let st = s.active().unwrap();
+ (st.active_layer, st.selected_layers(), st.layer_anchor, st.revision, st.saved_revision)
+ };
+ let before = snap(&s);
+ assert!(matches!(s.restore_layer_selection(Some(gone), &[gone], None), Err(EngineError::NoLayer(_))));
+ assert_eq!(snap(&s), before, "an error changes nothing");
+ s.restore_layer_selection(None, &[a], Some(a)).unwrap();
+ let st = s.active().unwrap();
+ assert_eq!((st.active_layer, st.selected_layers(), st.layer_anchor), (None, vec![], None), "no layer selected");
+ assert!(Session::new().restore_layer_selection(None, &[], None).is_err(), "no document");
+}
++
+ /// #4535: every edit snapshots the document into history. The large payloads it carries (the
+ /// XMP packet, Duotone's PSD data, an unsupported adjustment's bytes) are shared between the
+ /// snapshot and the document, not copied per state.
+ #[test]
+ fn history_states_share_large_document_payloads() {
+ use photocraft_doc::{Adjustment, Duotone, DuotoneInk, Layer, LayerContent};
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
+ let raw_id = {
+ let st = s.active_mut().unwrap();
+ let doc = std::sync::Arc::make_mut(&mut st.doc);
+ doc.metadata.xmp = Some("x".repeat(1 << 20).into());
+ doc.duotone = Some(Duotone { inks: vec![DuotoneInk::new("Black", [0.0; 3])], psd_raw: Some(vec![7u8; 1 << 16].into()) });
+ let layer = Layer::new("kept", LayerContent::Adjustment(Adjustment::Unsupported { psd_key: "abcd".into(), raw: vec![9u8; 1 << 16].into() }));
+ let id = layer.id;
+ doc.layers.push(layer);
+ id
+ };
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let st = s.active().unwrap();
+ let before = st.history.state(st.history.past_len() - 1).unwrap();
+ let (now, then) = (&st.doc, &before);
+ assert!(!std::sync::Arc::ptr_eq(now, then), "the edit made a new document");
+ let xmp = |d: &Document| d.metadata.xmp.clone().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&xmp(now), &xmp(then)), "the XMP packet is shared");
+ let duotone = |d: &Document| d.duotone.as_ref().and_then(|d| d.psd_raw.clone()).unwrap();
+ assert!(std::sync::Arc::ptr_eq(&duotone(now), &duotone(then)), "the Duotone data is shared");
+ let raw = |d: &Document| match &d.layer(raw_id).unwrap().content {
+ LayerContent::Adjustment(Adjustment::Unsupported { raw, .. }) => raw.clone(),
+ other => panic!("{other:?}"),
+ };
+ assert!(std::sync::Arc::ptr_eq(&raw(now), &raw(then)), "the adjustment's bytes are shared");
+ }
diff --cc crates/io/src/psd_export.rs
index 3f772a2fb,007281ead..6070d651f
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@@ -621,19 -603,9 +621,19 @@@ impl Ex
// updated in place.
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)));
+ && raw.iter_mut().any(|(k, d)| {
+ k == b"grdm" && !adjust_map::is_unpadded_photocraft_gradient_map(d) && 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));
++ 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()));
@@@ -1632,18 -1520,7 +1632,18 @@@ fn document_to_psd_nested(doc: &Documen
if doc.mode == ColorMode::Multichannel {
return crate::multichannel_map::document_to_psd(doc, opts.force_psb);
}
+ if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) {
+ return file;
+ }
let fmt = doc.pixel_format();
+ // A Duotone is written over its grey plate with its inks: the block it was imported with,
+ // verbatim, while the inks are unedited, else one made from them (`duotone_map`). Photoshop
+ // has only 8-bit Duotone: it refuses to open a 16-bit one.
+ let duotone_inks: Option<Vec<u8>> = doc
+ .duotone
+ .as_ref()
+ .filter(|d| !d.inks.is_empty() && doc.mode == ColorMode::Duotone && fmt.mode == ColorMode::Grayscale && fmt.sample == SampleType::U8)
- .map(|d| d.psd_raw.clone().unwrap_or_else(|| crate::duotone_map::write(d)));
++ .map(|d| d.psd_raw.as_deref().map_or_else(|| crate::duotone_map::write(d), <[u8]>::to_vec));
let sample = fmt.sample;
let cc = fmt.mode.color_channels();
let big = doc.size.width > 30_000 || doc.size.height > 30_000;
diff --cc crates/io/src/psd_import.rs
index bf4707bce,5355b624b..43dc334a6
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@@ -498,15 -465,6 +498,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();
++ let raw = rec.block(&k).map(|b| b.data.as_slice()).unwrap_or_default().into();
+ LayerContent::Adjustment(photocraft_doc::Adjustment::Unsupported { psd_key: key, raw })
} else {
LayerContent::Raster(self.record_surface(rec, &name))
};
@@@ -1070,24 -1000,15 +1070,24 @@@ pub(crate) fn psd_to_document_decoded
if h.color_mode == PsdMode::Indexed && file.color_mode_data.len() >= 768 {
// Planar palette: 256 reds, 256 greens, 256 blues (the Color Table).
let m = &file.color_mode_data;
- let colors = (0..256).map(|i| [m[i], m[256 + i], m[512 + i]]).collect();
- doc.color_table = Some(photocraft_doc::ColorTable { colors, transparent: None });
+ // Resource 1046 says how many entries are used, 1047 which one is transparent.
+ let u16_of = |id: u16| file.resource(id).and_then(|r| r.data.get(..2)).map(|b| u16::from_be_bytes([b[0], b[1]]));
+ let count = u16_of(crate::palette_map::COLOR_TABLE_COUNT).map_or(256, usize::from).clamp(1, 256);
+ let colors = (0..count).map(|i| [m[i], m[256 + i], m[512 + i]]).collect();
+ let transparent = u16_of(crate::palette_map::TRANSPARENCY_INDEX).filter(|&i| usize::from(i) < count).map(|i| i as u8);
+ doc.color_table = Some(photocraft_doc::ColorTable { colors, transparent });
} else if h.color_mode == PsdMode::Duotone && !file.color_mode_data.is_empty() {
- // The duotone ink block is undocumented: keep it raw; the image shows as its gray plate.
- doc.duotone = Some(photocraft_doc::Duotone {
- inks: vec![photocraft_doc::DuotoneInk::new("Black", [0.0; 3])],
- psd_raw: Some(file.color_mode_data.as_slice().into()),
- });
- cx.warn("duotone inks are not interpreted (shown as grayscale)");
+ // The inks (`duotone_map`); the block is also kept raw, written back while they stay
+ // unedited. An ink whose colour is unknown (a colour book without its Lab equivalent)
+ // would show black and darken the image: the grey plate is shown instead, as before.
+ let mut unknown = false;
+ let alternate = file.resource(crate::duotone_map::ALTERNATE_DUOTONE_COLORS).map(|r| r.data.as_slice());
+ let inks = crate::duotone_map::parse(&file.color_mode_data, alternate, &mut unknown).filter(|_| !unknown);
+ if inks.is_none() {
+ cx.warn("duotone inks are not interpreted (shown as grayscale)");
+ }
+ let inks = inks.unwrap_or_else(|| vec![photocraft_doc::DuotoneInk::new("Black", [0.0; 3])]);
- doc.duotone = Some(photocraft_doc::Duotone { inks, psd_raw: Some(file.color_mode_data.clone()) });
++ doc.duotone = Some(photocraft_doc::Duotone { inks, psd_raw: Some(file.color_mode_data.as_slice().into()) });
} else if !file.color_mode_data.is_empty() {
cx.warn("color mode data is not preserved");
}
diff --cc crates/io/tests/it/adjust_warnings.rs
index c5bba0182,000000000..e120b0db4
mode 100644,000000..100644
--- a/crates/io/tests/it/adjust_warnings.rs
+++ b/crates/io/tests/it/adjust_warnings.rs
@@@ -1,111 -1,0 +1,111 @@@
+//! 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::*;
+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);
+ 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] };
++ let profile = Adjustment::Unsupported { psd_key: "clrL".into(), raw: vec![0, 2, 0, 0].into() };
+ 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());
++ let (_, warnings) = reopen(Adjustment::Unsupported { psd_key: "levl".into(), raw: vec![0, 9].into() }, "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:?}");
+ }
+}
+
+/// 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);
++ let (doc, warnings) = reopen(Adjustment::Unsupported { psd_key: "clrL".into(), raw: raw.as_slice().into() }, "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:?}");
+}
diff --cc crates/io/tests/it/psd_unknown_adjustment.rs
index 5a7981c5c,000000000..8b1f0cbdd
mode 100644,000000..100644
--- a/crates/io/tests/it/psd_unknown_adjustment.rs
+++ b/crates/io/tests/it/psd_unknown_adjustment.rs
@@@ -1,106 -1,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),
++ 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}");
+ }
+}
diff --cc crates/ui-egui/src/unsupported_marker_tests.rs
index dc748381e,000000000..262cf6251
mode 100644,000000..100644
--- a/crates/ui-egui/src/unsupported_marker_tests.rs
+++ b/crates/ui-egui/src/unsupported_marker_tests.rs
@@@ -1,42 -1,0 +1,42 @@@
+//! #6541: the Layers panel marks an adjustment layer PhotoCraft keeps as imported but cannot
+//! render, so a picture that differs from Photoshop's has a visible reason.
+
+use egui::vec2;
+use egui_kittest::Harness;
+use photocraft_doc::{Adjustment, Layer, LayerContent, LayerId};
+use serde_json::json;
+
+use crate::PhotocraftApp;
+use crate::layer_row_ui::{Indicator, RowRects, recorded};
+
+fn row(h: &Harness<'_, PhotocraftApp>, id: LayerId) -> RowRects {
+ recorded(&h.ctx).into_iter().find(|r| r.layer == id.0).unwrap()
+}
+
+#[test]
+fn an_unsupported_adjustment_row_carries_a_warning_marker() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
+ let plain = LayerId(s.execute("layer.new.layer", json!({"name": "plain"})).unwrap()["layer"].as_u64().unwrap());
- let mystery = Layer::new("Mystery", LayerContent::Adjustment(Adjustment::Unsupported { psd_key: "xyzw".into(), raw: vec![1, 2, 3] }));
++ let mystery = Layer::new("Mystery", LayerContent::Adjustment(Adjustment::Unsupported { psd_key: "xyzw".into(), raw: vec![1, 2, 3].into() }));
+ let mystery_id = mystery.id;
+ s.edit("unsupported fixture", |doc, active| {
+ doc.layers.push(mystery);
+ *active = Some(mystery_id);
+ Ok(())
+ })
+ .unwrap();
+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ PhotocraftApp::new(s, crate::Services::default())
+ });
+ h.run_steps(8);
+ let marked = row(&h, mystery_id);
+ assert!(marked.indicators.iter().any(|(k, _)| *k == Indicator::Unsupported), "{:?}", marked.indicators);
+ assert!(!row(&h, plain).indicators.iter().any(|(k, _)| *k == Indicator::Unsupported));
+ // The marker takes room from the name, never overlaps it.
+ let (_, marker) = marked.indicators.iter().find(|(k, _)| *k == Indicator::Unsupported).copied().unwrap();
+ if let Some(name) = marked.name {
+ assert!(name.right() <= marker.left(), "name {name:?} runs under the marker {marker:?}");
+ }
+}
diff --cc docs/architecture.md
index f4b80270b,2b1220bd3..1efd47ac5
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@@ -1,6 -1,6 +1,6 @@@
# PhotoCraft architecture
- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (accurate GPU matrix/TRC display conversion; original design plan retained) · **Target:** Adobe Photoshop 2026
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (large payloads in the document model are `Arc`-shared, #4535; earlier: workspace size and test counts recounted; current-state summary added; the design plan below is kept, with its deviations listed) · **Target:** Adobe Photoshop 2026
++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (accurate GPU matrix/TRC display conversion; large payloads in the document model are `Arc`-shared, #4535; original design plan retained) · **Target:** Adobe Photoshop 2026
## Current state (2026-10-10)
@@@ -587,8 -589,7 +587,9 @@@ Each phase ends with a demoable build a
| Date | Change | Summary |
|---|---|---|
+| 2026-10-21 | minor | Removed references to the deleted `rust-framework-options.md`; dropped the UI toolkit and plug-in items from Open decisions, both recorded as decided |
+| 2026-10-20 | minor | GPU display matrix/shaper path preserves near-black ICC values; complex transforms retain the 3D LUT fallback (#7958) |
+ | 2026-10-14 | minor | Principle 5: every large payload in the document model is `Arc`-shared, so snapshots never copy one (#4535) |
| 2026-10-13 | minor | Workspace size and `#[test]` counts recounted (393k → 539k lines, 5,460 → 8,040 tests); other current-state figures unchanged |
| 2026-10-10 | minor | Current-state summary and deviations from the plan; status line; broken link to `photoshop-parity.md` repointed to `target-app-parity.md` |
| 2026-09-30 | major | Design plan v1 |