PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Expose shared Smart Object instances in inspection and replacement results (#4832)
jonathanwxh-cell8d2806f66c4f
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rsindex 22c3d3a96..6068503ae 100644--- a/crates/engine/src/inspect.rs+++ b/crates/engine/src/inspect.rs@@ -1,6 +1,8 @@//! JSON views of engine state for automation, tests and debugging.-use photocraft_doc::{Layer, LayerContent, SmartSource};+use std::collections::HashMap;++use photocraft_doc::{Layer, LayerContent, SmartContentsId, SmartSource};use serde_json::{Value, json};use crate::{DocState, Session};@@ -25,6 +27,7 @@ pub fn session(s: &Session) -> Value {pub fn document(d: &DocState) -> Value {let doc = &d.doc;let selected = d.selected_layers();+ let instances = smart_instances(&doc.layers);json!({"name": doc.name,"path": &d.path,@@ -38,7 +41,7 @@ pub fn document(d: &DocState) -> Value {"isolatedLayers": d.isolated_layers.iter().map(|l| l.0).collect::<Vec<_>>(),"hasSelection": doc.selection.is_some(),"selectionBounds": doc.selection.as_ref().map(|s| { let r = s.content_bounds(); [r.x0, r.y0, r.width() as i32, r.height() as i32] }),- "layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected, Some(&doc.metadata))).collect::<Vec<_>>(),+ "layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected, &instances, Some(&doc.metadata))).collect::<Vec<_>>(),"history": d.history.entries(),"snapshots": d.snapshots.iter().map(|snap| json!({"id": snap.id, "name": snap.name})).collect::<Vec<_>>(),"canUndo": d.history.can_undo(),@@ -61,14 +64,27 @@ pub fn document(d: &DocState) -> Value {})}-/// Layer tree top-to-bottom (display order).+/// Layer tree top-to-bottom (display order). Smart object instances are counted within `l`.pub fn layer(l: &Layer) -> Value {- layer_sel(l, &[], None)+ layer_sel(l, &[], &smart_instances(std::slice::from_ref(l)), None)+}++/// How many smart objects in `layers`, groups included, share each contents identity.+fn smart_instances(layers: &[Layer]) -> HashMap<SmartContentsId, usize> {+ let mut counts = HashMap::new();+ let mut pending: Vec<&Layer> = layers.iter().collect();+ while let Some(l) = pending.pop() {+ match &l.content {+ LayerContent::Smart(sm) => *counts.entry(sm.contents_id).or_default() += 1,+ LayerContent::Group(g) => pending.extend(&g.children),+ _ => {}+ }+ }+ counts}-/// [`layer`] with a `selected` flag on every node (Layers panel multi-selection); with the-/// document's `meta`, a smart object whose file is embedded in the PSD says so.-fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], meta: Option<&photocraft_doc::Metadata>) -> Value {+/// [`layer`] with a `selected` flag on every node (Layers panel multi-selection).+fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], instances: &HashMap<SmartContentsId, usize>, meta: Option<&photocraft_doc::Metadata>) -> Value {let bounds = l.surface().map(|s| {let r = s.content_bounds();[r.x0, r.y0, r.width() as i32, r.height() as i32]@@ -92,7 +108,7 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], meta: Option<&phot});match &l.content {LayerContent::Group(g) => {- v["children"] = Value::Array(g.children.iter().rev().map(|c| layer_sel(c, selected, meta)).collect());+ v["children"] = Value::Array(g.children.iter().rev().map(|c| layer_sel(c, selected, instances, meta)).collect());v["expanded"] = json!(g.expanded);if let Some(a) = &g.artboard {v["artboard"] = json!({"rect": [a.rect.x0, a.rect.y0, a.rect.width(), a.rect.height()], "background": a.background.name(), "preset": a.preset});@@ -122,6 +138,9 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], meta: Option<&photNone => json!({"kind": "linked", "path": path}),},};+ // Copies of the same contents change together (Edit and Replace Contents), and+ // `smartSource` can't tell them from independent copies of one file (#4075).+ v["smartContents"] = json!({"id": sm.contents_id.0, "instances": instances.get(&sm.contents_id).copied().unwrap_or(1)});}LayerContent::Text(t) => {v["text"] = json!({"text": t.text, "font": t.font_family, "sizePt": t.size_pt});diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rsindex 295b845df..649a15441 100644--- a/crates/engine/src/smart_cmds.rs+++ b/crates/engine/src/smart_cmds.rs@@ -827,21 +827,24 @@ fn set_source(s: &mut Session, p: &Value, label: &str, keep_psd: bool, make: imp// Keep the shared-instance transaction out of the per-command source-builder instantiations.fn set_shared_source(s: &mut Session, id: LayerId, label: &str, keep_psd: bool, new: SmartSource) -> Result<Value> {- let (parent, contents_id) = s.edit(label, |doc, _| {+ let (parent, contents_id, changed) = s.edit(label, |doc, _| {let contents_id = smart(doc, id)?.contents_id;- for instance in instances(doc, contents_id) {+ let changed = instances(doc, contents_id);+ for &instance in &changed {smart_mut(doc, instance)?.source = new.clone();if !keep_psd {detach_psd(doc.layer_mut(instance).ok_or(EngineError::NoLayer(instance))?);}refresh_or_fail(doc, instance)?;}- Ok((doc.id, contents_id))+ Ok((doc.id, contents_id, changed))})?;// An old editor must not overwrite newly replaced/relinked contents on close. Keep its// document open, but the next Edit Contents opens the replacement source.s.smart_links.retain(|l| l.parent != parent || l.contents_id != contents_id);- Ok(json!({"layer": id.0}))+ // Every instance changed, not only `layer`: list them, so a caller doesn't repeat the+ // command once per copy (#4075).+ Ok(json!({"layer": id.0, "instances": changed.iter().map(|l| l.0).collect::<Vec<_>>()}))}fn replace_contents(s: &mut Session, p: &Value) -> Result<Value> {diff --git a/crates/engine/tests/smart_duplicates.rs b/crates/engine/tests/smart_duplicates.rsindex 12f5ec548..554fd23f0 100644--- a/crates/engine/tests/smart_duplicates.rs+++ b/crates/engine/tests/smart_duplicates.rs@@ -4,7 +4,7 @@ use photocraft_doc::{Layer, LayerContent, LayerId, SmartObject};use photocraft_engine::Session;use photocraft_engine::smart_cmds::{decode_source, source_bytes};use photocraft_geom::Rect;-use serde_json::json;+use serde_json::{Value, json};fn session(depth: u64) -> (Session, u64, u64) {let mut s = Session::new();@@ -195,3 +195,104 @@ fn replacing_shared_contents_does_not_reuse_or_commit_a_stale_editor() {s.execute("layer.smartObjects.editContents", json!({"layer": original})).unwrap();assert_eq!(photocraft_compose::flatten(&s.active().unwrap().doc).px[0], [0.0, 1.0, 0.0, 1.0]);}++/// A `.pcraft` file whose contents are one solid colour, for Replace Contents.+fn contents_file(rgba: [f32; 4], tag: &str) -> std::path::PathBuf {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 6})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ paint(&mut s, rgba);+ let path = std::env::temp_dir().join(format!("photocraft-{tag}-{}.pcraft", std::process::id()));+ std::fs::write(&path, photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap()).unwrap();+ path+}++/// The node named `name` in `document.inspect`'s layer tree, searched through groups.+fn inspected<'a>(layers: &'a Value, name: &str) -> Option<&'a Value> {+ layers.as_array()?.iter().find_map(|l| if l["name"] == name { Some(l) } else { inspected(&l["children"], name) })+}++/// Placed layers sharing a source (a PSD's copies of one smart object) share their contents, so+/// one Replace Contents updates every copy. Nothing showed it: `linkGroup` is Link Layers, which+/// stays unset (#4075). Inspect gives each smart object its contents identity and instance count,+/// and Replace Contents lists every layer it changed.+#[test]+fn inspect_and_replace_contents_report_shared_instances() {+ let (mut s, original, duplicate) = session(8);+ let independent = s.execute("layer.smartObjects.newSmartObjectViaCopy", json!({"layer": original})).unwrap()["layer"].as_u64().unwrap();+ s.edit("name and group", |doc, _| {+ for (id, name) in [(original, "original"), (duplicate, "duplicate"), (independent, "independent")] {+ doc.layer_mut(LayerId(id)).unwrap().name = name.into();+ }+ // An instance inside a group counts too.+ let copy = doc.remove(LayerId(duplicate)).unwrap();+ doc.layers.push(Layer::group("Copies", vec![copy]));+ Ok(())+ })+ .unwrap();+ let out = photocraft_io::export(&s.active().unwrap().doc, "psd", &Default::default()).unwrap();+ let mut s = Session::new();+ s.add_document(photocraft_io::import("copies.psd", &out.bytes).unwrap().document, None);++ let tree = s.execute("document.inspect", json!({})).unwrap();+ let [o, d, i] = ["original", "duplicate", "independent"].map(|name| inspected(&tree["layers"], name).unwrap().clone());+ assert_eq!(o["smartContents"]["id"], d["smartContents"]["id"]);+ assert_ne!(o["smartContents"]["id"], i["smartContents"]["id"]);+ assert_eq!([&o, &d, &i].map(|l| l["smartContents"]["instances"].as_u64()), [Some(2), Some(2), Some(1)]);+ assert!([&o, &d, &i].iter().all(|l| l["linkGroup"].is_null()), "shared contents don't link the layers");++ let [o, d, i] = [&o, &d, &i].map(|l| l["id"].as_u64().unwrap());+ let path = contents_file([0.0, 1.0, 0.0, 1.0], "replace-instances");+ let replaced = s.execute("layer.smartObjects.replaceContents", json!({"layer": d, "path": path}));+ std::fs::remove_file(path).unwrap();+ let mut changed: Vec<u64> = replaced.unwrap()["instances"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();+ changed.sort_unstable();+ assert_eq!(changed, if o < d { [o, d] } else { [d, o] });+ assert_eq!([o, d, i].map(|id| contents_pixel(&s, id)), [[0.0, 1.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]]);+ for (id, expected) in [(o, [0.0, 1.0, 0.0, 1.0]), (d, [0.0, 1.0, 0.0, 1.0]), (i, [0.0, 0.0, 1.0, 1.0])] {+ assert_eq!(smart(&s, id).cache.as_ref().unwrap().rgba(4, 3), expected, "instance {id} must display its current contents");+ }+}++/// The same with the placed layer Photoshop wrote, twice: Photoshop's copies of a smart object+/// each carry a `SoLd` naming the one embedded file (`Idnt`), so they import as one contents.+#[cfg(feature = "corpus")]+#[test]+fn photoshop_placed_copies_import_as_shared_instances() {+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/photoshop/smart-filters/sf-none-plain.psd");+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e} (run `cargo xtask corpus --all`)", path.display()));+ let mut file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap();+ let placed = file.layers().iter().find(|r| r.block(b"SoLd").is_some()).expect("a placed layer").clone();+ file.layers_mut().push(placed);+ let mut s = Session::new();+ s.add_document(photocraft_io::psd_to_document(&file).0, None);++ let tree = s.execute("document.inspect", json!({})).unwrap();+ let copies: Vec<&Value> = tree["layers"].as_array().unwrap().iter().filter(|l| l["kind"] == "Smart Object").collect();+ assert_eq!(copies.len(), 2);+ assert_eq!(copies[0]["smartContents"], copies[1]["smartContents"]);+ assert_eq!(copies[0]["smartContents"]["instances"], 2);+ for copy in &copies {+ assert_eq!(copy["smartSource"]["kind"], "embedded");+ assert!(copy["smartSource"]["uuid"].as_str().is_some());+ }+ let mut ids: Vec<u64> = copies.iter().map(|l| l["id"].as_u64().unwrap()).collect();+ let path = contents_file([0.0, 1.0, 0.0, 1.0], "photoshop-copies");+ let replaced = s.execute("layer.smartObjects.replaceContents", json!({"layer": ids[0], "path": path}));+ std::fs::remove_file(path).unwrap();+ let mut changed: Vec<u64> = replaced.unwrap()["instances"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();+ changed.sort_unstable();+ ids.sort_unstable();+ assert_eq!(changed, ids);+ for id in ids {+ assert_eq!(contents_pixel(&s, id), [0.0, 1.0, 0.0, 1.0]);+ let cache = smart(&s, id).cache.as_ref().unwrap();+ let bounds = cache.content_bounds();+ assert!(!bounds.is_empty(), "instance {id} must have rendered pixels");+ assert_eq!(+ cache.rgba(bounds.x0 + bounds.width() as i32 / 2, bounds.y0 + bounds.height() as i32 / 2),+ [0.0, 1.0, 0.0, 1.0],+ "instance {id} must refresh its imported cache"+ );+ }+}diff --git a/docs/development.md b/docs/development.mdindex f685f653c..8bfc53df8 100644--- a/docs/development.md+++ b/docs/development.md@@ -243,7 +243,9 @@ claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp \`doc_inspect` (and the engine command `document.inspect`) reports the layer tree with kinds,bounds, masks, selection, effects (`effects.items[].kind`), smart filters (`smartFilters[]`), smartobject sources (`smartSource`: `embedded` with its file name, or `linked` with a file path or, for a-PSD placed layer, the `Idnt` uuid its duplicates share), type+PSD placed layer, the `Idnt` uuid its duplicates share), shared contents (`smartContents`: an `id`+every copy of the same contents has, and the number of `instances`; Replace Contents changes them+all and lists them in its result), typetext, adjustment settings, channels and history, so agents can verify what they did without ascreenshot. `crates/automation/tests/agent_tasks.rs` is the reference: ten realistic edit tasks(title card, colour grade, undo/redo, editable smart blur, masks, saved selections, align,