From b4c7656c49d60e0cd61de9efef3650386da83bbc Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 13:09:16 -0800 Subject: [PATCH] feat(engine): replay Smart Object file events from ATN --- crates/engine/src/cmd/atn_cmds/events.rs | 69 +++++++- crates/engine/src/cmd/atn_cmds/tests.rs | 4 + crates/engine/tests/it/atn_newer_events.rs | 196 ++++++++++++++++++++- docs/atn.md | 21 +++ 4 files changed, 283 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 67e1aeae75..0e04fb85df 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -1,6 +1,6 @@ const DIFFUSE_MODE: &[(&str, &str)] = &[("Nrml", "normal"), ("DrkO", "darkenOnly"), ("LghO", "lightenOnly"), ("Anst", "anisotropic")]; use super::adjustments::{adjustment_by_class, adjustment_steps, levels_from, levels_to, shadows_highlights_from, shadows_highlights_to}; -use super::descriptors::{desc, get_bool, get_ref, jbool, layer_ref, layer_target, ref_class, target_ref}; +use super::descriptors::{desc, get_bool, get_ref, jbool, layer_ref, layer_target, path_text, path_value, ref_class, target_ref}; use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; use super::steps_doc::{ align_from, align_to, canvas_size_from, canvas_size_to, close_from, close_to, conditional_from, conditional_to, convert_mode_from, convert_mode_to, @@ -178,7 +178,8 @@ fn clipping_to(_: &str, p: &Value) -> Option { // Target matching follows #10628's Link Layers adapter. Recorded Link and Unlink // need explicit state: replaying the UI toggle can perform the opposite operation. fn link_from(d: &Descriptor, linked: bool) -> Mapped { - if *d == desc("null").with("null", target_ref("Lyr ")) { + // The reference permits normalizing the top-level descriptor class to null. + if d.items == desc("null").with("null", target_ref("Lyr ")).items { step("layer.linkLayers", json!({"linked": linked})) } else { Mapped::Unsupported { harmless: false } @@ -190,6 +191,38 @@ fn link_to(p: &Value, linked: bool) -> Option { (p.len() == 1 && p.get("linked") == Some(&Value::Bool(linked))).then(|| desc("null").with("null", target_ref("Lyr "))) } +fn smart_path_from(d: &Descriptor, id: &str) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let key = if id == "layer.smartObjects.convertToLinked" { "Usng" } else { "null" }; + let Some(path) = d.get(key).and_then(path_text) else { return unsupported }; + let p = json!({"path": path}); + let Some(mut expected) = smart_path_to(id, &p) else { return unsupported }; + if let Some(hint) = d.get("LyrI") { + // The reference explicitly omits recording-session IDs on save (#10603, + // docs/atn.md:200). They must never become PhotoCraft's playback target. + if !matches!(id, "layer.smartObjects.relinkToFile" | "layer.smartObjects.replaceContents") || !matches!(hint, D::Integer(n) if *n > 0) { + return unsupported; + } + expected = expected.with("LyrI", hint.clone()); + } + // Normalize the top-level header as Open/Place do, but refuse unknown keys, + // targets and path encodings rather than partly replaying them. + if d.items == expected.items { step(id, p) } else { unsupported } +} + +fn smart_path_to(id: &str, p: &Value) -> Option { + let p = p.as_object()?; + let path = p.get("path")?.as_str()?; + if p.len() != 1 || path.is_empty() || path.contains('\0') { + return None; + } + Some(if id == "layer.smartObjects.convertToLinked" { + desc("null").with("null", target_ref("Lyr ")).with("Usng", path_value(path)) + } else { + desc("null").with("null", path_value(path)) + }) +} + /// A clipping mask event: `clipping_from` / `clipping_to` with one command id. macro_rules! clipping_event { ($code:literal, $name:literal, $label:literal, $id:literal) => { @@ -496,6 +529,38 @@ pub(super) const EVENTS: &[Event] = &[ ev!("", "newPlacedLayer", "Convert to Smart Object", "layer.smartObjects.convertToSmartObject", &[]), ev!("", "placedLayerEditContents", "Edit Contents", "layer.smartObjects.editContents", &[]), ev!("", "updatePlacedLayer", "Update Smart Objects", "layer.smartObjects.updateModifiedContent", &[]), + Event { + code: "", + name: "placedLayerExportContents", + label: "Export Contents", + ids: &["layer.smartObjects.exportContents"], + from: |d| smart_path_from(d, "layer.smartObjects.exportContents"), + to: smart_path_to, + }, + Event { + code: "", + name: "placedLayerConvertToLinked", + label: "Convert to Linked", + ids: &["layer.smartObjects.convertToLinked"], + from: |d| smart_path_from(d, "layer.smartObjects.convertToLinked"), + to: smart_path_to, + }, + Event { + code: "", + name: "placedLayerRelinkToFile", + label: "Relink to File", + ids: &["layer.smartObjects.relinkToFile"], + from: |d| smart_path_from(d, "layer.smartObjects.relinkToFile"), + to: smart_path_to, + }, + Event { + code: "", + name: "placedLayerReplaceContents", + label: "Replace Contents", + ids: &["layer.smartObjects.replaceContents"], + from: |d| smart_path_from(d, "layer.smartObjects.replaceContents"), + to: smart_path_to, + }, Event { code: "Hd ", name: "hide", label: "Hide", ids: &["layer.hideLayers"], from: |d| visibility_from(d, "layer.hideLayers"), to: visibility_to }, Event { code: "Shw ", name: "show", label: "Show", ids: &["layer.showLayers"], from: |d| visibility_from(d, "layer.showLayers"), to: visibility_to }, Event { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 8680429482..5975f03bc1 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -621,6 +621,10 @@ fn every_mapped_command_exports_and_imports_back() { ("layer.smartObjects.convertToSmartObject", json!({})), ("layer.smartObjects.editContents", json!({})), ("layer.smartObjects.updateModifiedContent", json!({})), + ("layer.smartObjects.exportContents", json!({"path": "/tmp/contents.png"})), + ("layer.smartObjects.convertToLinked", json!({"path": "/tmp/linked.png"})), + ("layer.smartObjects.relinkToFile", json!({"path": "/tmp/relinked.png"})), + ("layer.smartObjects.replaceContents", json!({"path": "/tmp/replacement.png"})), ("paint.bucket", json!({"x": 10, "y": 20, "tolerance": 32, "antiAlias": true, "contiguous": false, "opacity": 100})), ("image.imageSize", json!({"percent": 200, "resample": "bicubicAutomatic"})), ("file.placeEmbedded", json!({"path": "/tmp/logo.png", "scale": 50})), diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 5b56235657..a4cf68bb2c 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -1,5 +1,5 @@ //! #10700: recorded Link and Unlink must not replay as a state-dependent toggle. -use photocraft_doc::{Layer, LayerId}; +use photocraft_doc::{Layer, LayerContent, LayerId, SmartObject, SmartSource}; use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; use photocraft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, @@ -32,8 +32,12 @@ fn groups(s: &Session) -> Vec> { } fn target() -> D { + target_class("Lyr ") +} + +fn target_class(class_id: &str) -> D { D::Reference(vec![ReferenceItem::Enumerated { - class: Class { name: UnicodeString::new_nul(""), class_id: Id::new("Lyr ") }, + class: Class { name: UnicodeString::new_nul(""), class_id: Id::new(class_id) }, type_id: Id::new("Ordn"), value: Id::new("Trgt"), }]) @@ -57,6 +61,12 @@ fn load(s: &mut Session, bytes: &[u8]) -> serde_json::Value { s.execute("actions.load", json!({"data": photocraft_engine::paint::tile::b64_encode(bytes)})).unwrap() } +fn play(s: &mut Session) { + let report = s.execute("actions.play", json!({"action": "A", "set": "Links"})).unwrap(); + assert!(report.get("failed").is_none(), "{report}"); + assert_eq!(report["ran"], 1, "{report}"); +} + #[test] fn explicit_links_are_idempotent_and_omitted_state_still_toggles() { let mut s = fixture(&[None, None], &[0, 1]); @@ -138,7 +148,7 @@ fn atn_link_events_keep_descriptors_and_replay_the_requested_operation() { assert_eq!(parsed.actions[0].items[0].descriptor, Some(descriptor)); let mut replay = fixture(&initial, &[0, 1]); assert_eq!(load(&mut replay, &bytes)["unsupported"], json!([])); - replay.execute("actions.play", json!({"action": "A", "set": "Links"})).unwrap(); + play(&mut replay); if linked { let result = groups(&replay); assert!(result[0].is_some()); @@ -149,7 +159,7 @@ fn atn_link_events_keep_descriptors_and_replay_the_requested_operation() { } let before = replay.active().unwrap().doc.clone(); let history = replay.active().unwrap().history.past_len(); - replay.execute("actions.play", json!({"action": "A", "set": "Links"})).unwrap(); + play(&mut replay); assert_eq!(replay.active().unwrap().doc, before); assert_eq!(replay.active().unwrap().history.past_len(), history); } @@ -162,7 +172,7 @@ fn unsupported_link_descriptors_are_kept_and_ambiguous_exports_are_refused() { for descriptor in [ Descriptor::new("null"), Descriptor::new("null").with("null", D::Integer(1)), - Descriptor::new("other").with("null", target()), + Descriptor::new("null").with("null", target_class("Dcmn")), Descriptor::new("null").with("null", target()).with("extra", D::Boolean(true)), Descriptor::new("null").with("null", target()).with("null", target()), ] { @@ -180,3 +190,179 @@ fn unsupported_link_descriptors_are_kept_and_ambiguous_exports_are_refused() { assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); } } + +#[test] +fn link_descriptor_headers_normalize_without_changing_meaningful_keys() { + for event in ["linkSelectedLayers", "unlinkSelectedLayers"] { + let mut s = Session::new(); + let descriptor = Descriptor::new(event).with("null", target()); + assert_eq!(load(&mut s, &file(event, descriptor))["unsupported"], json!([])); + let saved = s.execute("actions.save", json!({"set": "Links"})).unwrap(); + let bytes = photocraft_engine::paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + let parsed = atn::parse(&bytes).unwrap(); + assert_eq!(parsed.actions[0].items[0].event, AtnEvent::name(event)); + assert_eq!(parsed.actions[0].items[0].descriptor, Some(Descriptor::new("null").with("null", target()))); + } +} + +const SMART_PATHS: &[(&str, &str)] = &[ + ("placedLayerExportContents", "layer.smartObjects.exportContents"), + ("placedLayerConvertToLinked", "layer.smartObjects.convertToLinked"), + ("placedLayerRelinkToFile", "layer.smartObjects.relinkToFile"), + ("placedLayerReplaceContents", "layer.smartObjects.replaceContents"), +]; + +fn path_value(path: &str) -> D { + let units: Vec<_> = path.encode_utf16().chain(std::iter::once(0)).collect(); + let mut bytes = b"txtu".to_vec(); + bytes.extend_from_slice(&u32::try_from(12 + units.len() * 2).unwrap().to_le_bytes()); + bytes.extend_from_slice(&u32::try_from(units.len()).unwrap().to_le_bytes()); + bytes.extend(units.iter().flat_map(|unit| unit.to_le_bytes())); + D::Path(bytes) +} + +fn smart_path_descriptor(event: &str, path: &str) -> Descriptor { + if event == "placedLayerConvertToLinked" { + Descriptor::new("null").with("null", target()).with("Usng", path_value(path)) + } else { + Descriptor::new("null").with("null", path_value(path)) + } +} + +fn png(color: &str) -> Vec { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "background": color})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "png", &Default::default()).unwrap().bytes +} + +fn smart_fixture(bytes: &[u8]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + photocraft_engine::file_cmds::place_bytes(&mut s, "original.png", bytes.to_vec(), None, &json!({})).unwrap(); + s +} + +fn active_smart(s: &Session) -> &SmartObject { + let st = s.active().unwrap(); + let LayerContent::Smart(smart) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("expected a Smart Object") }; + smart +} + +fn assert_smart_file_output(event: &str, s: &Session, path: &str, original: &[u8], replacement: &[u8]) { + match event { + "placedLayerExportContents" => assert_eq!(std::fs::read(path).unwrap().as_slice(), original), + "placedLayerConvertToLinked" => { + assert_eq!(std::fs::read(path).unwrap().as_slice(), original); + assert!(matches!(&active_smart(s).source, SmartSource::Linked { path: actual } if actual == path)); + } + "placedLayerRelinkToFile" => assert!(matches!(&active_smart(s).source, SmartSource::Linked { path: actual } if actual == path)), + "placedLayerReplaceContents" => { + assert!(matches!(&active_smart(s).source, SmartSource::Embedded { bytes, .. } if bytes.as_slice() == replacement)); + } + _ => unreachable!(), + } +} + +#[test] +fn smart_paths_roundtrip_and_play_real_files_on_the_current_target() { + let original = png("#0000ff"); + let replacement = png("#ff0000"); + for &(event, id) in SMART_PATHS { + for header in ["null", event] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("contents Ω.png"); + let path = path.to_str().unwrap(); + let replacing = matches!(event, "placedLayerRelinkToFile" | "placedLayerReplaceContents"); + if replacing { + std::fs::write(path, &replacement).unwrap(); + } + let canonical = smart_path_descriptor(event, path); + let mut recorded = canonical.clone(); + recorded.class_id = Id::new(header); + let mut s = smart_fixture(&original); + if replacing { + let hint = i32::MAX; + assert!(s.active().unwrap().doc.walk().iter().all(|(_, _, layer)| layer.id.0 != hint as u64)); + recorded = recorded.with("LyrI", D::Integer(hint)); + } + assert_eq!(load(&mut s, &file(event, recorded))["unsupported"], json!([]), "{event}"); + assert_eq!(s.actions.list[0].steps, [(id.to_string(), json!({"path": path}))]); + let saved = s.execute("actions.save", json!({"set": "Links"})).unwrap(); + assert_eq!(saved["skipped"], json!([])); + let bytes = photocraft_engine::paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + let parsed = atn::parse(&bytes).unwrap(); + assert_eq!(parsed.actions[0].items[0].event, AtnEvent::name(event)); + // Reference #10603, docs/atn.md:197–201: normalize the descriptor class, + // and omit session LyrI. All meaningful event/path keys remain identical. + assert_eq!(parsed.actions[0].items[0].descriptor, Some(canonical)); + assert_eq!(load(&mut s, &bytes)["unsupported"], json!([])); + let before = s.active().unwrap().doc.clone(); + let before_smart = active_smart(&s).clone(); + play(&mut s); + assert_eq!(active_smart(&s).transform, before_smart.transform); + assert_smart_file_output(event, &s, path, &original, &replacement); + if replacing { + assert!(photocraft_compose::flatten(&s.active().unwrap().doc).px.iter().all(|px| *px == [1.0, 0.0, 0.0, 1.0])); + } + if event == "placedLayerExportContents" { + assert_eq!(s.active().unwrap().doc, before); + } else { + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } + } + } +} + +#[test] +fn smart_paths_keep_missing_unusable_and_unrepresented_descriptors_whole() { + for &(event, _) in SMART_PATHS { + let key = if event == "placedLayerConvertToLinked" { "Usng" } else { "null" }; + for descriptor in [ + Descriptor::new("null"), + Descriptor::new("null").with(key, path_value("")), + Descriptor::new("null").with(key, path_value("a\0b")), + Descriptor::new("null").with(key, D::Text(UnicodeString::new("/tmp/file.png"))), + Descriptor::new("null").with(key, D::Path(b"txtu".to_vec())), + Descriptor::new("null").with("Usng", path_value("/tmp/file.png")), + smart_path_descriptor(event, "/tmp/file.png").with("extra", D::Integer(1)), + smart_path_descriptor(event, "/tmp/file.png").with("LyrI", D::Boolean(true)), + smart_path_descriptor(event, "/tmp/file.png").with("LyrI", D::Integer(-1)), + smart_path_descriptor(event, "/tmp/file.png").with("LyrI", D::LargeInteger(i64::from(i32::MAX) + 1)), + ] { + let mut s = Session::new(); + assert_eq!(load(&mut s, &file(event, descriptor.clone()))["unsupported"].as_array().unwrap().len(), 1); + let saved = s.execute("actions.save", json!({"set": "Links"})).unwrap(); + let bytes = photocraft_engine::paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0].descriptor, Some(descriptor)); + } + } +} + +#[test] +fn smart_path_exports_refuse_unrepresentable_native_params() { + for &(_, id) in SMART_PATHS { + for params in [json!({}), json!({"path": ""}), json!({"path": "a\0b"}), json!({"path": 3}), json!({"path": "/tmp/a.png", "layer": 1})] { + let action = Action::new("A", vec![(id.into(), params)]); + assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); + } + } +} + +#[test] +fn unusable_smart_file_at_playback_fails_without_changing_the_document() { + let original = png("#0000ff"); + let dir = tempfile::tempdir().unwrap(); + for &(event, id) in SMART_PATHS { + let mut s = smart_fixture(&original); + assert_eq!(load(&mut s, &file(event, smart_path_descriptor(event, dir.path().to_str().unwrap())))["unsupported"], json!([])); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let report = s.execute("actions.play", json!({"action": "A", "set": "Links"})).unwrap(); + assert_eq!(report["ran"], 0, "{event}: {report}"); + assert_eq!(report["failed"]["id"], id, "{event}: {report}"); + assert!(report["failed"]["error"].as_str().is_some_and(|error| !error.is_empty()), "{event}: {report}"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } +} diff --git a/docs/atn.md b/docs/atn.md index c0a836a735..727a5c30c6 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -15,3 +15,24 @@ Omitting `linked` retains the native UI toggle. That ambiguous toggle cannot be saved as either Photoshop event. Explicit layer lists and extra parameters also cannot be saved as these events. Unsupported targets or extra descriptor keys are kept as Photoshop steps for lossless saving, rather than partially replayed. + +## Smart Object file operations + +| Photoshop event | Meaningful descriptor keys | PhotoCraft command | +| --- | --- | --- | +| `placedLayerExportContents` | `null`: path | `layer.smartObjects.exportContents` | +| `placedLayerConvertToLinked` | `null`: target layer; `Usng`: path | `layer.smartObjects.convertToLinked` | +| `placedLayerRelinkToFile` | `null`: path | `layer.smartObjects.relinkToFile` | +| `placedLayerReplaceContents` | `null`: path | `layer.smartObjects.replaceContents` | + +The path uses the same `Pth `/`txtu` encoding as Open and Place. Missing, +undecodable or unrepresented path options are kept as complete Photoshop steps. +Native steps aimed at explicit layers or carrying extra options cannot be saved +as these targeted events. File access occurs during playback through the native +command; a missing or unusable file produces that command's error. + +The reference explicitly permits normalizing the top-level descriptor class to +`null` and omitting recording-session IDs on save. Relink and Replace accept a +recorded integer `LyrI` as a session hint; it does not select a PhotoCraft layer. +Playback operates on the current Smart Object. The hint is omitted on save, +while the event, path and other meaningful keys are retained.