Skip to content

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

Keep duplicated Smart Objects linked to shared contents (#2222)

Harrison O'Connor-Hoover607a8542f541
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 93e0d3ae0..1cc8502f0 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -64,7 +64,17 @@ impl LayerId {
}
}
-/// Advance the process-wide id counter (shared by layer and document ids) past `max`, so ids
+/// Identity of the source contents shared by smart-object instances, independent of their bytes.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+pub struct SmartContentsId(pub u64);
+
+impl SmartContentsId {
+ pub fn fresh() -> Self {
+ SmartContentsId(next_id())
+ }
+}
+
+/// Advance the process-wide id counter (shared by layer, document and smart-contents ids) past `max`, so ids
/// loaded from a file never collide with ids minted later.
pub fn ensure_ids_above(max: u64) {
NEXT_ID.fetch_max(max.saturating_add(1), Ordering::Relaxed);
@@ -457,6 +467,8 @@ fn normalize_runs<S: Clone>(text: &str, runs: Vec<(usize, S)>, base: S) -> Vec<(
#[derive(Clone, Debug, PartialEq)]
pub struct SmartObject {
+ /// Ordinary layer duplicates share this identity; independent contents receive a fresh one.
+ pub contents_id: SmartContentsId,
/// Embedded source file bytes (PSD, PNG, …) or linked path.
pub source: SmartSource,
pub transform: Affine,
@@ -488,6 +500,7 @@ impl SmartObject {
/// A smart object with no filters and no PSD data.
pub fn new(source: SmartSource, transform: Affine, cache: Option<Surface>) -> Self {
Self {
+ contents_id: SmartContentsId::fresh(),
source,
transform,
smart_filters: Vec::new(),
diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs
index c34c9e561..8e8cb273d 100644
--- a/crates/engine/src/filters.rs
+++ b/crates/engine/src/filters.rs
@@ -669,6 +669,7 @@ mod tests {
let l = Layer::new(
"so",
LayerContent::Smart(SmartObject {
+ contents_id: photocraft_doc::SmartContentsId::fresh(),
source: SmartSource::Linked { path: String::new() },
transform: photocraft_geom::Affine::IDENTITY,
smart_filters: vec![],
diff --git a/crates/engine/src/layer_copy_cmds.rs b/crates/engine/src/layer_copy_cmds.rs
index 3996c029b..59f18ad76 100644
--- a/crates/engine/src/layer_copy_cmds.rs
+++ b/crates/engine/src/layer_copy_cmds.rs
@@ -8,8 +8,10 @@
//! document. Pixels are converted to the destination's colour profile (Color Settings' intent and
//! black point compensation) and bit depth, as Photoshop converts dragged layers.
+use std::collections::HashMap;
+
use photocraft_color::ColorMode;
-use photocraft_doc::{Document, LayerId};
+use photocraft_doc::{Document, LayerContent, LayerId, SmartContentsId};
use photocraft_geom::Rect;
use serde_json::{Value, json};
@@ -105,6 +107,17 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
}
copies.layers.push(l);
}
+ // Contents IDs belong to a document. Preserve sharing within this batch, without joining
+ // pre-existing objects in the destination (including another opening of the same file).
+ let mut contents = HashMap::new();
+ let smart_ids: Vec<_> = copies.walk().into_iter().filter_map(|(_, _, l)| matches!(l.content, LayerContent::Smart(_)).then_some(l.id)).collect();
+ for id in smart_ids {
+ if let Some(l) = copies.layer_mut(id)
+ && let LayerContent::Smart(sm) = &mut l.content
+ {
+ sm.contents_id = *contents.entry(sm.contents_id).or_insert_with(SmartContentsId::fresh);
+ }
+ }
if (copies.mode, &copies.icc_profile) != (ddoc.mode, &ddoc.icc_profile) {
let profile = crate::color_cmds::document_profile(&ddoc);
crate::color_cmds::convert_document(&mut copies, &profile, s.color.settings.intent(), s.color.settings.bpc)?;
diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs
index e4103b63c..3a0aa9323 100644
--- a/crates/engine/src/smart_cmds.rs
+++ b/crates/engine/src/smart_cmds.rs
@@ -25,7 +25,7 @@ use std::sync::{Arc, Mutex};
use photocraft_algo::resample::translate_surface;
use photocraft_algo::transform::Homography;
use photocraft_color::{BlendMode, PixelFormat};
-use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, LayerMask, Metadata, SmartObject, SmartSource};
+use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, LayerMask, Metadata, SmartContentsId, SmartObject, SmartSource};
use photocraft_geom::{Affine, Rect, Size};
use photocraft_raster::Surface;
use serde_json::{Value, json};
@@ -33,12 +33,13 @@ use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str, layer_param};
use crate::{EngineError, Result, Session};
-/// An open Edit Contents document and the smart object it updates when saved or closed.
+/// An open Edit Contents document and the shared contents it updates when saved or closed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SmartLink {
pub child: DocId,
pub parent: DocId,
pub layer: LayerId,
+ pub contents_id: SmartContentsId,
}
/// PSD placed-layer keys that describe the smart object's source; stale once we change it.
@@ -686,6 +687,7 @@ fn via_copy(s: &mut Session, p: &Value) -> Result<Value> {
copy.name = doc.copy_name(&src.name);
if let LayerContent::Smart(sm) = &mut copy.content {
// Independent contents: resolve to embedded bytes and drop the shared PSD uuid.
+ sm.contents_id = SmartContentsId::fresh();
if let Some((file_name, bytes)) = source_bytes(&doc.metadata, &sm.source) {
sm.source = SmartSource::Embedded { file_name, bytes };
}
@@ -703,18 +705,36 @@ fn path_param<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> {
p.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "pass `path`"))
}
-/// Swaps a smart object's source, keeping its transform and filters, and re-renders.
+/// Instances sharing contents in this document, including those inside groups.
+fn instances(doc: &Document, contents_id: SmartContentsId) -> Vec<LayerId> {
+ doc.walk().into_iter().filter_map(|(_, _, l)| matches!(&l.content, LayerContent::Smart(sm) if sm.contents_id == contents_id).then_some(l.id)).collect()
+}
+
+/// Swaps shared contents, keeping each instance's transform and filters, and re-renders.
fn set_source(s: &mut Session, p: &Value, label: &str, keep_psd: bool, make: impl FnOnce(&Metadata, &SmartSource) -> Result<SmartSource>) -> Result<Value> {
let id = layer_param(s, p)?;
- s.edit(label, |doc, _| {
- let new = make(&doc.metadata, &smart(doc, id)?.source)?;
- smart_mut(doc, id)?.source = new;
- if !keep_psd {
- detach_psd(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?);
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let new = make(&doc.metadata, &smart(doc, id)?.source)?;
+ set_shared_source(s, id, label, keep_psd, new)
+}
+
+// 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 contents_id = smart(doc, id)?.contents_id;
+ for instance in instances(doc, contents_id) {
+ 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)?;
}
- refresh_or_fail(doc, id)?;
- Ok(json!({"layer": id.0}))
- })
+ Ok((doc.id, contents_id))
+ })?;
+ // 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}))
}
fn replace_contents(s: &mut Session, p: &Value) -> Result<Value> {
@@ -738,8 +758,10 @@ fn edit_contents(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, p)?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let parent = st.doc.id;
+ let contents_id = smart(&st.doc, id)?.contents_id;
// Already open for editing: switch to that document rather than opening another copy.
- if let Some(index) = s.smart_links.iter().find(|l| l.parent == parent && l.layer == id).and_then(|l| s.documents().iter().position(|d| d.doc.id == l.child))
+ if let Some(index) =
+ s.smart_links.iter().find(|l| l.parent == parent && l.contents_id == contents_id).and_then(|l| s.documents().iter().position(|d| d.doc.id == l.child))
{
s.set_active(index);
return Ok(json!({"document": index, "parentLayer": id.0}));
@@ -755,11 +777,11 @@ fn edit_contents(s: &mut Session, p: &Value) -> Result<Value> {
// Admission may replace an ID already owned by another open document.
let child_id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id;
s.smart_links.retain(|l| l.child != child_id);
- s.smart_links.push(SmartLink { child: child_id, parent, layer: id });
+ s.smart_links.push(SmartLink { child: child_id, parent, layer: id, contents_id });
Ok(json!({"document": index, "parentLayer": id.0}))
}
-/// Writes an Edit Contents document back into its parent smart object (one undoable step in the
+/// Writes an Edit Contents document back into all its parent instances (one undoable step in the
/// parent) and marks it saved. Returns false if `index` isn't an Edit Contents document.
pub fn commit_child(s: &mut Session, index: usize) -> Result<bool> {
let Some(st) = s.docs.get(index) else { return Ok(false) };
@@ -770,14 +792,22 @@ pub fn commit_child(s: &mut Session, index: usize) -> Result<bool> {
let prev = s.active;
s.active = Some(parent);
let r = s.edit("Edit Contents", |doc, _| {
- let sm = smart_mut(doc, link.layer)?;
- let stem = match &sm.source {
- SmartSource::Embedded { file_name, .. } => file_name.rsplit_once('.').map_or(file_name.as_str(), |(a, _)| a).to_string(),
- SmartSource::Linked { .. } => child.name.rsplit_once('.').map_or(child.name.as_str(), |(a, _)| a).to_string(),
- };
- sm.source = SmartSource::Embedded { file_name: format!("{stem}.pcraft"), bytes: bytes.clone() };
- detach_psd(doc.layer_mut(link.layer).ok_or(EngineError::NoLayer(link.layer))?);
- refresh_or_fail(doc, link.layer)
+ let ids = instances(doc, link.contents_id);
+ if ids.is_empty() {
+ return Err(other("the smart object's instances were removed"));
+ }
+ for id in ids {
+ let sm = smart_mut(doc, id)?;
+ let name = match &sm.source {
+ SmartSource::Embedded { file_name, .. } => file_name.as_str(),
+ SmartSource::Linked { .. } => child.name.as_str(),
+ };
+ let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem);
+ sm.source = SmartSource::Embedded { file_name: format!("{stem}.pcraft"), bytes: bytes.clone() };
+ detach_psd(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?);
+ refresh_or_fail(doc, id)?;
+ }
+ Ok(())
});
s.active = prev;
r?;
diff --git a/crates/engine/tests/smart_duplicates.rs b/crates/engine/tests/smart_duplicates.rs
new file mode 100644
index 000000000..12f5ec548
--- /dev/null
+++ b/crates/engine/tests/smart_duplicates.rs
@@ -0,0 +1,197 @@
+//! Duplicated smart objects share their editable contents, but not instance settings (#2163).
+
+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;
+
+fn session(depth: u64) -> (Session, u64, u64) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 6, "depth": depth})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ paint(&mut s, [0.0, 0.0, 1.0, 1.0]);
+ let original = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap();
+ let duplicate = s.execute("layer.duplicate", json!({"layer": original})).unwrap()["layer"].as_u64().unwrap();
+ (s, original, duplicate)
+}
+
+fn paint(s: &mut Session, rgba: [f32; 4]) {
+ s.edit("paint", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 6), &rgba);
+ Ok(())
+ })
+ .unwrap();
+}
+
+fn smart(s: &Session, id: u64) -> &SmartObject {
+ let LayerContent::Smart(sm) = &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content else { panic!("smart object") };
+ sm
+}
+
+fn contents_pixel(s: &Session, id: u64) -> [f32; 4] {
+ let (name, bytes) = source_bytes(&s.active().unwrap().doc.metadata, &smart(s, id).source).unwrap();
+ photocraft_compose::flatten(&decode_source(&name, &bytes).unwrap()).px[0]
+}
+
+#[test]
+fn editing_original_updates_duplicate_contents() {
+ for depth in [8, 16, 32] {
+ let (mut s, original, duplicate) = session(depth);
+ // The sibling may be nested and have its own placement and smart filters.
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap();
+ s.execute("edit.transform", json!({"layer": duplicate, "matrix": [1, 0, 0, 1, 2, 1]})).unwrap();
+ let instance = smart(&s, duplicate).clone();
+ s.edit("group", |doc, _| {
+ let copy = doc.remove(LayerId(duplicate)).unwrap();
+ doc.layers.push(Layer::group("Copies", vec![copy]));
+ Ok(())
+ })
+ .unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let child = s.execute("layer.smartObjects.editContents", json!({"layer": original})).unwrap()["document"].as_u64().unwrap();
+ paint(&mut s, [1.0, 0.0, 0.0, 1.0]);
+ s.execute("layer.smartObjects.saveContents", json!({})).unwrap();
+ assert_eq!(s.active_index(), Some(child as usize));
+ assert!(!s.active().unwrap().is_dirty());
+ s.set_active(0);
+ for id in [original, duplicate] {
+ assert_eq!(contents_pixel(&s, id), [1.0, 0.0, 0.0, 1.0]);
+ let cache = smart(&s, id).cache.as_ref().unwrap();
+ let alpha = if id == duplicate { instance.cache.as_ref().unwrap().rgba(4, 3)[3] } else { 1.0 };
+ assert_eq!(cache.rgba(4, 3), [1.0, 0.0, 0.0, alpha], "re-rendered contents retain the instance's blurred edge");
+ }
+ assert_eq!(smart(&s, duplicate).transform, instance.transform);
+ assert_eq!(smart(&s, duplicate).smart_filters, instance.smart_filters);
+ assert!(smart(&s, original).smart_filters.is_empty());
+ let after = s.active().unwrap().doc.clone();
+ assert!(s.undo());
+ assert_eq!(s.active().unwrap().doc, before, "all instances revert in one undo step");
+ assert!(s.redo());
+ assert_eq!(s.active().unwrap().doc, after);
+ // Entering from the duplicate reuses the same editor, and close commits back to both.
+ let open = s.documents().len();
+ assert_eq!(s.execute("layer.smartObjects.editContents", json!({"layer": duplicate})).unwrap()["document"], child);
+ assert_eq!(s.documents().len(), open);
+ paint(&mut s, [0.0, 1.0, 0.0, 1.0]);
+ s.execute("file.close", json!({})).unwrap();
+ assert_eq!(contents_pixel(&s, original), [0.0, 1.0, 0.0, 1.0]);
+ assert_eq!(contents_pixel(&s, duplicate), [0.0, 1.0, 0.0, 1.0]);
+ }
+}
+
+#[test]
+fn surviving_duplicate_receives_edits_after_originating_layer_is_deleted() {
+ let (mut s, original, duplicate) = session(16);
+ let child = s.execute("layer.smartObjects.editContents", json!({"layer": original})).unwrap()["document"].as_u64().unwrap() as usize;
+ s.set_active(0);
+ s.execute("layer.delete", json!({"layer": original})).unwrap();
+ s.set_active(child);
+ paint(&mut s, [1.0, 0.0, 0.0, 1.0]);
+ s.execute("layer.smartObjects.saveContents", json!({})).unwrap();
+ s.set_active(0);
+ assert_eq!(contents_pixel(&s, duplicate), [1.0, 0.0, 0.0, 1.0]);
+}
+
+#[test]
+fn shared_and_independent_contents_survive_native_psd_and_psb() {
+ for format in ["pcraft", "psd", "psb"] {
+ let (mut s, original, duplicate) = session(16);
+ let independent = s.execute("layer.smartObjects.newSmartObjectViaCopy", json!({"layer": original})).unwrap()["layer"].as_u64().unwrap();
+ s.edit("name", |doc, _| {
+ for (id, name) in [(original, "original"), (duplicate, "duplicate"), (independent, "independent")] {
+ doc.layer_mut(LayerId(id)).unwrap().name = name.into();
+ }
+ Ok(())
+ })
+ .unwrap();
+ // Initially byte-identical independent copies must not be merged by blob deduplication.
+ let doc = &s.active().unwrap().doc;
+ let back = if format == "pcraft" {
+ let bytes = photocraft_format::save_to_bytes(doc, &Default::default()).unwrap();
+ photocraft_format::load_from_bytes(&bytes).unwrap()
+ } else {
+ let out = photocraft_io::export(doc, format, &Default::default()).unwrap();
+ assert!(out.warnings.is_empty(), "{format}: {:?}", out.warnings);
+ photocraft_io::import(&format!("duplicates.{format}"), &out.bytes).unwrap().document
+ };
+ let named = |name: &str| back.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id.0;
+ let (original, duplicate, independent) = (named("original"), named("duplicate"), named("independent"));
+ let mut s = Session::new();
+ s.add_document(back, None);
+ s.execute("layer.smartObjects.editContents", json!({"layer": duplicate})).unwrap();
+ paint(&mut s, [1.0, 0.0, 0.0, 1.0]);
+ s.execute("layer.smartObjects.saveContents", json!({})).unwrap();
+ s.set_active(0);
+ assert_eq!(contents_pixel(&s, original), [1.0, 0.0, 0.0, 1.0], "{format}");
+ assert_eq!(contents_pixel(&s, duplicate), [1.0, 0.0, 0.0, 1.0], "{format}");
+ assert_eq!(contents_pixel(&s, independent), [0.0, 0.0, 1.0, 1.0], "{format}");
+ s.execute("layer.smartObjects.editContents", json!({"layer": independent})).unwrap();
+ assert_eq!(s.documents().len(), 3, "independent contents need their own editor");
+ paint(&mut s, [0.0, 1.0, 0.0, 1.0]);
+ s.execute("layer.smartObjects.saveContents", json!({})).unwrap();
+ s.set_active(0);
+ assert_eq!(contents_pixel(&s, original), [1.0, 0.0, 0.0, 1.0]);
+ assert_eq!(contents_pixel(&s, independent), [0.0, 1.0, 0.0, 1.0]);
+ }
+}
+
+#[test]
+fn copying_a_batch_between_documents_preserves_only_its_internal_sharing() {
+ let (mut s, original, duplicate) = session(16);
+ let independent = s.execute("layer.smartObjects.newSmartObjectViaCopy", json!({"layer": original})).unwrap()["layer"].as_u64().unwrap();
+ let source_names = [original, duplicate, independent].map(|id| s.active().unwrap().doc.layer(LayerId(id)).unwrap().name.clone());
+ // Another opening of the same document has the same persisted contents IDs.
+ let target = (*s.active().unwrap().doc).clone();
+ s.add_document(target, None);
+ s.set_active(0);
+ let result = s.execute("layer.copyToDocument", json!({"document": 1, "layers": [original, duplicate, independent]})).unwrap();
+ // The command returns stacking order, which differs from the requested order after via-copy.
+ let copied = source_names.map(|name| {
+ result["layers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|id| id.as_u64().unwrap())
+ .find(|id| s.active().unwrap().doc.layer(LayerId(*id)).unwrap().name == name)
+ .unwrap()
+ });
+ assert_eq!(smart(&s, copied[0]).contents_id, smart(&s, copied[1]).contents_id);
+ assert_ne!(smart(&s, copied[0]).contents_id, smart(&s, copied[2]).contents_id);
+ assert_ne!(smart(&s, copied[0]).contents_id, smart(&s, original).contents_id);
+ s.execute("layer.smartObjects.editContents", json!({"layer": copied[0]})).unwrap();
+ paint(&mut s, [1.0, 0.0, 0.0, 1.0]);
+ s.execute("layer.smartObjects.saveContents", json!({})).unwrap();
+ s.set_active(1);
+ for id in &copied[..2] {
+ assert_eq!(contents_pixel(&s, *id), [1.0, 0.0, 0.0, 1.0]);
+ }
+ for id in [original, duplicate, independent, copied[2]] {
+ assert_eq!(contents_pixel(&s, id), [0.0, 0.0, 1.0, 1.0]);
+ }
+ s.set_active(0);
+ assert_eq!(contents_pixel(&s, original), [0.0, 0.0, 1.0, 1.0]);
+}
+
+#[test]
+fn replacing_shared_contents_does_not_reuse_or_commit_a_stale_editor() {
+ let (mut s, original, duplicate) = session(16);
+ let child = s.execute("layer.smartObjects.editContents", json!({"layer": original})).unwrap()["document"].as_u64().unwrap() as usize;
+ paint(&mut s, [0.0, 1.0, 0.0, 1.0]);
+ let path = std::env::temp_dir().join(format!("photocraft-shared-contents-{}-{original}.pcraft", std::process::id()));
+ std::fs::write(&path, photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap()).unwrap();
+ paint(&mut s, [1.0, 0.0, 0.0, 1.0]);
+ s.set_active(0);
+ let replaced = s.execute("layer.smartObjects.replaceContents", json!({"layer": duplicate, "path": path}));
+ std::fs::remove_file(path).unwrap();
+ replaced.unwrap();
+ for id in [original, duplicate] {
+ assert_eq!(contents_pixel(&s, id), [0.0, 1.0, 0.0, 1.0]);
+ }
+ s.set_active(child);
+ assert!(!s.is_enabled("layer.smartObjects.saveContents"));
+ s.execute("file.close", json!({})).unwrap();
+ assert_eq!(contents_pixel(&s, original), [0.0, 1.0, 0.0, 1.0]);
+ 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]);
+}
diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs
index e0233df18..608b2bf7c 100644
--- a/crates/format/src/convert.rs
+++ b/crates/format/src/convert.rs
@@ -6,7 +6,7 @@ use std::sync::Arc;
use photocraft_color::{PixelFormat, SampleType};
use photocraft_doc::{
AlphaChannel, CompAppearance, CompLayerState, DocId, Document, Effects, FillCache, Group, Layer, LayerComp, LayerContent, LayerId, LayerMask, Metadata,
- NamedPath, Pattern, ShapeLayer, SmartObject, SmartSource, TextLayer,
+ NamedPath, Pattern, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer,
};
use photocraft_geom::{TILE_SIZE, TileCoord};
use photocraft_raster::{Surface, Tile, decode_pixel, encode_pixel};
@@ -153,6 +153,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
live: s.live.clone(),
},
LayerContent::Smart(s) => ContentM::Smart {
+ contents_id: Some(s.contents_id.0),
source: match &s.source {
SmartSource::Embedded { file_name, bytes } => SmartSourceM::Embedded { file_name: file_name.clone(), blob: sink.blob(bytes) },
SmartSource::Linked { path } => SmartSourceM::Linked { path: path.clone() },
@@ -299,9 +300,10 @@ fn comp_m(c: &LayerComp, sink: &mut dyn Sink) -> LayerCompM {
pub(crate) struct Loader<'a> {
pub fetch: &'a mut dyn Fetch,
pub preserve_ids: bool,
- pub max_id: u64,
/// Stored layer id → loaded id (differs when ids are remapped), for layer comp states.
pub id_map: std::collections::HashMap<u64, LayerId>,
+ pub contents_id_map: std::collections::HashMap<u64, SmartContentsId>,
+ pub legacy_linked_contents: std::collections::HashMap<String, SmartContentsId>,
}
impl Loader<'_> {
@@ -346,16 +348,25 @@ impl Loader<'_> {
}
fn id(&mut self, raw: u64) -> LayerId {
- let id = if self.preserve_ids {
- self.max_id = self.max_id.max(raw);
- LayerId(raw)
- } else {
- LayerId::fresh()
- };
+ let id = if self.preserve_ids { LayerId(raw) } else { LayerId::fresh() };
self.id_map.insert(raw, id);
id
}
+ fn contents_id(&mut self, raw: Option<u64>, source: &SmartSourceM) -> SmartContentsId {
+ if let Some(raw) = raw {
+ return *self.contents_id_map.entry(raw).or_insert_with(|| if self.preserve_ids { SmartContentsId(raw) } else { SmartContentsId::fresh() });
+ }
+ // Legacy embedded blobs may be deduplicated despite representing independent objects.
+ // Only a nonempty linked path provides an existing shared-source identity.
+ if let SmartSourceM::Linked { path } = source
+ && !path.is_empty()
+ {
+ return *self.legacy_linked_contents.entry(path.clone()).or_insert_with(SmartContentsId::fresh);
+ }
+ SmartContentsId::fresh()
+ }
+
fn comp(&mut self, m: &LayerCompM) -> Result<LayerComp> {
let mut states = Vec::with_capacity(m.states.len());
for s in &m.states {
@@ -438,8 +449,9 @@ impl Loader<'_> {
cache: self.opt_surface(cache)?,
psd_raw: self.opt_blob(psd_raw)?,
}),
- ContentM::Smart { source, transform, smart_filters, cache, psd_raw, filters_enabled, filter_mask, warp, stack_mode, perspective } => {
+ ContentM::Smart { contents_id, source, transform, smart_filters, cache, psd_raw, filters_enabled, filter_mask, warp, stack_mode, perspective } => {
LayerContent::Smart(SmartObject {
+ contents_id: self.contents_id(*contents_id, source),
source: match source {
SmartSourceM::Embedded { file_name, blob } => SmartSource::Embedded { file_name: file_name.clone(), bytes: self.fetch.blob(blob)? },
SmartSourceM::Linked { path } => SmartSource::Linked { path: path.clone() },
@@ -510,6 +522,27 @@ impl Loader<'_> {
}
pub(crate) fn document(&mut self, m: &DocM) -> Result<Document> {
+ // Reserve every stored id before allocating identities missing from older bundles. If an
+ // id is implausibly large, remap the whole document while retaining shared contents groups.
+ if self.preserve_ids {
+ fn max_ids(layers: &[LayerM], depth: usize, max: &mut u64) -> Result<()> {
+ if depth > MAX_GROUP_DEPTH && !layers.is_empty() {
+ return Err(too_deep());
+ }
+ for l in layers {
+ *max = (*max).max(l.id);
+ match &l.content {
+ ContentM::Group { children, .. } => max_ids(children, depth + 1, max)?,
+ ContentM::Smart { contents_id: Some(id), .. } => *max = (*max).max(*id),
+ _ => {}
+ }
+ }
+ Ok(())
+ }
+ let mut max = m.id;
+ max_ids(&m.layers, 0, &mut max)?;
+ self.preserve_ids = reserve_ids_through(max);
+ }
let layers = m.layers.iter().map(|l| self.layer(l, 0)).collect::<Result<Vec<_>>>()?;
let mut channels = Vec::with_capacity(m.channels.len());
for c in &m.channels {
@@ -550,12 +583,7 @@ impl Loader<'_> {
}
}
}
- let id = if self.preserve_ids {
- self.max_id = self.max_id.max(m.id);
- DocId(m.id)
- } else {
- DocId::fresh()
- };
+ let id = if self.preserve_ids { DocId(m.id) } else { DocId::fresh() };
Ok(Document {
id,
name: m.name.clone(),
diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs
index 11c17cb53..6b07ee43d 100644
--- a/crates/format/src/manifest.rs
+++ b/crates/format/src/manifest.rs
@@ -283,6 +283,9 @@ pub enum ContentM {
live: Option<LiveShape>,
},
Smart {
+ /// Shared source identity; older bundles did not record it.
+ #[serde(default)]
+ contents_id: Option<u64>,
source: SmartSourceM,
transform: Affine,
smart_filters: Vec<SmartFilter>,
diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs
index 9fd800871..fcf7884ac 100644
--- a/crates/format/src/store.rs
+++ b/crates/format/src/store.rs
@@ -233,14 +233,14 @@ impl Fetch for LoadFetch<'_> {
pub(crate) fn load(src: &dyn Source, opts: &LoadOptions) -> Result<Document> {
let m = read_manifest(src, opts)?;
let mut fetch = LoadFetch { src, opts: *opts, total: 0, blobs: HashMap::new() };
- let mut loader = Loader { fetch: &mut fetch, preserve_ids: opts.preserve_ids, max_id: 0, id_map: HashMap::new() };
- let doc = loader.document(&m.document)?;
- if opts.preserve_ids && !convert::reserve_ids_through(loader.max_id) {
- // Ids far beyond our counter: remap instead of risking collisions.
- let fresh = LoadOptions { preserve_ids: false, ..*opts };
- return load(src, &fresh);
- }
- Ok(doc)
+ let mut loader = Loader {
+ fetch: &mut fetch,
+ preserve_ids: opts.preserve_ids,
+ id_map: HashMap::new(),
+ contents_id_map: HashMap::new(),
+ legacy_linked_contents: HashMap::new(),
+ };
+ loader.document(&m.document)
}
// ---------------------------------------------------------------------------
diff --git a/crates/format/tests/common/mod.rs b/crates/format/tests/common/mod.rs
index 8e8def3f9..4adf8ccb3 100644
--- a/crates/format/tests/common/mod.rs
+++ b/crates/format/tests/common/mod.rs
@@ -166,6 +166,7 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
let smart = Layer::new(
"Smart",
LayerContent::Smart(SmartObject {
+ contents_id: SmartContentsId::fresh(),
source: SmartSource::Embedded { file_name: "inner.png".into(), bytes: blob(11, 2000) },
transform: Affine::scale(0.5),
smart_filters: vec![SmartFilter {
@@ -194,6 +195,7 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
let linked = Layer::new(
"Linked",
LayerContent::Smart(SmartObject {
+ contents_id: SmartContentsId::fresh(),
source: SmartSource::Linked { path: "/tmp/linked.psd".into() },
transform: Affine::IDENTITY,
smart_filters: vec![],
diff --git a/crates/format/tests/smart_contents.rs b/crates/format/tests/smart_contents.rs
new file mode 100644
index 000000000..ce91f8571
--- /dev/null
+++ b/crates/format/tests/smart_contents.rs
@@ -0,0 +1,143 @@
+//! Native bundles preserve smart-object sharing without inferring it from equal source bytes.
+
+use std::sync::Arc;
+
+use photocraft_color::{ColorMode, SampleType};
+use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size, SmartContentsId, SmartObject, SmartSource};
+use photocraft_format::{LoadOptions, SaveOptions, load_from_bytes, load_from_bytes_with, save_to_bytes, zip};
+use photocraft_geom::Affine;
+
+fn embedded(bytes: &Arc<Vec<u8>>) -> Layer {
+ Layer::new(
+ "embedded",
+ LayerContent::Smart(SmartObject::new(SmartSource::Embedded { file_name: "source.png".into(), bytes: bytes.clone() }, Affine::IDENTITY, None)),
+ )
+}
+
+fn linked(path: &str) -> Layer {
+ Layer::new("linked", LayerContent::Smart(SmartObject::new(SmartSource::Linked { path: path.into() }, Affine::IDENTITY, None)))
+}
+
+fn sample() -> Document {
+ let mut doc = Document::new("contents identities", Size::new(1, 1), ColorMode::Rgb, SampleType::U8);
+ let bytes = Arc::new(vec![1, 2, 3]);
+ let first = embedded(&bytes);
+ let duplicate = first.duplicate();
+ doc.layers.push(Layer::group("instances", vec![first, duplicate]));
+ doc.layers.push(embedded(&bytes));
+ doc
+}
+
+fn contents_ids(doc: &Document) -> Vec<SmartContentsId> {
+ doc.walk()
+ .iter()
+ .filter_map(|(_, _, layer)| match &layer.content {
+ LayerContent::Smart(s) => Some(s.contents_id),
+ _ => None,
+ })
+ .collect()
+}
+
+fn rewrite_manifest(bytes: &[u8], edit: impl FnOnce(&mut serde_json::Value)) -> Vec<u8> {
+ let r = zip::ZipReader::new(bytes).unwrap();
+ let mut manifest: serde_json::Value = serde_json::from_slice(&r.read_by_name("manifest.json", usize::MAX).unwrap()).unwrap();
+ edit(&mut manifest);
+ let mut z = zip::ZipWriter::new();
+ z.add("manifest.json", &serde_json::to_vec(&manifest).unwrap()).unwrap();
+ for entry in r.entries.iter().filter(|e| e.name != "manifest.json") {
+ z.add(&entry.name, &r.read(entry, usize::MAX).unwrap()).unwrap();
+ }
+ z.finish().unwrap()
+}
+
+fn remove_contents_ids(layers: &mut serde_json::Value) {
+ for layer in layers.as_array_mut().unwrap() {
+ let content = layer["content"].as_object_mut().unwrap();
+ content.remove("contents_id");
+ if let Some(children) = content.get_mut("children") {
+ remove_contents_ids(children);
+ }
+ }
+}
+
+#[test]
+fn smart_contents_roundtrip_preserves_shared_instances_and_independent_equal_blobs() {
+ let doc = sample();
+ let ids = contents_ids(&doc);
+ assert_eq!(ids[0], ids[1], "ordinary layer duplicates share their contents");
+ assert_ne!(ids[0], ids[2], "equal bytes, even the same Arc, do not imply shared contents");
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ assert_eq!(load_from_bytes(&bytes).unwrap(), doc);
+}
+
+#[test]
+fn smart_contents_remapping_preserves_groups() {
+ let doc = sample();
+ let original = contents_ids(&doc);
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ let back = load_from_bytes_with(&bytes, &LoadOptions { preserve_ids: false, ..Default::default() }).unwrap();
+ let ids = contents_ids(&back);
+ assert_eq!(ids[0], ids[1]);
+ assert_ne!(ids[0], ids[2]);
+ assert!(ids.iter().all(|id| !original.contains(id)));
+ assert_ne!(back.id, doc.id);
+ assert_ne!(back.layers[0].id, doc.layers[0].id);
+}
+
+#[test]
+fn legacy_smart_contents_are_independent_except_for_nonempty_linked_paths() {
+ let mut doc = sample();
+ doc.layers.extend([linked("/tmp/shared.psd"), linked("/tmp/shared.psd"), linked("/tmp/other.psd"), linked(""), linked("")]);
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ let legacy = rewrite_manifest(&bytes, |m| remove_contents_ids(&mut m["document"]["layers"]));
+ let back = load_from_bytes(&legacy).unwrap();
+ let ids = contents_ids(&back);
+ assert_ne!(ids[0], ids[1], "legacy embedded duplicates have no recorded shared identity");
+ assert_ne!(ids[0], ids[2]);
+ assert_ne!(ids[1], ids[2]);
+ assert_eq!(ids[3], ids[4]);
+ assert_ne!(ids[3], ids[5]);
+ assert_ne!(ids[6], ids[7], "an empty path identifies no shared source");
+ // Allocated legacy identities become explicit on the next save.
+ assert_eq!(load_from_bytes(&save_to_bytes(&back, &SaveOptions::default()).unwrap()).unwrap(), back);
+}
+
+#[test]
+fn stored_smart_contents_ids_are_reserved_before_allocating_legacy_ids() {
+ let mut doc = sample();
+ doc.layers.push(linked("/tmp/source.psd"));
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ let stored = LayerId::fresh().0 + 5000;
+ let mixed = rewrite_manifest(&bytes, |m| {
+ remove_contents_ids(&mut m["document"]["layers"]);
+ // This later, nested entry must be reserved before the first missing identity is minted.
+ m["document"]["layers"][0]["content"]["children"][1]["content"]["contents_id"] = stored.into();
+ });
+ let back = load_from_bytes(&mixed).unwrap();
+ let ids = contents_ids(&back);
+ assert_eq!(ids[1], SmartContentsId(stored));
+ assert!(ids[0].0 > stored);
+ assert!(ids[2].0 > stored);
+ assert!(ids[3].0 > stored);
+ assert!(LayerId::fresh().0 > stored);
+}
+
+#[test]
+fn extreme_smart_contents_ids_remap_without_poisoning_allocator() {
+ let doc = sample();
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ let damaged = rewrite_manifest(&bytes, |m| {
+ for child in m["document"]["layers"][0]["content"]["children"].as_array_mut().unwrap() {
+ child["content"]["contents_id"] = u64::MAX.into();
+ }
+ });
+ let back = load_from_bytes(&damaged).unwrap();
+ let ids = contents_ids(&back);
+ assert_eq!(ids[0], ids[1]);
+ assert_ne!(ids[0], ids[2]);
+ assert_ne!(back.id, doc.id);
+ assert_ne!(back.layers[0].id, doc.layers[0].id);
+ assert!(ids.iter().all(|id| id.0 < u64::MAX / 2));
+ assert!(SmartContentsId::fresh().0 < u64::MAX / 2);
+ assert!(LayerId::fresh().0 < u64::MAX / 2);
+}
diff --git a/crates/io/src/linked.rs b/crates/io/src/linked.rs
index fbc8f0d88..b1b7286d2 100644
--- a/crates/io/src/linked.rs
+++ b/crates/io/src/linked.rs
@@ -188,6 +188,23 @@ pub fn block_uuids(data: &[u8]) -> Vec<String> {
split_items(data).into_iter().filter_map(|(u, _)| u).collect()
}
+/// Copies one linked item under a new UUID, preserving its embedded, external or alias payload.
+pub(crate) fn copy_item(data: &[u8], uuid: &str, new_uuid: &str) -> Option<Vec<u8>> {
+ let (_, raw) = split_items(data).into_iter().find(|(u, _)| u.as_deref() == Some(uuid))?;
+ let len = usize::try_from(u64::from_be_bytes(raw.get(..8)?.try_into().ok()?)).ok()?;
+ let item = raw.get(8..8usize.checked_add(len)?)?;
+ let old_end = 9usize.checked_add(usize::from(*item.get(8)?))?;
+ let new_len = u8::try_from(new_uuid.len()).ok()?;
+ let mut copy = item.get(..8)?.to_vec();
+ copy.push(new_len);
+ copy.extend_from_slice(new_uuid.as_bytes());
+ copy.extend_from_slice(item.get(old_end..)?);
+ let mut out = (copy.len() as u64).to_be_bytes().to_vec();
+ out.extend(copy);
+ out.resize(out.len().next_multiple_of(4), 0);
+ Some(out)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -236,4 +253,17 @@ mod tests {
d.truncate(d.len() - 6);
assert!(parse_linked_files(&d).is_empty());
}
+
+ #[test]
+ fn copying_linked_item_preserves_unknown_external_payload() {
+ let mut raw = encode_linked_file(&LinkedFile { uuid: "old".into(), file_name: "missing.psb".into(), bytes: vec![7; 5] });
+ raw[8..12].copy_from_slice(b"liFE");
+ let copy = copy_item(&raw, "old", "independent-copy").unwrap();
+ assert_eq!(block_uuids(&copy), vec!["independent-copy"]);
+ let original_len = u64::from_be_bytes(raw[..8].try_into().unwrap()) as usize;
+ let copied_len = u64::from_be_bytes(copy[..8].try_into().unwrap()) as usize;
+ assert_eq!(&copy[8..16], &raw[8..16]);
+ assert_eq!(&copy[17 + "independent-copy".len()..8 + copied_len], &raw[20..8 + original_len]);
+ assert!(copy_item(&raw, "missing", "new").is_none());
+ }
}
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index f58f73280..c72f99d64 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -1,7 +1,7 @@
//! [`Document`] → PSD/PSB.
use photocraft_color::{ColorMode, PixelFormat, SampleType};
-use photocraft_doc::{Document, Layer, LayerContent, LayerMask};
+use photocraft_doc::{Document, Layer, LayerContent, LayerMask, SmartContentsId};
use photocraft_psd::file::{GlobalLayerMask, LayerInfoPlacement};
use photocraft_psd::layer::{BlendingRanges, ChannelData, LayerFlags, LayerInfo, LayerMask as PsdMask, MaskData, MaskParameters};
use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids, version_info_resource};
@@ -81,6 +81,13 @@ struct Source {
dpi: f64,
}
+fn contents_uuid(contents_id: SmartContentsId, bytes: &[u8]) -> String {
+ let mut identity = blake3::Hasher::new();
+ identity.update(&contents_id.0.to_le_bytes());
+ identity.update(bytes);
+ crate::smart_map::uuid_from(identity.finalize().as_bytes())
+}
+
/// Smart-object state collected while emitting layers, written into the global blocks at the end.
#[derive(Default)]
struct SmartOut {
@@ -96,8 +103,18 @@ struct SmartOut {
prune_ok: bool,
/// Files to embed.
add: Vec<crate::linked::LinkedFile>,
- /// Sources converted so far, by content hash (`Err` = can't be embedded).
- converted: std::collections::HashMap<[u8; 32], Result<Source, String>>,
+ /// Sources converted so far, by contents identity and bytes (`Err` = can't be embedded).
+ converted: std::collections::HashMap<(SmartContentsId, [u8; 32]), Result<Source, String>>,
+ /// Each placed layer has its own id, even when it duplicates an imported layer.
+ placed_used: std::collections::HashSet<String>,
+ /// Original instances reserve their imported placement regardless of layer order.
+ placed_owners: std::collections::HashMap<String, photocraft_doc::LayerId>,
+ /// Legacy records without a placed id stay unchanged for the original instance.
+ unplaced_owners: std::collections::HashMap<SmartContentsId, photocraft_doc::LayerId>,
+ /// The imported identity that keeps each original linked UUID.
+ linked_contents: std::collections::HashMap<String, SmartContentsId>,
+ /// Independent copies of preserved linked items, including unavailable external sources.
+ linked_copies: std::collections::BTreeMap<(String, SmartContentsId), photocraft_doc::PsdGlobalBlock>,
/// Embedded documents decoded while converting them, by uuid (for the filter caches).
docs: std::collections::HashMap<String, Document>,
/// Source composites (document pixel format, source space) by uuid; `None` = unreadable.
@@ -131,7 +148,27 @@ impl SmartOut {
.filter_map(|(_, _, d)| photocraft_psd::filter_effects::FilterEffects::parse(d).ok())
.flat_map(|fx| fx.items)
.collect();
- SmartOut { depth, globals, known, prune_ok: true, old_fx, ..Default::default() }
+ let mut linked_contents = std::collections::HashMap::new();
+ let mut placed_owners = std::collections::HashMap::new();
+ let mut unplaced_owners = std::collections::HashMap::new();
+ let mut layers = doc.walk();
+ // Duplicating a layer clears psd_id and gives it a newer runtime id.
+ layers.sort_by_key(|(_, _, layer)| (layer.psd_id.is_none(), layer.id));
+ for (_, _, layer) in layers {
+ if let LayerContent::Smart(sm) = &layer.content
+ && let photocraft_doc::SmartSource::Linked { path } = &sm.source
+ && let Some(placed) = sm.psd_raw.as_ref().and_then(|d| crate::smart_map::parse_sold(d))
+ && placed.idnt == *path
+ {
+ linked_contents.entry(path.clone()).or_insert(sm.contents_id);
+ if placed.placed.is_empty() {
+ unplaced_owners.entry(sm.contents_id).or_insert(layer.id);
+ } else {
+ placed_owners.entry(placed.placed).or_insert(layer.id);
+ }
+ }
+ }
+ SmartOut { depth, globals, known, prune_ok: true, old_fx, linked_contents, placed_owners, unplaced_owners, ..Default::default() }
}
/// The document's global blocks with the linked-layer files and filter caches brought up to
@@ -177,6 +214,13 @@ impl SmartOut {
let data: Vec<u8> = self.add.iter().flat_map(crate::linked::encode_linked_file).collect();
out.push((*b"8BIM", *b"lnk2", Arc::new(data)));
}
+ for (sig, key, data) in self.linked_copies.values() {
+ if let Some((_, _, block)) = out.iter_mut().find(|(s, k, _)| s == sig && k == key) {
+ Arc::make_mut(block).extend_from_slice(data);
+ } else {
+ out.push((*sig, *key, data.clone()));
+ }
+ }
if !fx_placed && !self.new_fx.is_empty() {
let fx = photocraft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() };
out.push((*b"8BIM", *b"FEid", Arc::new(padded_fx(&fx))));
@@ -610,8 +654,25 @@ impl Ex {
mask_linked: sm.filter_mask.as_ref().is_some_and(|m| m.linked),
};
let same_source = template.as_ref().filter(|t| t.idnt == src.uuid);
+ let unchanged = same_source.zip(sm.psd_raw.as_ref()).is_some_and(|(t, data)| self.placed_unchanged(t, data, sm, &stack));
+ let placed = match same_source {
+ Some(t) if t.placed.is_empty() && unchanged && self.smart.unplaced_owners.get(&sm.contents_id) == Some(&l.id) => String::new(),
+ Some(t) if self.smart.placed_owners.get(&t.placed) == Some(&l.id) && self.smart.placed_used.insert(t.placed.clone()) => t.placed.clone(),
+ _ => {
+ let seed = format!("{}:{}", src.uuid, l.id.0);
+ let mut suffix = 0u64;
+ loop {
+ let id = uuid_from(if suffix == 0 { seed.clone() } else { format!("{seed}:{suffix}") }.as_bytes());
+ if !self.smart.placed_owners.contains_key(&id) && self.smart.placed_used.insert(id.clone()) {
+ break id;
+ }
+ suffix += 1;
+ }
+ }
+ };
if let (Some(t), Some(data)) = (same_source, sm.psd_raw.as_ref())
- && self.placed_unchanged(t, data, sm, &stack)
+ && t.placed == placed
+ && unchanged
{
let keys: &[&[u8; 4]] = if raw.iter().any(|(k, _)| k == b"SoLd") { &[b"SoLd"] } else { &[b"SoLE", b"SoLd"] };
match keys.iter().find_map(|k| raw.iter().position(|(rk, _)| rk == *k)) {
@@ -623,10 +684,6 @@ impl Ex {
}
return;
}
- let placed = match same_source {
- Some(t) if !t.placed.is_empty() => t.placed.clone(),
- _ => uuid_from(format!("{}:{}", src.uuid, l.id.0).as_bytes()),
- };
let size = same_source.and_then(|t| crate::smart_map::stored_size(&t.descriptor)).unwrap_or(src.size);
let size = if size.0 > 0.0 && size.1 > 0.0 { size } else { size_from_layer(sm) };
let mut warnings = Vec::new();
@@ -707,7 +764,31 @@ impl Ex {
source_geometry(&f.file_name, &f.bytes).ok()
});
let (size, dpi) = geometry.unwrap_or((size_from_layer(sm), f64::from(self.dpi)));
- Ok(Source { uuid: path.clone(), size, dpi })
+ let original = self.smart.linked_contents.entry(path.clone()).or_insert(sm.contents_id);
+ // An absent Idnt is not a shared-source identity; import treats each as fresh.
+ let uuid = if path.is_empty() || *original == sm.contents_id {
+ path.clone()
+ } else {
+ let uuid = contents_uuid(sm.contents_id, path.as_bytes());
+ let key = (path.clone(), sm.contents_id);
+ if !self.smart.linked_copies.contains_key(&key) {
+ let copy = self
+ .smart
+ .globals
+ .iter()
+ .find_map(|(sig, k, data)| {
+ LINK_KEYS
+ .contains(&k)
+ .then(|| crate::linked::copy_item(data, path, &uuid))
+ .flatten()
+ .map(|data| (*sig, *k, std::sync::Arc::new(data)))
+ })
+ .ok_or_else(|| format!("the linked source {path} has no readable record to copy independently"))?;
+ self.smart.linked_copies.insert(key, copy);
+ }
+ uuid
+ };
+ Ok(Source { uuid, size, dpi })
}
SmartSource::Linked { path } => {
#[cfg(not(target_arch = "wasm32"))]
@@ -715,12 +796,12 @@ impl Ex {
let bytes = std::fs::read(path).map_err(|e| format!("the linked file {path} can't be read: {e}"))?;
let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string();
self.warnings.push(format!("the linked smart object {name} was embedded (PSD export keeps no external links)"));
- self.embed(&name, &bytes)
+ self.embed(sm.contents_id, &name, &bytes)
}
#[cfg(target_arch = "wasm32")]
Err(format!("the linked file {path} can't be read here"))
}
- SmartSource::Embedded { file_name, bytes } => self.embed(file_name, bytes),
+ SmartSource::Embedded { file_name, bytes } => self.embed(sm.contents_id, file_name, bytes),
}
}
@@ -734,7 +815,10 @@ impl Ex {
Some(d) => Some(d.clone()),
None => {
let file = self.smart.add.iter().find(|f| f.uuid == uuid).cloned().or_else(|| {
- let meta = photocraft_doc::Metadata { psd_global_blocks: self.smart.globals.clone(), ..Default::default() };
+ let meta = photocraft_doc::Metadata {
+ psd_global_blocks: self.smart.globals.iter().chain(self.smart.linked_copies.values()).cloned().collect(),
+ ..Default::default()
+ };
crate::linked::find_linked_file(&meta, uuid)
});
file.and_then(|f| crate::import(&f.file_name, &f.bytes).ok()).map(|r| r.document)
@@ -761,18 +845,18 @@ impl Ex {
}
/// Adds `bytes` as an embedded file (converted to PSB when it is a `.pcraft` bundle), once
- /// per distinct content.
- fn embed(&mut self, file_name: &str, bytes: &[u8]) -> Result<Source, String> {
- let key = *blake3::hash(bytes).as_bytes();
+ /// per contents identity and bytes. Equal bytes in independent objects stay independent.
+ fn embed(&mut self, contents_id: SmartContentsId, file_name: &str, bytes: &[u8]) -> Result<Source, String> {
+ let key = (contents_id, *blake3::hash(bytes).as_bytes());
if let Some(r) = self.smart.converted.get(&key) {
return r.clone();
}
- let r = self.convert_source(file_name, bytes);
+ let r = self.convert_source(contents_id, file_name, bytes);
self.smart.converted.insert(key, r.clone());
r
}
- fn convert_source(&mut self, file_name: &str, bytes: &[u8]) -> Result<Source, String> {
+ fn convert_source(&mut self, contents_id: SmartContentsId, file_name: &str, bytes: &[u8]) -> Result<Source, String> {
let (name, data, size, dpi, nested) = if photocraft_format::is_pcraft(bytes) {
if self.smart.depth >= MAX_NESTING {
return Err(format!("smart objects nest more than {MAX_NESTING} deep"));
@@ -789,7 +873,7 @@ impl Ex {
let (size, dpi) = source_geometry(file_name, bytes).unwrap_or(((0.0, 0.0), f64::from(self.dpi)));
(file_name.to_string(), bytes.to_vec(), size, dpi, None)
};
- let uuid = crate::smart_map::uuid_from(&data);
+ let uuid = contents_uuid(contents_id, &data);
if let Some(d) = nested {
self.smart.docs.insert(uuid.clone(), d);
}
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index 6490471f3..a61c1909b 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -3,7 +3,9 @@
use std::sync::Arc;
use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};
-use photocraft_doc::{AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, ShapeLayer, SmartObject, SmartSource, TextLayer};
+use photocraft_doc::{
+ AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer,
+};
use photocraft_geom::{Rect, Size, TILE_SIZE};
use photocraft_psd::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK};
use photocraft_psd::resources::ids;
@@ -55,6 +57,8 @@ pub(crate) struct Ctx<'a> {
pub txt2: Option<photocraft_text::engine_data::Value>,
/// Smart-filter caches from the global `FEid`/`FXid` blocks (filter masks, by placed id).
pub filter_effects: Vec<photocraft_psd::filter_effects::FilterEffectsItem>,
+ /// Placed layers naming the same source share editable contents, not their placement.
+ pub smart_contents: std::collections::HashMap<String, SmartContentsId>,
/// Cancellation and progress for background opens (checked per layer record).
pub ctl: photocraft_raster::Interrupt<'a>,
/// Layer records decoded so far, out of `total` (progress).
@@ -317,6 +321,8 @@ impl Ctx<'_> {
LayerContent::Text(t)
} else if let Some(k) = smart_key {
let (id, transform) = rec.block(k).map(|b| blocks::parse_smart(k, &b.data)).unwrap_or_default();
+ let contents_id =
+ if id.is_empty() { SmartContentsId::fresh() } else { *self.smart_contents.entry(id.clone()).or_insert_with(SmartContentsId::fresh) };
// Smart filters (`filterFX` in the placed-layer data) and their mask (`FEid`).
let placed = rec.block(b"SoLd").or_else(|| rec.block(b"SoLE")).and_then(|b| crate::smart_map::parse_sold(&b.data));
let stack = placed.as_ref().and_then(|p| p.stack.clone()).unwrap_or_default();
@@ -325,6 +331,7 @@ impl Ctx<'_> {
_ => None,
};
LayerContent::Smart(SmartObject {
+ contents_id,
source: SmartSource::Linked { path: id },
transform,
smart_filters: stack.filters,
@@ -623,6 +630,7 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)
dpi: doc.resolution_dpi,
txt2: file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)),
filter_effects: Vec::new(),
+ smart_contents: Default::default(),
ctl: *ctl,
done: 0,
total: file.layers().len(),
diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs
index f4b7f47d3..7423de9a5 100644
--- a/crates/io/src/smart_map.rs
+++ b/crates/io/src/smart_map.rs
@@ -597,13 +597,16 @@ fn pad4(mut v: Vec<u8>) -> Vec<u8> {
}
/// `SoLd` block data. With `template` (the imported descriptor) every key it has is kept and only
-/// the transform (when it moved), warp and filter stack are rewritten; otherwise a fresh
-/// descriptor in Photoshop's key order.
+/// the placed id (for a duplicate), transform (when it moved), warp and filter stack are rewritten;
+/// otherwise a fresh descriptor in Photoshop's key order.
pub fn sold_bytes(template: Option<&Descriptor>, s: &PlacedSpec<'_>, warnings: &mut Vec<String>) -> Vec<u8> {
let warp = warp_desc(s.warp, s.size, warnings);
let d = match template {
Some(t) => {
let mut d = t.clone();
+ if text_of(t, "placed").as_deref() != Some(s.placed) {
+ set(&mut d, "placed", Value::Text(UnicodeString::new_nul(s.placed)));
+ }
if quad_moved(t, s) {
set(&mut d, "Trnf", quad(s));
set(&mut d, "nonAffineTransform", quad(s));
@@ -789,8 +792,7 @@ fn filter_mask_item(placed: &str, mask: Option<&LayerMask>, bounds: GeomRect, sa
FilterEffectsItem { id: placed.to_string(), version: 1, rect, depth: u32::from(depth), max_channels: 24, slots: vec![None; 26], mask: Some((rect, plane)) }
}
-/// A uuid-shaped id (8-4-4-4-12 hex digits) derived from `seed`: equal contents get equal ids, so
-/// identical smart objects share one embedded file, as Photoshop's instances do.
+/// A deterministic uuid-shaped id (8-4-4-4-12 hex digits) derived from `seed`.
pub fn uuid_from(seed: &[u8]) -> String {
let h = blake3::hash(seed);
let x = to_hex(&h.as_bytes()[..16]);
diff --git a/crates/io/tests/roundtrip.rs b/crates/io/tests/roundtrip.rs
index fc84700e6..3e2403f2e 100644
--- a/crates/io/tests/roundtrip.rs
+++ b/crates/io/tests/roundtrip.rs
@@ -115,6 +115,7 @@ fn text_shape_smart_raw_blocks_survive() {
let mut smart = Layer::new(
"Smart",
LayerContent::Smart(SmartObject {
+ contents_id: SmartContentsId::fresh(),
source: SmartSource::Linked { path: String::new() },
transform: photocraft_geom::Affine::IDENTITY,
smart_filters: vec![],
diff --git a/crates/io/tests/smart_contents_identity.rs b/crates/io/tests/smart_contents_identity.rs
new file mode 100644
index 000000000..632547b0d
--- /dev/null
+++ b/crates/io/tests/smart_contents_identity.rs
@@ -0,0 +1,201 @@
+//! Shared contents and independent placed layers through PSD/PSB persistence.
+
+use std::sync::Arc;
+
+use photocraft_color::{BlendMode, ColorMode, SampleType};
+use photocraft_doc::{Document, Layer, LayerContent, SmartContentsId, SmartFilter, SmartObject, SmartSource};
+use photocraft_geom::{Affine, Size};
+use photocraft_io::{ExportOptions, export, import, linked, smart_map};
+use photocraft_psd::{PsdFile, TaggedBlock};
+use photocraft_raster::Surface;
+
+fn fixture() -> Document {
+ let mut source = Document::new("contents", Size::new(2, 2), ColorMode::Rgb, SampleType::U8);
+ let mut pixels = Surface::new(source.pixel_format());
+ pixels.fill_rect(source.bounds(), &[1.0, 0.0, 0.0, 1.0]);
+ source.layers.push(Layer::new("red", LayerContent::Raster(pixels.clone())));
+ let bytes = photocraft_format::save_to_bytes(&source, &Default::default()).unwrap();
+ let mut doc = Document::new("instances", Size::new(12, 4), ColorMode::Rgb, SampleType::U8);
+ let smart = SmartObject::new(SmartSource::Embedded { file_name: "contents.pcraft".into(), bytes: Arc::new(bytes) }, Affine::IDENTITY, Some(pixels));
+ doc.layers.push(Layer::new("original", LayerContent::Smart(smart)));
+ doc
+}
+
+fn smart<'a>(doc: &'a Document, name: &str) -> &'a SmartObject {
+ let layer = doc.layers.iter().find(|l| l.name == name).unwrap();
+ let LayerContent::Smart(sm) = &layer.content else { panic!("{name} is no longer a smart object") };
+ sm
+}
+
+fn smart_mut(layer: &mut Layer) -> &mut SmartObject {
+ let LayerContent::Smart(sm) = &mut layer.content else { panic!("expected smart object") };
+ sm
+}
+
+fn round_trip(doc: &Document, extension: &str) -> (PsdFile, Document) {
+ let out = export(doc, extension, &ExportOptions::default()).unwrap();
+ assert!(!out.warnings.iter().any(|w| w.contains("smart object written as pixels")), "{:?}", out.warnings);
+ let file = PsdFile::from_bytes(&out.bytes).unwrap();
+ let back = import(extension, &out.bytes).unwrap().document;
+ (file, back)
+}
+
+fn sold(file: &PsdFile, name: &str) -> smart_map::Placed {
+ let layer = file.layers().iter().find(|l| l.name() == name).unwrap();
+ smart_map::parse_sold(&layer.block(b"SoLd").unwrap().data).unwrap()
+}
+
+fn gaussian(radius: f64) -> SmartFilter {
+ SmartFilter {
+ command: "filter.blur.gaussianBlur".into(),
+ params: serde_json::json!({ "radius": radius }),
+ blend: BlendMode::Normal,
+ opacity: 1.0,
+ visible: true,
+ }
+}
+
+#[test]
+fn psd_and_psb_keep_shared_contents_and_identical_independent_copies_distinct() {
+ let mut doc = fixture();
+ let mut shared = doc.layers[0].duplicate();
+ shared.name = "shared".into();
+ let sm = smart_mut(&mut shared);
+ sm.transform = Affine::translate(4.0, 0.0);
+ sm.cache = sm.cache.as_ref().map(|c| c.translated(4, 0, c.content_bounds()));
+ sm.smart_filters.push(gaussian(2.0));
+ let mut independent = doc.layers[0].duplicate();
+ independent.name = "independent".into();
+ smart_mut(&mut independent).contents_id = SmartContentsId::fresh();
+ doc.layers.extend([shared, independent]);
+
+ for extension in ["psd", "psb"] {
+ let (file, back) = round_trip(&doc, extension);
+ let a = sold(&file, "original");
+ let b = sold(&file, "shared");
+ let c = sold(&file, "independent");
+ assert_eq!(a.idnt, b.idnt);
+ assert_ne!(a.idnt, c.idnt);
+ assert_eq!([a.placed, b.placed, c.placed].into_iter().collect::<std::collections::HashSet<_>>().len(), 3);
+ let payloads: Vec<_> = file.global_blocks.iter().filter(|b| &b.key == b"lnk2").flat_map(|b| linked::parse_linked_files(&b.data)).collect();
+ assert_eq!(payloads.len(), 2);
+ assert_eq!(payloads[0].bytes, payloads[1].bytes, "independent identical contents still have separate payload identities");
+ assert_eq!(smart(&back, "original").contents_id, smart(&back, "shared").contents_id);
+ assert_ne!(smart(&back, "original").contents_id, smart(&back, "independent").contents_id);
+ assert_eq!(smart(&back, "shared").transform, Affine::translate(4.0, 0.0));
+ assert_eq!(smart(&back, "shared").smart_filters[0].params["radius"].as_f64(), Some(2.0));
+ assert!(smart(&back, "original").smart_filters.is_empty());
+ assert!(smart(&back, "independent").smart_filters.is_empty());
+ }
+}
+
+#[test]
+fn duplicated_imported_layer_keeps_source_but_gets_its_own_placement() {
+ let (before, mut doc) = round_trip(&fixture(), "psd");
+ let original_files = before.global_blocks.iter().find(|b| &b.key == b"lnk2").unwrap().data.clone();
+ let mut duplicate = doc.layers[0].duplicate();
+ duplicate.name = "duplicate".into();
+ smart_mut(&mut duplicate).smart_filters.push(gaussian(3.0));
+ // An imported UUID may have been generated under a different allocator lifetime and equal
+ // the duplicate's first candidate. Preserve it for the original even when emitted second.
+ let old = sold(&before, "original");
+ let colliding = smart_map::uuid_from(format!("{}:{}", old.idnt, duplicate.id.0).as_bytes());
+ let spec = smart_map::PlacedSpec {
+ idnt: &old.idnt,
+ placed: &colliding,
+ transform: Affine::IDENTITY,
+ perspective: None,
+ size: (2.0, 2.0),
+ dpi: 72.0,
+ warp: None,
+ filter_fx: None,
+ };
+ let original_raw = smart_map::sold_bytes(Some(&old.descriptor), &spec, &mut Vec::new());
+ for layer in [&mut doc.layers[0], &mut duplicate] {
+ smart_mut(layer).psd_raw = Some(Arc::new(original_raw.clone()));
+ for (key, data) in &mut layer.psd_blocks {
+ if key == b"SoLd" {
+ *data = Arc::new(original_raw.clone());
+ }
+ }
+ }
+ doc.layers.push(duplicate);
+
+ for reversed in [false, true] {
+ let mut ordered = doc.clone();
+ if reversed {
+ ordered.layers.reverse();
+ }
+ let (after, back) = round_trip(&ordered, "psd");
+ let original = sold(&after, "original");
+ let duplicate = sold(&after, "duplicate");
+ assert_eq!(original.idnt, duplicate.idnt);
+ assert_eq!(original.placed, colliding);
+ assert_ne!(original.placed, duplicate.placed);
+ let filter_cache = after.global_blocks.iter().find(|b| &b.key == b"FEid").unwrap();
+ let filter_cache = photocraft_psd::filter_effects::FilterEffects::parse(&filter_cache.data).unwrap();
+ assert_eq!(filter_cache.items.len(), 1);
+ assert_eq!(filter_cache.items[0].id, duplicate.placed);
+ assert_eq!(after.layers().iter().find(|l| l.name() == "original").unwrap().block(b"SoLd").unwrap().data, original_raw);
+ assert_eq!(after.global_blocks.iter().find(|b| &b.key == b"lnk2").unwrap().data, original_files);
+ assert_eq!(smart(&back, "original").contents_id, smart(&back, "duplicate").contents_id);
+ assert_eq!(smart(&back, "duplicate").smart_filters[0].params["radius"].as_f64(), Some(3.0));
+ assert!(smart(&back, "original").smart_filters.is_empty());
+ }
+}
+
+#[test]
+fn missing_source_identifiers_do_not_join_imported_contents() {
+ let (mut file, _) = round_trip(&fixture(), "psd");
+ let spec = smart_map::PlacedSpec {
+ idnt: "",
+ placed: "placement",
+ transform: Affine::IDENTITY,
+ perspective: None,
+ size: (2.0, 2.0),
+ dpi: 72.0,
+ warp: None,
+ filter_fx: None,
+ };
+ let data = smart_map::sold_bytes(None, &spec, &mut Vec::new());
+ let mut record = file.layers()[0].clone();
+ record.blocks.retain(|b| !matches!(&b.key, b"SoLd" | b"SoLE" | b"PlLd"));
+ record.blocks.push(TaggedBlock::new(*b"SoLd", data));
+ *file.layers_mut() = vec![record.clone(), record];
+ let (doc, _) = photocraft_io::psd_to_document(&file);
+ let LayerContent::Smart(a) = &doc.layers[0].content else { panic!("first smart object missing") };
+ let LayerContent::Smart(b) = &doc.layers[1].content else { panic!("second smart object missing") };
+ assert_ne!(a.contents_id, b.contents_id);
+ let (_, back) = round_trip(&doc, "psd");
+ let LayerContent::Smart(a) = &back.layers[0].content else { panic!("first smart object lost on save") };
+ let LayerContent::Smart(b) = &back.layers[1].content else { panic!("second smart object lost on save") };
+ assert_ne!(a.contents_id, b.contents_id);
+}
+
+#[test]
+fn independent_unavailable_link_retains_separate_preserved_record() {
+ let (mut file, _) = round_trip(&fixture(), "psd");
+ let block = file.global_blocks.iter_mut().find(|b| &b.key == b"lnk2").unwrap();
+ // An opaque external item: the source UUID is known, but no embedded bytes can be loaded.
+ block.data[8..12].copy_from_slice(b"liFE");
+ let original_record = block.data.clone();
+ let (mut doc, _) = photocraft_io::psd_to_document(&file);
+ let mut independent = doc.layers[0].duplicate();
+ independent.name = "independent".into();
+ let sm = smart_mut(&mut independent);
+ sm.contents_id = SmartContentsId::fresh();
+ sm.psd_raw = None;
+ independent.psd_blocks.retain(|(key, _)| !matches!(key, b"SoLd" | b"SoLE" | b"PlLd"));
+ // Encounter the independent copy first: the original imported identity must keep its UUID.
+ doc.layers.insert(0, independent);
+
+ let (after, back) = round_trip(&doc, "psd");
+ assert_eq!(sold(&file, "original").idnt, sold(&after, "original").idnt);
+ assert_ne!(sold(&after, "original").idnt, sold(&after, "independent").idnt);
+ let links = &after.global_blocks.iter().find(|b| &b.key == b"lnk2").unwrap().data;
+ assert!(links.starts_with(&original_record));
+ assert_eq!(linked::block_uuids(links).len(), 2);
+ assert_ne!(smart(&back, "original").contents_id, smart(&back, "independent").contents_id);
+ let (again, _) = round_trip(&doc, "psd");
+ assert_eq!(after.to_bytes().unwrap(), again.to_bytes().unwrap());
+}
diff --git a/docs/decisions.md b/docs/decisions.md
new file mode 100644
index 000000000..15519ecf7
--- /dev/null
+++ b/docs/decisions.md
@@ -0,0 +1,7 @@
+# Implementation decisions
+
+## 2026-10-10: Smart Object contents identity (#2163)
+
+Smart Object instances carry a document-scoped contents ID separately from their layer ID. Normal duplicates preserve it; New Smart Object via Copy creates a new one. Contents edits update the matching instances together, retaining their individual placement and filters. Copies into another document remap contents IDs as a batch, preserving sharing within the copied layers without joining existing destination objects.
+
+Native files persist this ID. Legacy embedded objects without an ID remain independent: identical file bytes do not prove that two objects were intended to share edits. Legacy nonempty linked paths and PSD source identifiers retain their explicit sharing relationship. PSD export keys embedded sources by contents identity as well as bytes, so independent equal-content objects stay independent.