PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(doc): variable definitions follow layer id remapping on copy and load (#5023)
mroxso57d488032ce5
diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rsindex 697794f46..3e870aa68 100644--- a/crates/engine/src/image_cmds.rs+++ b/crates/engine/src/image_cmds.rs@@ -71,11 +71,12 @@ pub(crate) fn for_each_layer(layers: &mut [Layer], f: &mut dyn FnMut(&mut Layer)}}-/// Assign new layer ids to a copied document and update every saved layer-comp reference.+/// Assign new layer ids to a copied document and update every saved layer reference.///-/// A document copy needs fresh identities, but its comps must still target the copied-/// layers. Deliberately leave references to already-deleted layers untouched so their-/// missing-layer warnings remain meaningful. The same applies to Last Document State.+/// A document copy needs fresh identities, but its comps and variable definitions must+/// still target the copied layers. Deliberately leave references to already-deleted+/// layers untouched so their missing-layer warnings remain meaningful. The same applies+/// to Last Document State.pub(crate) fn reidentify_copied_layers(doc: &mut Document) {let mut ids = std::collections::HashMap::new();for_each_layer(&mut doc.layers, &mut |layer| {@@ -97,6 +98,11 @@ pub(crate) fn reidentify_copied_layers(doc: &mut Document) {if let Some(last) = &mut doc.last_document_state {remap(last);}+ for def in &mut doc.variables.defs {+ if let Some(&new_id) = ids.get(&def.layer) {+ def.layer = new_id;+ }+ }}/// Scale every size and distance of a style by `k` (Image Size's Scale Styles, Layer Style ›@@ -735,6 +741,9 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {doc.layer_comps.clear();doc.last_applied_comp = None;doc.last_document_state = None;+ // Likewise, variables drove template layers that no longer exist: drop the whole+ // binding set (defs, data sets and the active index) on the flattened copy.+ doc.variables = photocraft_doc::Variables::default();}reidentify_copied_layers(&mut doc);let name = doc.name.clone();diff --git a/crates/engine/tests/duplicate_variables.rs b/crates/engine/tests/duplicate_variables.rsnew file mode 100644index 000000000..48d197b51--- /dev/null+++ b/crates/engine/tests/duplicate_variables.rs@@ -0,0 +1,146 @@+//! Variable definitions must continue targeting their layers after a copied document gets+//! fresh ids (#4969), and a merged-only copy must not keep bindings to discarded layers.++use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size, TextLayer};+use photocraft_engine::Session;+use serde_json::json;++fn scene() -> (Session, LayerId, LayerId, LayerId) {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();+ let ids = s+ .edit("setup", |doc, _| {+ let fmt = doc.pixel_format();+ let mut photo = Layer::raster("photo", fmt);+ photo.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 64, 48), &photocraft_raster::from_rgba(&fmt, [0.5, 0.5, 0.5, 1.0]));+ let badge = Layer::raster("badge", fmt);+ let title = Layer::new("title", LayerContent::Text(TextLayer { text: "Old".into(), ..Default::default() }));+ let (p, b, t) = (photo.id, badge.id, title.id);+ doc.layers.push(photo);+ doc.layers.push(badge);+ doc.layers.push(title);+ Ok((p, b, t))+ })+ .unwrap();+ (s, ids.0, ids.1, ids.2)+}++fn red_png(dir: &str) -> String {+ let doc = Document::with_background(+ "red",+ Size::new(4, 4),+ photocraft_doc::ColorMode::Rgb,+ photocraft_doc::SampleType::U8,+ photocraft_doc::Color::rgb(1.0, 0.0, 0.0),+ );+ let bytes = photocraft_io::export(&doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes;+ let path = format!("{dir}/replacement.png");+ std::fs::write(&path, bytes).unwrap();+ path+}++fn copied_layer(s: &Session, name: &str) -> LayerId {+ s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id+}++fn define_all(s: &mut Session, photo: LayerId, badge: LayerId, title: LayerId, png: &str) {+ s.execute(+ "image.variables.define",+ json!({"defs": [+ {"name": "showBadge", "layer": badge.0, "type": "visibility"},+ {"name": "headline", "layer": title.0, "type": "textReplacement"},+ {"name": "photo", "layer": photo.0, "type": "pixelReplacement", "method": "conform"},+ ]}),+ )+ .unwrap();+ s.execute(+ "image.variables.dataSets",+ json!({"dataSets": [+ {"name": "A", "values": [+ {"variable": "showBadge", "kind": "visibility", "value": false},+ {"variable": "headline", "kind": "text", "value": "Hello"},+ {"variable": "photo", "kind": "pixels", "value": png},+ ]},+ ]}),+ )+ .unwrap();+}++#[test]+fn duplicated_documents_keep_variables_targeting_the_copied_layers() {+ let dir = std::env::temp_dir().join(format!("pc-dup-vars-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let png = red_png(&dir.to_string_lossy());++ for command in ["image.duplicate", "history.newDocument"] {+ let (mut s, photo, badge, title) = scene();+ define_all(&mut s, photo, badge, title, &png);+ s.execute(command, json!({})).unwrap();++ let doc = &s.active().unwrap().doc;+ let new_photo = copied_layer(&s, "photo");+ let new_badge = copied_layer(&s, "badge");+ let new_title = copied_layer(&s, "title");+ assert_ne!(new_photo, photo, "{command}: layers must get new identities");+ let targets: Vec<LayerId> = doc.variables.defs.iter().map(|d| d.layer).collect();+ assert_eq!(targets, vec![new_badge, new_title, new_photo], "{command}: variable defs follow their layers");++ let r = s.execute("image.applyDataSet", json!({"name": "A"})).unwrap();+ assert_eq!(r["applied"], "A");+ let doc = &s.active().unwrap().doc;+ assert!(!doc.layer(new_badge).unwrap().visible, "{command}: visibility drives the copy");+ match &doc.layer(new_title).unwrap().content {+ LayerContent::Text(t) => assert_eq!(t.text, "Hello", "{command}: text drives the copy"),+ _ => panic!("not a text layer"),+ }+ let px = doc.layer(new_photo).unwrap().surface().unwrap().pixel(0, 0);+ assert!(px[0] > 0.9 && px[1] < 0.1, "{command}: pixel replacement drives the copy: {px:?}");++ // The source document still targets its own layers and is untouched.+ s.set_active(0);+ let src = &s.active().unwrap().doc;+ let src_targets: Vec<LayerId> = src.variables.defs.iter().map(|d| d.layer).collect();+ assert_eq!(src_targets, vec![badge, title, photo], "{command}: source defs untouched");+ assert!(src.layer(badge).unwrap().visible);+ assert!(src.layer(photo).unwrap().surface().unwrap().pixel(0, 0)[0] < 0.9);+ }+}++#[test]+fn dangling_variable_targets_stay_dangling_after_duplication() {+ let (mut s, photo, badge, title) = scene();+ define_all(&mut s, photo, badge, title, "unused.png");+ // A def may already refer to a deleted layer before duplication.+ let missing = LayerId(u64::MAX);+ s.edit("Break one def", |doc, _| {+ doc.variables.defs.iter_mut().find(|d| d.name == "showBadge").unwrap().layer = missing;+ Ok(())+ })+ .unwrap();+ s.execute("image.duplicate", json!({})).unwrap();++ let doc = &s.active().unwrap().doc;+ let def = doc.variables.defs.iter().find(|d| d.name == "showBadge").unwrap();+ assert_eq!(def.layer, missing, "a deleted target must not be rewritten to an unrelated new id");+ let photo_def = doc.variables.defs.iter().find(|d| d.name == "photo").unwrap();+ assert_eq!(photo_def.layer, copied_layer(&s, "photo"), "live targets still remap");+}++#[test]+fn merged_only_duplicate_does_not_carry_variables_for_removed_layers() {+ let dir = std::env::temp_dir().join(format!("pc-dup-vars-merged-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let png = red_png(&dir.to_string_lossy());+ let (mut s, photo, badge, title) = scene();+ define_all(&mut s, photo, badge, title, &png);++ s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap();+ let d = &s.active().unwrap().doc;+ assert_eq!(d.layers.len(), 1, "merged-only copy is a single composite layer");+ assert!(d.variables.defs.is_empty(), "old variables cannot address discarded layers");+ assert!(d.variables.data_sets.is_empty());+ assert_eq!(d.variables.active, None);++ s.set_active(0);+ assert_eq!(s.active().unwrap().doc.variables.defs.len(), 3, "original variables are preserved");+}diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rsindex 51d6183ba..95d45fafb 100644--- a/crates/format/src/convert.rs+++ b/crates/format/src/convert.rs@@ -617,6 +617,15 @@ impl Loader<'_> {}}}+ // Variable targets follow their layers through id remapping; a dangling one keeps a+ // non-colliding placeholder so it stays a missing-layer skip rather than driving an+ // unrelated layer (#4969). With preserved ids the map is the identity and defs stay as saved.+ let mut variables = m.variables.clone();+ if !self.preserve_ids {+ for vd in &mut variables.defs {+ vd.layer = self.id_map.get(&vd.layer.0).copied().unwrap_or(LayerId(u64::MAX - vd.layer.0.min(u64::MAX / 2)));+ }+ }let id = if self.preserve_ids { DocId(m.id) } else { DocId::fresh() };Ok(Document {id,@@ -641,7 +650,7 @@ impl Loader<'_> {patterns,color_table: m.color_table.clone(),duotone: m.duotone.clone(),- variables: m.variables.clone(),+ variables,timeline: m.timeline.clone(),file_encoding: m.file_encoding,layer_comps,diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rsindex 8b74a00c4..f78e93947 100644--- a/crates/format/tests/roundtrip.rs+++ b/crates/format/tests/roundtrip.rs@@ -5,7 +5,7 @@ use common::*;use photocraft_color::{ColorMode, SampleType};use photocraft_doc::text::{CharStyle, ParagraphStyle, TextRun};use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef};-use photocraft_doc::{Document, Layer, LayerContent, LayerId, Slice, TextLayer};+use photocraft_doc::{Document, Layer, LayerContent, LayerId, Slice, TextLayer, VarKind, VariableDef};use photocraft_format::*;use photocraft_raster::Rgba8Image;@@ -729,3 +729,25 @@ fn a_non_finite_float_is_refused_at_save_rather_than_breaking_every_later_load()let back = load_from_bytes(&save_to_bytes(&doc, &SaveOptions::default()).unwrap()).unwrap();assert_eq!(back, doc);}++#[test]+fn variables_follow_layer_id_remapping() {+ let mut doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let id_of = |d: &Document, name: &str| d.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id;+ doc.variables.defs = vec![+ VariableDef { name: "head".into(), layer: id_of(&doc, "Paint"), kind: VarKind::TextReplacement },+ VariableDef { name: "badge".into(), layer: id_of(&doc, "Inner"), kind: VarKind::Visibility },+ VariableDef { name: "gone".into(), layer: LayerId(u64::MAX), kind: VarKind::Visibility },+ ];+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();+ // Preserved ids keep every definition exactly as saved, dangling ones included.+ assert_eq!(load_from_bytes(&bytes).unwrap(), doc);+ // Remapped ids carry the definitions to the copied layers; a dangling target stays+ // dangling and must not collide with a live layer (#4969).+ let back = load_from_bytes_with(&bytes, &LoadOptions { preserve_ids: false, ..Default::default() }).unwrap();+ let defs = &back.variables.defs;+ assert_eq!(defs.iter().find(|d| d.name == "head").unwrap().layer, id_of(&back, "Paint"));+ assert_eq!(defs.iter().find(|d| d.name == "badge").unwrap().layer, id_of(&back, "Inner"));+ let gone = defs.iter().find(|d| d.name == "gone").unwrap().layer;+ assert!(back.walk().into_iter().all(|(_, _, l)| l.id != gone), "dangling target must not address a live layer");+}