From 5881923406a06181351d07fa6a3e9de1783622e1 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 12:49:47 -0800 Subject: [PATCH 01/12] fix(engine): replay recorded link and unlink explicitly --- crates/engine/src/cmd/atn_cmds/events.rs | 26 ++- crates/engine/src/cmd/atn_cmds/tests.rs | 2 + crates/engine/src/cmd/layer_multi_cmds.rs | 12 +- .../src/cmd/layer_multi_cmds/structure.rs | 23 ++- crates/engine/src/session/execute.rs | 6 + crates/engine/tests/it/atn_newer_events.rs | 182 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + docs/atn.md | 17 ++ 8 files changed, 260 insertions(+), 9 deletions(-) create mode 100644 crates/engine/tests/it/atn_newer_events.rs create mode 100644 docs/atn.md diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 5723c93c59..67e1aeae75 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}; +use super::descriptors::{desc, get_bool, get_ref, jbool, layer_ref, layer_target, 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, @@ -175,6 +175,21 @@ fn clipping_to(_: &str, p: &Value) -> Option { Some(desc("null").with("null", layer_ref(p)?)) } +// 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 ")) { + step("layer.linkLayers", json!({"linked": linked})) + } else { + Mapped::Unsupported { harmless: false } + } +} + +fn link_to(p: &Value, linked: bool) -> Option { + let p = p.as_object()?; + (p.len() == 1 && p.get("linked") == Some(&Value::Bool(linked))).then(|| desc("null").with("null", target_ref("Lyr "))) +} + /// A clipping mask event: `clipping_from` / `clipping_to` with one command id. macro_rules! clipping_event { ($code:literal, $name:literal, $label:literal, $id:literal) => { @@ -353,6 +368,15 @@ pub(super) const EVENTS: &[Event] = &[ }, Event { code: "Dplc", name: "duplicate", label: "Duplicate", ids: &["layer.duplicate", "image.duplicate"], from: duplicate_from, to: duplicate_to }, // Layers. + Event { code: "", name: "linkSelectedLayers", label: "Link Layers", ids: &["layer.linkLayers"], from: |d| link_from(d, true), to: |_, p| link_to(p, true) }, + Event { + code: "", + name: "unlinkSelectedLayers", + label: "Unlink Layers", + ids: &["layer.linkLayers"], + from: |d| link_from(d, false), + to: |_, p| link_to(p, false), + }, Event { code: "Mk ", name: "make", diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index f9e633244c..8680429482 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -548,6 +548,8 @@ fn every_mapped_command_exports_and_imports_back() { ("layer.new.layer", json!({"name": "Ink", "opacity": 0.5, "mode": "Multiply"})), ("layer.new.group", json!({"name": "G"})), ("layer.groupLayers", json!({})), + ("layer.linkLayers", json!({"linked": true})), + ("layer.linkLayers", json!({"linked": false})), ("layer.new.layerViaCopy", json!({})), ("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("layer.newAdjustmentLayer.hueSaturation", json!({})), diff --git a/crates/engine/src/cmd/layer_multi_cmds.rs b/crates/engine/src/cmd/layer_multi_cmds.rs index 79abb250a3..ada040e8b7 100644 --- a/crates/engine/src/cmd/layer_multi_cmds.rs +++ b/crates/engine/src/cmd/layer_multi_cmds.rs @@ -134,9 +134,15 @@ pub fn specs() -> Vec { s, "vertically" )), - spec!("layer.linkLayers", "Link Layers", &["Layer"], None, "{} (toggles: unlinks when the selection is already one link group)", can_link, |s, _| { - link_layers(s) - }), + spec!( + "layer.linkLayers", + "Link Layers", + &["Layer"], + None, + r#"{"linked":bool?} (omitted: toggle; explicit true links, false unlinks)"#, + can_link, + link_layers + ), spec!("layer.mergeLayers", "Merge Layers", &["Layer"], Some("Cmd+E"), "{} (one layer selected: Merge Down)", has_layer, |s, _| merge_layers(s)), spec!( "layer.new.groupFromLayers", diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index 70aa512223..c52f7a3a1d 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -3,13 +3,26 @@ use super::{Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, Re // ---------- structural commands ---------- -pub(super) fn link_layers(s: &mut Session) -> Result { +pub(super) fn link_layers(s: &mut Session, p: &Value) -> Result { + let requested = match p.get("linked") { + None => None, + Some(Value::Bool(value)) => Some(*value), + Some(_) => return Err(bad("layer.linkLayers", "`linked` must be true or false")), + }; let sel = selected(s); - let linked = s.edit("Link Layers", |doc, _| { - let groups: Vec> = sel.iter().map(|id| doc.layer(*id).and_then(|l| l.link_group)).collect(); + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let groups = sel.iter().map(|id| doc.layer(*id).map(|l| l.link_group).ok_or(EngineError::NoLayer(*id))).collect::>>()?; + let first = groups.first().copied().flatten(); + let same_group = first.is_some() && groups.iter().all(|group| *group == first); + // A recorded Link/Unlink is an operation, not the UI's state-dependent toggle. + // An explicit repeat must neither allocate a group nor add an undo entry. + if requested == Some(true) && same_group || requested == Some(false) && groups.iter().all(Option::is_none) { + return Ok(json!({"linked": requested == Some(true)})); + } + let label = if requested == Some(false) { "Unlink Layers" } else { "Link Layers" }; + let linked = s.edit(label, |doc, _| { // Already one link group (or a single linked layer): unlink, like Photoshop's toggle. - let first = groups.first().copied().flatten(); - let unlink = first.is_some() && groups.iter().all(|g| *g == first); + let unlink = requested.map_or(same_group, |linked| !linked); // A loaded file can store any id up to u64::MAX, so the new id must not be a bare // max + 1 (#961). Unlinking needs no new id at all. let next = if unlink { None } else { Some(doc.unused_link_group().ok_or_else(|| bad("layer.linkLayers", "no free link group id is left"))?) }; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 2c7ef1ba1c..32eb2c6197 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -150,6 +150,12 @@ impl Session { if spec.id == "layer.smartFilter.deleteFilterMask" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { return smart_cmds::smart_layer_active(self); } + // Recorded Unlink can be repeated on a single, already-unlinked layer. + // Keep the menu toggle's two-layer requirement when no state is supplied. + if spec.id == "layer.linkLayers" && params.get("linked").and_then(Value::as_bool) == Some(false) { + let d = self.active().ok_or_else(|| "no document open".to_string())?; + return if d.selected_layers().is_empty() { Err("no layer selected".into()) } else { Ok(()) }; + } channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) } diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs new file mode 100644 index 0000000000..5b56235657 --- /dev/null +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -0,0 +1,182 @@ +//! #10700: recorded Link and Unlink must not replay as a state-dependent toggle. +use photocraft_doc::{Layer, LayerId}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; +use photocraft_psd::{ + atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, + descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, +}; +use serde_json::json; +use std::sync::Arc; + +fn fixture(groups: &[Option], selected: &[usize]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 2})).unwrap(); + let st = s.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + doc.layers = groups + .iter() + .enumerate() + .map(|(i, group)| { + let mut layer = Layer::raster(format!("Layer {i}"), doc.pixel_format()); + layer.link_group = *group; + layer + }) + .collect(); + let ids: Vec<_> = selected.iter().map(|i| doc.layers[*i].id).collect(); + s.restore_layer_selection(ids.last().copied(), &ids, ids.first().copied()).unwrap(); + s +} + +fn groups(s: &Session) -> Vec> { + s.active().unwrap().doc.layers.iter().map(|layer| layer.link_group).collect() +} + +fn target() -> D { + D::Reference(vec![ReferenceItem::Enumerated { + class: Class { name: UnicodeString::new_nul(""), class_id: Id::new("Lyr ") }, + type_id: Id::new("Ordn"), + value: Id::new("Trgt"), + }]) +} + +fn file(event: &str, descriptor: Descriptor) -> Vec { + atn::write(&AtnFile { + name: UnicodeString::new_nul("Links"), + expanded: false, + actions: vec![AtnAction { + name: UnicodeString::new_nul("A"), + items: vec![AtnItem { event: AtnEvent::name(event), descriptor: Some(descriptor), ..Default::default() }], + ..Default::default() + }], + warnings: vec![], + }) + .unwrap() +} + +fn load(s: &mut Session, bytes: &[u8]) -> serde_json::Value { + s.execute("actions.load", json!({"data": photocraft_engine::paint::tile::b64_encode(bytes)})).unwrap() +} + +#[test] +fn explicit_links_are_idempotent_and_omitted_state_still_toggles() { + let mut s = fixture(&[None, None], &[0, 1]); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + s.execute("layer.linkLayers", json!({"linked": false})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + s.execute("layer.linkLayers", json!({"linked": true})).unwrap(); + let linked = s.active().unwrap().doc.clone(); + assert!(groups(&s)[0].is_some()); + assert_eq!(groups(&s)[0], groups(&s)[1]); + let history = s.active().unwrap().history.past_len(); + s.execute("layer.linkLayers", json!({"linked": true})).unwrap(); + assert_eq!(s.active().unwrap().doc, linked); + assert_eq!(s.active().unwrap().history.past_len(), history); + s.execute("layer.linkLayers", json!({})).unwrap(); + assert_eq!(groups(&s), [None, None]); + s.execute("layer.linkLayers", json!({})).unwrap(); + assert!(groups(&s).iter().all(Option::is_some)); +} + +#[test] +fn unlink_cleans_singletons_preserves_other_groups_and_undoes() { + for initial in [vec![Some(77), Some(77), Some(77), Some(93), Some(93)], vec![Some(77), None, Some(77), Some(93), Some(93)]] { + let mut s = fixture(&initial, &[0, 1]); + let before = s.active().unwrap().doc.clone(); + s.execute("layer.linkLayers", json!({"linked": false})).unwrap(); + assert_eq!(groups(&s), [None, None, None, Some(93), Some(93)]); + let history = s.active().unwrap().history.past_len(); + s.execute("layer.linkLayers", json!({"linked": false})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } + let mut one = fixture(&[Some(77), Some(77)], &[0]); + one.execute("layer.linkLayers", json!({"linked": false})).unwrap(); + assert_eq!(groups(&one), [None, None]); + let history = one.active().unwrap().history.past_len(); + one.execute("layer.linkLayers", json!({"linked": false})).unwrap(); + assert_eq!(one.active().unwrap().history.past_len(), history); + assert!(!one.is_enabled("layer.linkLayers"), "the UI toggle still requires two unlinked layers"); +} + +#[test] +fn invalid_link_state_fails_without_editing() { + let mut s = fixture(&[None, None], &[0, 1]); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + for invalid in [json!(null), json!("false"), json!(0), json!([]), json!({})] { + assert!(s.execute("layer.linkLayers", json!({"linked": invalid})).is_err()); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + for active in [None, Some(LayerId(u64::MAX))] { + let st = s.active_mut().unwrap(); + st.active_layer = active; + st.selected_layers = active.into_iter().collect(); + assert!(s.execute("layer.linkLayers", json!({"linked": false})).is_err()); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + assert!(Session::new().execute("layer.linkLayers", json!({"linked": false})).is_err()); +} + +#[test] +fn atn_link_events_keep_descriptors_and_replay_the_requested_operation() { + for (event, linked) in [("linkSelectedLayers", true), ("unlinkSelectedLayers", false)] { + for initial in [vec![None, None, None, Some(93), Some(93)], vec![Some(77), Some(77), Some(77), Some(93), Some(93)]] { + let descriptor = Descriptor::new("null").with("null", target()); + let mut s = fixture(&initial, &[0, 1]); + assert_eq!(load(&mut s, &file(event, descriptor.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps, [("layer.linkLayers".into(), json!({"linked": linked}))]); + 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)); + 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(); + if linked { + let result = groups(&replay); + assert!(result[0].is_some()); + assert_eq!(result[0], result[1]); + assert_eq!(&result[2..], &[initial[2], Some(93), Some(93)]); + } else { + assert_eq!(groups(&replay), [None, None, None, Some(93), Some(93)]); + } + 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(); + assert_eq!(replay.active().unwrap().doc, before); + assert_eq!(replay.active().unwrap().history.past_len(), history); + } + } +} + +#[test] +fn unsupported_link_descriptors_are_kept_and_ambiguous_exports_are_refused() { + for event in ["linkSelectedLayers", "unlinkSelectedLayers"] { + 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()).with("extra", D::Boolean(true)), + Descriptor::new("null").with("null", target()).with("null", target()), + ] { + 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(); + 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)); + } + } + for params in [json!({}), json!({"linked": null}), json!({"linked": true, "layer": "Layer 0"}), json!({"linked": false, "layers": [1, 2]})] { + let action = Action::new("A", vec![("layer.linkLayers".into(), params)]); + assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f6a8360a4f..0535f2e96b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -3,6 +3,7 @@ mod affinity; mod artboard_export_names; mod atn_crystallize_cell_size; +mod atn_newer_events; mod atn_ripple_amount; mod atn_selective_color; mod atn_stroke_width; diff --git a/docs/atn.md b/docs/atn.md new file mode 100644 index 0000000000..c0a836a735 --- /dev/null +++ b/docs/atn.md @@ -0,0 +1,17 @@ +# Photoshop action files + +## Targeted layer links + +| Photoshop event | Descriptor | PhotoCraft command | +| --- | --- | --- | +| `linkSelectedLayers` | `null`: layer target (`Lyr `/`Ordn.Trgt`) | `layer.linkLayers {"linked":true}` | +| `unlinkSelectedLayers` | `null`: layer target (`Lyr `/`Ordn.Trgt`) | `layer.linkLayers {"linked":false}` | + +These events act on the current layer selection. Link keeps an already linked +selection linked; Unlink keeps an already unlinked selection unlinked. Unlink +also clears a link group left with only one member. Undo restores the edit. + +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. From b4c7656c49d60e0cd61de9efef3650386da83bbc Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 13:09:16 -0800 Subject: [PATCH 02/12] 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. From 71b98c813421decd855880eb2d613fc78531fc7f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 13:36:08 -0800 Subject: [PATCH 03/12] feat(engine): replay target-only ATN menu events --- crates/engine/src/cmd/atn_cmds/events.rs | 78 +++++- crates/engine/src/cmd/atn_cmds/tests.rs | 16 ++ crates/engine/tests/it/atn_newer_events.rs | 270 ++++++++++++++++++++- docs/atn.md | 28 +++ 4 files changed, 380 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 0e04fb85df..cca7d2d69c 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -17,7 +17,7 @@ use super::steps_layer::{ }; use super::steps_make::{locking_from, locking_to, make_from, make_to, set_from, set_to}; use super::tables::{NOISE, OFFSET_FILL, SMART_BLUR_MODE, SMART_BLUR_QUALITY, TRIM}; -use super::{AtnEvent, D, Descriptor, STOP_MESSAGE, Value, json}; +use super::{AtnEvent, D, Descriptor, Map, STOP_MESSAGE, Value, json}; /// An event: code (empty when Photoshop only has a string name), string name, the panel /// label, the command ids it exports (the first is the one simple events import to), and the @@ -175,20 +175,57 @@ fn clipping_to(_: &str, p: &Value) -> Option { Some(desc("null").with("null", layer_ref(p)?)) } -// 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 { - // 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 } +// Adapter-only transport bit: the reference permits either no target key or the +// current-layer target. Save must retain that distinction; native behavior is identical. +const NO_TARGET: &str = "_atnNoTarget"; + +fn target_params(d: &Descriptor) -> Option> { + let mut p = Map::new(); + if d.items.is_empty() { + p.insert(NO_TARGET.into(), Value::Bool(true)); + } else if d.items != desc("null").with("null", target_ref("Lyr ")).items { + return None; + } + Some(p) +} + +fn target_descriptor(p: &Value) -> Option { + match p.get(NO_TARGET) { + None => Some(desc("null").with("null", target_ref("Lyr "))), + Some(Value::Bool(true)) => Some(desc("null")), + Some(_) => None, } } +// Native-parameter allowlist adapted from #10628; refuse unrepresented options on export. +fn params(p: &Value, allowed: &[&str]) -> bool { + p.as_object().is_some_and(|p| p.keys().all(|key| allowed.contains(&key.as_str()))) +} + +fn target_only_from(d: &Descriptor, id: &str) -> Mapped { + target_params(d).map_or(Mapped::Unsupported { harmless: false }, |p| step(id, Value::Object(p))) +} + +fn target_only_to(_: &str, p: &Value) -> Option { + if !params(p, &[NO_TARGET]) { + return None; + } + target_descriptor(p) +} + +// Recorded Link and Unlink need explicit state: replaying the UI toggle can +// perform the opposite operation. Target matching follows #10628's adapter. +fn link_from(d: &Descriptor, linked: bool) -> Mapped { + let Some(mut p) = target_params(d) else { return Mapped::Unsupported { harmless: false } }; + p.insert("linked".into(), Value::Bool(linked)); + step("layer.linkLayers", Value::Object(p)) +} + fn link_to(p: &Value, linked: bool) -> Option { - let p = p.as_object()?; - (p.len() == 1 && p.get("linked") == Some(&Value::Bool(linked))).then(|| desc("null").with("null", target_ref("Lyr "))) + if !params(p, &["linked", NO_TARGET]) || p.get("linked") != Some(&Value::Bool(linked)) { + return None; + } + target_descriptor(p) } fn smart_path_from(d: &Descriptor, id: &str) -> Mapped { @@ -230,6 +267,12 @@ macro_rules! clipping_event { }; } +macro_rules! target_event { + ($name:literal, $label:literal, $id:literal) => { + Event { code: "", name: $name, label: $label, ids: &[$id], from: |d| target_only_from(d, $id), to: target_only_to } + }; +} + /// Every Photoshop event PhotoCraft maps. The order matters only for the panel label. pub(super) const EVENTS: &[Event] = &[ // Filters. @@ -401,6 +444,15 @@ pub(super) const EVENTS: &[Event] = &[ }, Event { code: "Dplc", name: "duplicate", label: "Duplicate", ids: &["layer.duplicate", "image.duplicate"], from: duplicate_from, to: duplicate_to }, // Layers. + target_event!("reverse", "Reverse", "layer.arrange.reverse"), + target_event!("selectLinkedLayers", "Select Linked Layers", "layer.selectLinkedLayers"), + target_event!("disableLayerStyle", "Clear Layer Style", "layer.layerStyle.clear"), + target_event!("rasterizeAll", "Rasterize All Layers", "layer.rasterize.allLayers"), + target_event!("addBlankVideoLayer", "New Blank Video Layer", "layer.videoLayers.newBlankVideoLayer"), + target_event!("isolateLayers", "Isolate Layers", "select.isolateLayers"), + target_event!("textLoadDefaultTypeStyles", "Load Default Type Styles", "type.loadDefaultTypeStyles"), + target_event!("textSaveDefaultTypeStyles", "Save Default Type Styles", "type.saveDefaultTypeStyles"), + target_event!("recordMeasurements", "Record Measurements", "image.analysis.recordMeasurements"), Event { code: "", name: "linkSelectedLayers", label: "Link Layers", ids: &["layer.linkLayers"], from: |d| link_from(d, true), to: |_, p| link_to(p, true) }, Event { code: "", @@ -529,6 +581,10 @@ 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", &[]), + target_event!("placedLayerMakeCopy", "New Smart Object via Copy", "layer.smartObjects.newSmartObjectViaCopy"), + target_event!("placedLayerConvertToLayers", "Convert to Layers", "layer.smartObjects.convertToLayers"), + target_event!("placedLayerConvertToEmbedded", "Convert to Embedded", "layer.smartObjects.convertToEmbedded"), + target_event!("placedLayerUpdateAllModified", "Update All Modified Content", "layer.smartObjects.updateAllModifiedContent"), Event { code: "", name: "placedLayerExportContents", diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 5975f03bc1..965399241c 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -550,6 +550,18 @@ fn every_mapped_command_exports_and_imports_back() { ("layer.groupLayers", json!({})), ("layer.linkLayers", json!({"linked": true})), ("layer.linkLayers", json!({"linked": false})), + ("layer.linkLayers", json!({"linked": true, "_atnNoTarget": true})), + ("layer.linkLayers", json!({"linked": false, "_atnNoTarget": true})), + ("layer.arrange.reverse", json!({})), + ("layer.arrange.reverse", json!({"_atnNoTarget": true})), + ("layer.selectLinkedLayers", json!({})), + ("layer.layerStyle.clear", json!({})), + ("layer.rasterize.allLayers", json!({})), + ("layer.videoLayers.newBlankVideoLayer", json!({})), + ("select.isolateLayers", json!({})), + ("type.loadDefaultTypeStyles", json!({})), + ("type.saveDefaultTypeStyles", json!({})), + ("image.analysis.recordMeasurements", json!({})), ("layer.new.layerViaCopy", json!({})), ("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("layer.newAdjustmentLayer.hueSaturation", json!({})), @@ -621,6 +633,10 @@ fn every_mapped_command_exports_and_imports_back() { ("layer.smartObjects.convertToSmartObject", json!({})), ("layer.smartObjects.editContents", json!({})), ("layer.smartObjects.updateModifiedContent", json!({})), + ("layer.smartObjects.newSmartObjectViaCopy", json!({})), + ("layer.smartObjects.convertToLayers", json!({})), + ("layer.smartObjects.convertToEmbedded", json!({})), + ("layer.smartObjects.updateAllModifiedContent", 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"})), diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index a4cf68bb2c..70db016186 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -170,7 +170,7 @@ fn atn_link_events_keep_descriptors_and_replay_the_requested_operation() { fn unsupported_link_descriptors_are_kept_and_ambiguous_exports_are_refused() { for event in ["linkSelectedLayers", "unlinkSelectedLayers"] { for descriptor in [ - Descriptor::new("null"), + Descriptor::new("null").with("null", D::Reference(vec![])), Descriptor::new("null").with("null", D::Integer(1)), Descriptor::new("null").with("null", target_class("Dcmn")), Descriptor::new("null").with("null", target()).with("extra", D::Boolean(true)), @@ -191,6 +191,274 @@ fn unsupported_link_descriptors_are_kept_and_ambiguous_exports_are_refused() { } } +const TARGET_EVENTS: &[(&str, &str)] = &[ + ("reverse", "layer.arrange.reverse"), + ("selectLinkedLayers", "layer.selectLinkedLayers"), + ("disableLayerStyle", "layer.layerStyle.clear"), + ("placedLayerMakeCopy", "layer.smartObjects.newSmartObjectViaCopy"), + ("placedLayerConvertToLayers", "layer.smartObjects.convertToLayers"), + ("placedLayerConvertToEmbedded", "layer.smartObjects.convertToEmbedded"), + ("placedLayerUpdateAllModified", "layer.smartObjects.updateAllModifiedContent"), + ("rasterizeAll", "layer.rasterize.allLayers"), + ("addBlankVideoLayer", "layer.videoLayers.newBlankVideoLayer"), + ("isolateLayers", "select.isolateLayers"), + ("textLoadDefaultTypeStyles", "type.loadDefaultTypeStyles"), + ("textSaveDefaultTypeStyles", "type.saveDefaultTypeStyles"), + ("recordMeasurements", "image.analysis.recordMeasurements"), +]; + +fn targeted(event: &str, explicit: bool) -> Descriptor { + let d = Descriptor::new(event); + if explicit { d.with("null", target()) } else { d } +} + +fn load_targeted(s: &mut Session, event: &str, id: &str, explicit: bool) { + assert_eq!(load(s, &file(event, targeted(event, explicit)))["unsupported"], json!([]), "{event}"); + let p = if explicit { json!({}) } else { json!({"_atnNoTarget": true}) }; + assert_eq!(s.actions.list[0].steps, [(id.into(), p)]); +} + +#[test] +fn target_events_keep_empty_and_explicit_target_descriptors_distinct() { + for &(event, id) in TARGET_EVENTS { + for explicit in [false, true] { + let mut s = Session::new(); + load_targeted(&mut s, event, id, explicit); + 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 item = &atn::parse(&bytes).unwrap().actions[0].items[0]; + assert_eq!(item.event, AtnEvent::name(event)); + assert_eq!(item.descriptor, Some(targeted("null", explicit)), "{event}"); + assert_eq!(load(&mut s, &bytes)["unsupported"], json!([])); + } + } + // Reference lines197–199 permits writing an empty descriptor for an absent one. + let mut f = atn::parse(&file("reverse", Descriptor::new("null"))).unwrap(); + f.actions[0].items[0].descriptor = None; + let mut s = Session::new(); + assert_eq!(load(&mut s, &atn::write(&f).unwrap())["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(); + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0].descriptor, Some(Descriptor::new("null"))); +} + +#[test] +fn bare_link_events_keep_their_operation_and_empty_keys() { + for (event, linked) in [("linkSelectedLayers", true), ("unlinkSelectedLayers", false)] { + let initial = if linked { None } else { Some(77) }; + let mut s = fixture(&[initial, initial], &[0, 1]); + assert_eq!(load(&mut s, &file(event, Descriptor::new(event)))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].1, json!({"linked": linked, "_atnNoTarget": true})); + 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::new("null"))); + let before = s.active().unwrap().doc.clone(); + play(&mut s); + assert_ne!(s.active().unwrap().doc, before); + let after = s.active().unwrap().doc.clone(); + assert!(groups(&s).iter().all(|group| group.is_some() == linked)); + assert_eq!(groups(&s)[0], groups(&s)[1]); + play(&mut s); + assert_eq!(s.active().unwrap().doc, after); + } +} + +#[test] +fn target_events_keep_unknown_targets_and_refuse_native_options() { + for &(event, id) in TARGET_EVENTS { + for descriptor in [ + Descriptor::new(event).with("null", D::Integer(1)), + Descriptor::new(event).with("null", target_class("Dcmn")), + targeted(event, true).with("null", target()), + targeted(event, true).with("extra", D::Boolean(true)), + ] { + 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)); + } + for p in [json!({"layer": 1}), json!({"on": true}), json!({"_atnNoTarget": false}), json!({"_atnNoTarget": "true"})] { + let action = Action::new("A", vec![(id.into(), p)]); + assert!(atn_cmds::export("Links", &[&action], &[], false).is_err(), "{event}"); + } + } + for linked in [false, true] { + let action = Action::new("A", vec![("layer.linkLayers".into(), json!({"linked": linked, "_atnNoTarget": false}))]); + assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); + } +} + +#[test] +fn reverse_linked_selection_and_clear_style_events_do_their_edits() { + for explicit in [false, true] { + let mut s = fixture(&[None, None, None], &[0, 1, 2]); + let before = s.active().unwrap().doc.clone(); + let ids: Vec<_> = before.layers.iter().map(|layer| layer.id).rev().collect(); + load_targeted(&mut s, "reverse", "layer.arrange.reverse", explicit); + play(&mut s); + assert_eq!(s.active().unwrap().doc.layers.iter().map(|layer| layer.id).collect::>(), ids); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + + let mut s = fixture(&[Some(77), Some(77), None], &[0]); + let ids: Vec<_> = s.active().unwrap().doc.layers[..2].iter().map(|layer| layer.id).collect(); + load_targeted(&mut s, "selectLinkedLayers", "layer.selectLinkedLayers", explicit); + play(&mut s); + assert_eq!(s.active().unwrap().selected_layers(), ids); + + let mut s = fixture(&[None], &[0]); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + let before = s.active().unwrap().doc.clone(); + assert_eq!(before.layers[0].effects.items.len(), 1); + load_targeted(&mut s, "disableLayerStyle", "layer.layerStyle.clear", explicit); + play(&mut s); + assert!(s.active().unwrap().doc.layers[0].effects.items.is_empty()); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +fn smart_target_scene(event: &str, bytes: &[u8], replacement: &[u8], path: &str) -> Session { + let mut s = smart_fixture(bytes); + if matches!(event, "placedLayerConvertToEmbedded" | "placedLayerUpdateAllModified") { + s.execute("layer.smartObjects.convertToLinked", json!({"path": path})).unwrap(); + } + if event == "placedLayerUpdateAllModified" { + std::fs::write(path, replacement).unwrap(); + } + s +} + +fn assert_smart_target_edit(event: &str, s: &Session, original_id: photocraft_doc::SmartContentsId, pixels: &[[f32; 4]], bytes: &[u8]) { + match event { + "placedLayerMakeCopy" => { + assert_ne!(active_smart(s).contents_id, original_id); + assert_eq!(s.active().unwrap().doc.walk().iter().filter(|(_, _, layer)| matches!(layer.content, LayerContent::Smart(_))).count(), 2); + } + "placedLayerConvertToLayers" => assert!(s.active().unwrap().doc.walk().iter().all(|(_, _, layer)| !matches!(layer.content, LayerContent::Smart(_)))), + "placedLayerConvertToEmbedded" => assert!(matches!(&active_smart(s).source, SmartSource::Embedded { bytes: actual, .. } if actual.as_slice() == bytes)), + "placedLayerUpdateAllModified" => assert!(photocraft_compose::flatten(&s.active().unwrap().doc).px.iter().all(|px| *px == [1.0, 0.0, 0.0, 1.0])), + _ => unreachable!(), + } + if event != "placedLayerUpdateAllModified" { + assert_eq!(photocraft_compose::flatten(&s.active().unwrap().doc).px, pixels); + } +} + +#[test] +fn smart_target_events_copy_unpack_embed_and_refresh_real_contents() { + let original = png("#0000ff"); + let replacement = png("#ff0000"); + for &(event, id) in &TARGET_EVENTS[3..7] { + for explicit in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("linked.png"); + let mut s = smart_target_scene(event, &original, &replacement, path.to_str().unwrap()); + let before = s.active().unwrap().doc.clone(); + let pixels = photocraft_compose::flatten(&before).px; + let contents_id = active_smart(&s).contents_id; + load_targeted(&mut s, event, id, explicit); + play(&mut s); + assert_smart_target_edit(event, &s, contents_id, &pixels, &original); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } + } +} + +#[test] +fn rasterize_all_event_visits_nested_and_top_level_smart_layers() { + for explicit in [false, true] { + let mut s = smart_fixture(&png("#0000ff")); + let first = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.smartObjects.newSmartObjectViaCopy", json!({})).unwrap(); + let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc); + let nested = doc.remove(first).unwrap(); + doc.layers.push(Layer::group("Nested", vec![nested])); + let before = s.active().unwrap().doc.clone(); + let pixels = photocraft_compose::flatten(&before).px; + load_targeted(&mut s, "rasterizeAll", "layer.rasterize.allLayers", explicit); + play(&mut s); + assert!(s.active().unwrap().doc.walk().iter().all(|(_, _, layer)| !matches!(layer.content, LayerContent::Smart(_)))); + assert_eq!(photocraft_compose::flatten(&s.active().unwrap().doc).px, pixels); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +#[test] +fn video_and_isolate_events_use_current_document_state() { + for explicit in [false, true] { + let mut s = fixture(&[None], &[0]); + let before = s.active().unwrap().doc.clone(); + load_targeted(&mut s, "addBlankVideoLayer", "layer.videoLayers.newBlankVideoLayer", explicit); + play(&mut s); + let st = s.active().unwrap(); + let video = st.doc.layer(st.active_layer.unwrap()).unwrap().video.as_ref().unwrap(); + assert_eq!(video.frames.len(), 1); + assert_eq!(video.fps, 30.0); + assert!(video.frames[0].content_bounds().is_empty()); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + + let mut s = fixture(&[None, None, None], &[0, 2]); + let before = s.active().unwrap().doc.clone(); + let ids = s.active().unwrap().selected_layers(); + let history = s.active().unwrap().history.past_len(); + load_targeted(&mut s, "isolateLayers", "select.isolateLayers", explicit); + play(&mut s); + assert_eq!(s.active().unwrap().isolated_layers, ids); + play(&mut s); + assert!(s.active().unwrap().isolated_layers.is_empty()); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } +} + +fn active_text(s: &Session) -> &photocraft_doc::TextLayer { + let st = s.active().unwrap(); + let LayerContent::Text(text) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("expected Type") }; + text +} + +#[test] +fn type_default_events_save_then_restore_changed_styles() { + for explicit in [false, true] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("type.create", json!({"text": "Hi", "size": 14})).unwrap(); + assert!(s.type_defaults.is_none()); + load_targeted(&mut s, "textSaveDefaultTypeStyles", "type.saveDefaultTypeStyles", explicit); + play(&mut s); + assert_eq!(s.type_defaults.as_ref().unwrap().0.size_pt, 14.0); + s.execute("type.setStyle", json!({"size": 28})).unwrap(); + assert_eq!(active_text(&s).char_runs()[0].style.size_pt, 28.0); + let before = s.active().unwrap().doc.clone(); + load_targeted(&mut s, "textLoadDefaultTypeStyles", "type.loadDefaultTypeStyles", explicit); + play(&mut s); + assert_eq!(active_text(&s).char_runs()[0].style.size_pt, 14.0); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +#[test] +fn measurement_event_records_actual_selected_area() { + for explicit in [false, true] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap(); + let before = s.active().unwrap().doc.clone(); + load_targeted(&mut s, "recordMeasurements", "image.analysis.recordMeasurements", explicit); + play(&mut s); + assert_eq!(s.analysis.log.len(), 1); + assert_eq!(s.analysis.log[0].values["source"], "Selection"); + assert_eq!(s.analysis.log[0].values["area"].as_f64(), Some(4.0)); + assert_eq!(s.active().unwrap().doc, before); + } +} + #[test] fn link_descriptor_headers_normalize_without_changing_meaningful_keys() { for event in ["linkSelectedLayers", "unlinkSelectedLayers"] { diff --git a/docs/atn.md b/docs/atn.md index 727a5c30c6..2c1e631bec 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -16,6 +16,34 @@ 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. +## Other events without settings + +| Photoshop event | PhotoCraft command | +| --- | --- | +| `reverse` | `layer.arrange.reverse` | +| `selectLinkedLayers` | `layer.selectLinkedLayers` | +| `disableLayerStyle` | `layer.layerStyle.clear` | +| `placedLayerMakeCopy` | `layer.smartObjects.newSmartObjectViaCopy` | +| `placedLayerConvertToLayers` | `layer.smartObjects.convertToLayers` | +| `placedLayerConvertToEmbedded` | `layer.smartObjects.convertToEmbedded` | +| `placedLayerUpdateAllModified` | `layer.smartObjects.updateAllModifiedContent` | +| `rasterizeAll` | `layer.rasterize.allLayers` | +| `addBlankVideoLayer` | `layer.videoLayers.newBlankVideoLayer` | +| `isolateLayers` | `select.isolateLayers` | +| `textLoadDefaultTypeStyles` | `type.loadDefaultTypeStyles` | +| `textSaveDefaultTypeStyles` | `type.saveDefaultTypeStyles` | +| `recordMeasurements` | `image.analysis.recordMeasurements` | + +These events and Link/Unlink accept either an empty descriptor or an explicit +current-layer target. Save retains which form was imported. Other targets or +extra settings stay complete Photoshop steps; native options with no recorded +representation are refused on export. + +Playback uses each native command's normal preconditions and current state. +Isolate Layers toggles the panel view. Type defaults are saved in the current +session. Record Measurements uses the current selection/ruler/count and data +point configuration. + ## Smart Object file operations | Photoshop event | Meaningful descriptor keys | PhotoCraft command | From 1130c8a66c6fa4db591b927354e6b2a258bc69fe Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 13:53:09 -0800 Subject: [PATCH 04/12] feat(engine): map Type to Shape and radius-only Shape Blur ATN --- crates/engine/src/cmd/atn_cmds/events.rs | 24 +++ crates/engine/src/cmd/atn_cmds/steps_make.rs | 10 ++ crates/engine/src/cmd/atn_cmds/tests.rs | 3 + crates/engine/tests/it/atn_newer_events.rs | 153 ++++++++++++++++++- docs/atn.md | 17 +++ 5 files changed, 205 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index cca7d2d69c..55b0e2966b 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -213,6 +213,28 @@ fn target_only_to(_: &str, p: &Value) -> Option { target_descriptor(p) } +const SHAPE_BLUR: &[F] = &[F("Rds ", "radius", Kind::Px)]; + +fn shape_blur_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(p) = fields_from(d, SHAPE_BLUR) else { return unsupported }; + let p = Value::Object(p); + if shape_blur_to("filter.blur.shapeBlur", &p).is_some_and(|expected| d.items == expected.items) { step("filter.blur.shapeBlur", p) } else { unsupported } +} + +fn shape_blur_to(_: &str, p: &Value) -> Option { + if !params(p, &["radius"]) { + return None; + } + if let Some(radius) = p.get("radius") { + let radius = radius.as_f64()?; + if !radius.is_finite() || !(5.0..=1000.0).contains(&radius) { + return None; + } + } + fields_to(p, SHAPE_BLUR, desc("null")) +} + // Recorded Link and Unlink need explicit state: replaying the UI toggle can // perform the opposite operation. Target matching follows #10628's adapter. fn link_from(d: &Descriptor, linked: bool) -> Mapped { @@ -310,6 +332,7 @@ pub(super) const EVENTS: &[Event] = &[ ev!("MtnB", "motionBlur", "Motion Blur", "filter.blur.motionBlur", &[F("Angl", "angle", Kind::Ang), F("Dstn", "distance", Kind::Px)]), ev!("", "boxblur", "Box Blur", "filter.blur.boxBlur", &[F("Rds ", "radius", Kind::Px)]), ev!("", "surfaceBlur", "Surface Blur", "filter.blur.surfaceBlur", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), + Event { code: "", name: "shapeBlur", label: "Shape Blur", ids: &["filter.blur.shapeBlur"], from: shape_blur_from, to: shape_blur_to }, ev!( "SmrB", "smartBlur", @@ -467,6 +490,7 @@ pub(super) const EVENTS: &[Event] = &[ name: "make", label: "Make", ids: &[ + "type.convertToShape", "layer.new.layer", "layer.new.group", "layer.groupLayers", diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 2fce72c36d..098bd6ab9a 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -139,7 +139,14 @@ fn new_document_from_descriptor(d: &Descriptor) -> Option { /// New Snapshot's From: the full document, the layers merged, or the current layer. const SNAPSHOT_FROM: &[(&str, &str)] = &[("FllD", "fullDocument"), ("MrgL", "mergedLayers"), ("CrnL", "currentLayer")]; +fn type_shape_descriptor() -> Descriptor { + desc("null").with("null", class_ref("contentLayer")).with("Usng", target_ref("textLayer")) +} + pub(super) fn make_from(d: &Descriptor) -> Mapped { + if d.items == type_shape_descriptor().items { + return none("type.convertToShape"); + } if let Some(mapped) = duplicate_layer_from_descriptor(d) { return mapped; } @@ -224,6 +231,9 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped { } pub(super) fn make_to(id: &str, p: &Value) -> Option { + if id == "type.convertToShape" { + return p.as_object().filter(|p| p.is_empty()).map(|_| type_shape_descriptor()); + } let with_name = |cls: &str| { let mut u = desc(cls); if let Some(n) = jstr(p, "name") { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 965399241c..757df349a0 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -546,6 +546,9 @@ fn every_mapped_command_exports_and_imports_back() { ("layer.duplicate", json!({"layer": "Shadow", "document": "new", "documentName": "Doc"})), ("image.duplicate", json!({"mergedOnly": true})), ("layer.new.layer", json!({"name": "Ink", "opacity": 0.5, "mode": "Multiply"})), + ("type.convertToShape", json!({})), + ("filter.blur.shapeBlur", json!({})), + ("filter.blur.shapeBlur", json!({"radius": 10})), ("layer.new.group", json!({"name": "G"})), ("layer.groupLayers", json!({})), ("layer.linkLayers", json!({"linked": true})), diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 70db016186..41f5ed7525 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -36,10 +36,14 @@ fn target() -> D { } fn target_class(class_id: &str) -> D { + ordinal_target(class_id, "Trgt") +} + +fn ordinal_target(class_id: &str, ordinal: &str) -> D { D::Reference(vec![ReferenceItem::Enumerated { class: Class { name: UnicodeString::new_nul(""), class_id: Id::new(class_id) }, type_id: Id::new("Ordn"), - value: Id::new("Trgt"), + value: Id::new(ordinal), }]) } @@ -49,7 +53,14 @@ fn file(event: &str, descriptor: Descriptor) -> Vec { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), - items: vec![AtnItem { event: AtnEvent::name(event), descriptor: Some(descriptor), ..Default::default() }], + items: vec![AtnItem { + event: match event.as_bytes() { + [a, b, c, d] => AtnEvent::Code([*a, *b, *c, *d]), + _ => AtnEvent::name(event), + }, + descriptor: Some(descriptor), + ..Default::default() + }], ..Default::default() }], warnings: vec![], @@ -67,6 +78,13 @@ fn play(s: &mut Session) { assert_eq!(report["ran"], 1, "{report}"); } +fn saved_item(s: &mut Session) -> AtnItem { + 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(); + atn::parse(&bytes).unwrap().actions[0].items[0].clone() +} + #[test] fn explicit_links_are_idempotent_and_omitted_state_still_toggles() { let mut s = fixture(&[None, None], &[0, 1]); @@ -459,6 +477,137 @@ fn measurement_event_records_actual_selected_area() { } } +fn class_reference(class_id: &str) -> D { + D::Reference(vec![ReferenceItem::Class(Class { name: UnicodeString::new_nul(""), class_id: Id::new(class_id) })]) +} + +fn make_type_descriptor() -> Descriptor { + Descriptor::new("Mk ").with("null", class_reference("contentLayer")).with("Usng", target_class("textLayer")) +} + +#[test] +fn make_type_shape_roundtrips_and_converts_actual_glyphs_with_undo() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 128, "height": 80, "background": "white"})).unwrap(); + let id = LayerId(s.execute("type.create", json!({"text": "oil", "size": 24, "x": 8, "y": 48})).unwrap()["layer"].as_u64().unwrap()); + Arc::make_mut(&mut s.active_mut().unwrap().doc).layer_mut(id).unwrap().psd_blocks.push((*b"TySh", Arc::new(vec![1, 2, 3]))); + let before = s.active().unwrap().doc.clone(); + assert_eq!(load(&mut s, &file("Mk ", make_type_descriptor()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps, [("type.convertToShape".into(), json!({}))]); + let saved = saved_item(&mut s); + assert_eq!(saved.event, AtnEvent::Code(*b"Mk ")); + let mut canonical = make_type_descriptor(); + canonical.class_id = Id::new("null"); + assert_eq!(saved.descriptor, Some(canonical.clone())); + assert_eq!(load(&mut s, &file("Mk ", canonical))["unsupported"], json!([])); + play(&mut s); + let layer = s.active().unwrap().doc.layer(id).unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("Type was not converted to Shape") }; + assert!(!shape.path.subpaths.is_empty()); + assert!(!layer.psd_blocks.iter().any(|(key, _)| key == b"TySh")); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); +} + +#[test] +fn make_type_shape_keeps_wrong_references_and_preserves_fill_mappings() { + for descriptor in [ + Descriptor::new("null").with("null", class_reference("contentLayer")), + Descriptor::new("null").with("null", class_reference("contentLayer")).with("Usng", target_class("Lyr ")), + Descriptor::new("null").with("null", class_reference("contentLayer")).with("Usng", ordinal_target("textLayer", "Frnt")), + make_type_descriptor().with("extra", D::Boolean(true)), + make_type_descriptor().with("Usng", target_class("textLayer")), + ] { + let mut s = Session::new(); + assert_eq!(load(&mut s, &file("Mk ", descriptor.clone()))["unsupported"].as_array().unwrap().len(), 1); + assert_eq!(saved_item(&mut s).descriptor, Some(descriptor)); + } + for (id, p) in [("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})), ("layer.newFillLayer.pattern", json!({"pattern": "Grid"}))] { + let action = Action::new("A", vec![(id.into(), p)]); + let (bytes, skipped) = atn_cmds::export("Links", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty()); + let mut s = Session::new(); + assert_eq!(load(&mut s, &bytes)["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].0, id); + } + let action = Action::new("A", vec![("type.convertToShape".into(), json!({"layer": 1}))]); + assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); +} + +fn radius_descriptor(radius: f64) -> Descriptor { + Descriptor::new("shapeBlur").with("Rds ", D::UnitFloat { unit: *b"#Pxl", value: radius }) +} + +fn impulse_fixture() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 9, "height": 9, "background": "transparent"})).unwrap(); + s.edit("impulse fixture", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_doc::Rect::new(4, 4, 5, 5), &[1.0, 1.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn radius_only_shape_blur_roundtrips_and_changes_pixels_including_default() { + for radius in [None, Some(5.0)] { + let mut s = impulse_fixture(); + let d = radius.map_or_else(|| Descriptor::new("shapeBlur"), radius_descriptor); + assert_eq!(load(&mut s, &file("shapeBlur", d.clone()))["unsupported"], json!([])); + let saved = saved_item(&mut s); + assert_eq!(saved.event, AtnEvent::name("shapeBlur")); + let mut canonical = d; + canonical.class_id = Id::new("null"); + assert_eq!(saved.descriptor, Some(canonical.clone())); + assert_eq!(load(&mut s, &file("shapeBlur", canonical))["unsupported"], json!([])); + let before = s.active().unwrap().doc.clone(); + let pixels = photocraft_compose::flatten(&before).px; + play(&mut s); + let blurred = photocraft_compose::flatten(&s.active().unwrap().doc).px; + assert_ne!(blurred, pixels); + let mut direct = impulse_fixture(); + direct.execute("filter.blur.shapeBlur", json!({"radius": radius.unwrap_or(10.0)})).unwrap(); + assert_eq!(blurred, photocraft_compose::flatten(&direct.active().unwrap().doc).px); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +#[test] +fn shape_blur_radius_boundaries_keep_their_value_without_running_large_kernels() { + for radius in [5.0, 10.0, 1000.0] { + let mut s = Session::new(); + let mut canonical = radius_descriptor(radius); + assert_eq!(load(&mut s, &file("shapeBlur", canonical.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].1["radius"].as_f64(), Some(radius)); + canonical.class_id = Id::new("null"); + assert_eq!(saved_item(&mut s).descriptor, Some(canonical)); + } +} + +#[test] +fn shape_blur_keeps_custom_assets_and_invalid_radius_forms_whole() { + let custom = Descriptor::new("customShape").with("Nm ", D::Text(UnicodeString::new_nul("Star"))).with("Idnt", D::Text(UnicodeString::new_nul("asset-id"))); + for descriptor in [ + radius_descriptor(4.0), + radius_descriptor(1001.0), + radius_descriptor(f64::NAN), + radius_descriptor(f64::INFINITY), + Descriptor::new("shapeBlur").with("Rds ", D::UnitFloat { unit: *b"#Prc", value: 10.0 }), + radius_descriptor(10.0).with("customShape", D::Descriptor(custom)).with("keyOriginType", D::Integer(9)), + radius_descriptor(10.0).with("extra", D::Boolean(true)), + ] { + let mut s = Session::new(); + assert_eq!(load(&mut s, &file("shapeBlur", descriptor.clone()))["unsupported"].as_array().unwrap().len(), 1); + assert_eq!(saved_item(&mut s).descriptor.unwrap().to_bytes(), descriptor.to_bytes()); + } + for p in [json!({"radius": 0}), json!({"radius": 1001}), json!({"radius": null}), json!({"radius": 10, "shape": "circle"}), json!({"target": "mask"})] { + let action = Action::new("A", vec![("filter.blur.shapeBlur".into(), p)]); + assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); + } +} + #[test] fn link_descriptor_headers_normalize_without_changing_meaningful_keys() { for event in ["linkSelectedLayers", "unlinkSelectedLayers"] { diff --git a/docs/atn.md b/docs/atn.md index 2c1e631bec..98a94434a5 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -44,6 +44,23 @@ Isolate Layers toggles the panel view. Type defaults are saved in the current session. Record Measurements uses the current selection/ruler/count and data point configuration. +## Type to Shape and radius-only Shape Blur + +| Photoshop form | PhotoCraft command | +| --- | --- | +| Make `contentLayer`, `Usng` a `textLayer` / `Ordn.Trgt` reference | `type.convertToShape` | +| `shapeBlur`, optional `Rds ` in pixels, 5–1000 | `filter.blur.shapeBlur` | + +Convert Type to Shape retains the Make event and its two references; it does not +export a separate `convertToShape` event. Other Make forms, including Solid Color +and Pattern fill layers, retain their existing mappings. + +Shape Blur maps the issue's radius-only form through the existing filter. An +omitted radius uses the native factory value of 10. Later dialog forms containing +`customShape` or `keyOriginType` stay complete kept steps. Native explicit shape +choices cannot be exported into a radius-only descriptor. No custom shape asset +lookup or new blur kernel is supplied by this mapping. + ## Smart Object file operations | Photoshop event | Meaningful descriptor keys | PhotoCraft command | From f39d0b828095e26d8e0d5688bf394fad79c5df46 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 14:06:12 -0800 Subject: [PATCH 05/12] feat(engine): replay the Crop Photos ATN parent once --- crates/engine/src/cmd/atn_cmds/events.rs | 1 + crates/engine/src/cmd/atn_cmds/tests.rs | 2 + crates/engine/src/cmd/photo_cmds.rs | 18 ++-- crates/engine/tests/it/atn_newer_events.rs | 115 +++++++++++++++++++++ docs/atn.md | 10 ++ 5 files changed, 140 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 55b0e2966b..d5a63f6350 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -476,6 +476,7 @@ pub(super) const EVENTS: &[Event] = &[ target_event!("textLoadDefaultTypeStyles", "Load Default Type Styles", "type.loadDefaultTypeStyles"), target_event!("textSaveDefaultTypeStyles", "Save Default Type Styles", "type.saveDefaultTypeStyles"), target_event!("recordMeasurements", "Record Measurements", "image.analysis.recordMeasurements"), + target_event!("CropPhotosAuto0001", "Crop and Straighten Photos", "file.automate.cropAndStraightenPhotos"), Event { code: "", name: "linkSelectedLayers", label: "Link Layers", ids: &["layer.linkLayers"], from: |d| link_from(d, true), to: |_, p| link_to(p, true) }, Event { code: "", diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 757df349a0..cf677baf5b 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -565,6 +565,8 @@ fn every_mapped_command_exports_and_imports_back() { ("type.loadDefaultTypeStyles", json!({})), ("type.saveDefaultTypeStyles", json!({})), ("image.analysis.recordMeasurements", json!({})), + ("file.automate.cropAndStraightenPhotos", json!({})), + ("file.automate.cropAndStraightenPhotos", json!({"_atnNoTarget": true})), ("layer.new.layerViaCopy", json!({})), ("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("layer.newAdjustmentLayer.hueSaturation", json!({})), diff --git a/crates/engine/src/cmd/photo_cmds.rs b/crates/engine/src/cmd/photo_cmds.rs index 2aa2a383b8..e5e0b0da69 100644 --- a/crates/engine/src/cmd/photo_cmds.rs +++ b/crates/engine/src/cmd/photo_cmds.rs @@ -875,6 +875,7 @@ fn mask_unselected(sel: &Surface, area: Rect, w: usize, h: usize, rgba: &mut [[f } fn crop_and_straighten(s: &mut Session, _p: &Value) -> Result { + crop_ready(s)?; let st = s.active().ok_or(EngineError::NoDocument)?; let doc = st.doc.clone(); let fmt = doc.pixel_format(); @@ -942,13 +943,18 @@ fn crop_and_straighten(s: &mut Session, _p: &Value) -> Result { // ---------- specs ---------- -/// Photoshop greys Crop and Straighten Photos out for Indexed Color documents. -fn not_indexed(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; +/// Crop needs a selected, visible, pixel-unlocked layer, including inherited state. +fn crop_ready(s: &Session) -> Result<()> { + let st = s.active().ok_or(EngineError::NoDocument)?; if st.doc.mode == ColorMode::Indexed { - return Err("not available for Indexed Color documents".into()); + return Err(EngineError::Other("not available for Indexed Color documents".into())); } - Ok(()) + let id = st.active_layer.ok_or_else(|| EngineError::Other("no layer selected".into()))?; + let path = st.doc.path_of(id).ok_or(EngineError::NoLayer(id))?; + if !st.doc.shown_at(&path) { + return Err(EngineError::Other("the selected layer is hidden".into())); + } + crate::commands::check_pixels_unlocked(&st.doc, id) } fn always(_: &Session) -> std::result::Result<(), String> { @@ -983,7 +989,7 @@ pub fn specs() -> Vec { menu: &["File", "Automate"], shortcut: None, params: "{} → one new document per photo found on the scan (inside the selection when there is one)", - enabled: not_indexed, + enabled: |s| crop_ready(s).map_err(|e| e.to_string()), run: crop_and_straighten, journal: true, }, diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 41f5ed7525..1ecdf41e81 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -223,6 +223,7 @@ const TARGET_EVENTS: &[(&str, &str)] = &[ ("textLoadDefaultTypeStyles", "type.loadDefaultTypeStyles"), ("textSaveDefaultTypeStyles", "type.saveDefaultTypeStyles"), ("recordMeasurements", "image.analysis.recordMeasurements"), + ("CropPhotosAuto0001", "file.automate.cropAndStraightenPhotos"), ]; fn targeted(event: &str, explicit: bool) -> Descriptor { @@ -307,6 +308,120 @@ fn target_events_keep_unknown_targets_and_refuse_native_options() { } } +fn scan_fixture() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 480, "height": 340, "background": "#fafafa"})).unwrap(); + let st = s.active_mut().unwrap(); + let id = st.active_layer.unwrap(); + let surface = Arc::make_mut(&mut st.doc).layer_mut(id).unwrap().surface_mut().unwrap(); + for (x, y, w, h, color) in [(40, 60, 160, 110, [0.6, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0])] { + surface.fill_rect(photocraft_doc::Rect::new(x, y, x + w, y + h), &color); + } + s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160})).unwrap(); + s +} + +fn assert_cropped_scan(s: &Session) { + assert_eq!(s.documents().len(), 2); + let doc = &s.documents()[1].doc; + assert!((i64::from(doc.size.width) - 150).abs() <= 4); + assert!((i64::from(doc.size.height) - 120).abs() <= 4); + let color = doc.layers[0].surface().unwrap().rgba(doc.size.width as i32 / 2, doc.size.height as i32 / 2); + assert!(color[2] > 0.5 && color[0] < 0.2, "{color:?}"); +} + +#[test] +fn crop_parent_creates_the_selected_photo_without_changing_the_scan() { + for explicit in [false, true] { + let mut s = scan_fixture(); + let source = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + load_targeted(&mut s, "CropPhotosAuto0001", "file.automate.cropAndStraightenPhotos", explicit); + assert!(s.is_enabled("file.automate.cropAndStraightenPhotos")); + play(&mut s); + assert_cropped_scan(&s); + assert_eq!(s.documents()[0].doc, source); + assert_eq!(s.documents()[0].history.past_len(), history); + } +} + +#[test] +fn crop_parent_refuses_ineligible_layers_without_document_or_history_changes() { + for case in ["missing", "stale", "hidden", "hidden-parent", "pixels", "locked-parent", "indexed"] { + let mut s = scan_fixture(); + let st = s.active_mut().unwrap(); + let id = st.active_layer.unwrap(); + let doc = Arc::make_mut(&mut st.doc); + match case { + "missing" => st.active_layer = None, + "stale" => st.active_layer = Some(LayerId::fresh()), + "hidden" => doc.layer_mut(id).unwrap().visible = false, + "pixels" => doc.layer_mut(id).unwrap().locks.pixels = true, + "indexed" => doc.mode = photocraft_doc::ColorMode::Indexed, + _ => { + let mut group = Layer::group("Parent", std::mem::take(&mut doc.layers)); + group.visible = case != "hidden-parent"; + group.locks.all = case == "locked-parent"; + doc.layers.push(group); + } + } + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + assert!(!s.is_enabled("file.automate.cropAndStraightenPhotos"), "{case}"); + load_targeted(&mut s, "CropPhotosAuto0001", "file.automate.cropAndStraightenPhotos", false); + let report = s.execute("actions.play", json!({"action": "A", "set": "Links"})).unwrap(); + assert_eq!(report["ran"], 0, "{case}: {report}"); + assert_eq!(report["failed"]["id"], "file.automate.cropAndStraightenPhotos", "{case}: {report}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + assert!(!Session::new().is_enabled("file.automate.cropAndStraightenPhotos")); +} + +#[test] +fn crop_parent_without_photos_fails_without_creating_documents() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 80, "height": 80, "background": "white"})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + load_targeted(&mut s, "CropPhotosAuto0001", "file.automate.cropAndStraightenPhotos", false); + let report = s.execute("actions.play", json!({"action": "A", "set": "Links"})).unwrap(); + assert_eq!(report["ran"], 0, "{report}"); + assert!(report["failed"]["error"].as_str().unwrap().contains("no photos found"), "{report}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); +} + +#[test] +fn crop_parent_runs_once_and_the_kept_helper_stops_the_duplicate_crop_tail() { + let mut f = atn::parse(&file("CropPhotosAuto0001", Descriptor::new("cjsp"))).unwrap(); + let helper = Descriptor::new("null").with("Vl ", D::List([0.0, 0.0, 150.0, 0.0, 150.0, 120.0, 0.0, 120.0].into_iter().map(D::Double).collect())); + f.actions[0].items.push(AtnItem { event: AtnEvent::name("CropPhotos0001"), descriptor: Some(helper.clone()), ..Default::default() }); + let tail = Action::new("Tail", vec![("image.duplicate".into(), json!({})), ("image.crop".into(), json!({"x": 1, "y": 1, "width": 10, "height": 10}))]); + let (bytes, skipped) = atn_cmds::export("Tail", &[&tail], &[], false).unwrap(); + assert!(skipped.is_empty()); + f.actions[0].items.extend(atn::parse(&bytes).unwrap().actions[0].items.clone()); + let mut s = scan_fixture(); + let source = s.active().unwrap().doc.clone(); + let report = load(&mut s, &atn::write(&f).unwrap()); + assert_eq!(report["unsupported"].as_array().unwrap().len(), 1); + assert_eq!( + s.actions.list[0].steps.iter().map(|step| step.0.as_str()).collect::>(), + ["file.automate.cropAndStraightenPhotos", "actions.photoshopStep", "image.duplicate", "image.crop"] + ); + 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[1].descriptor, Some(helper)); + let report = s.execute("actions.play", json!({"action": "A", "set": "Links"})).unwrap(); + assert_eq!(report["ran"], 1, "{report}"); + assert_eq!(report["failed"]["step"], 1); + assert_eq!(report["failed"]["id"], "actions.photoshopStep"); + assert_cropped_scan(&s); + assert_eq!(s.documents()[0].doc, source); +} + #[test] fn reverse_linked_selection_and_clear_style_events_do_their_edits() { for explicit in [false, true] { diff --git a/docs/atn.md b/docs/atn.md index 98a94434a5..69fca5446e 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -33,6 +33,7 @@ are kept as Photoshop steps for lossless saving, rather than partially replayed. | `textLoadDefaultTypeStyles` | `type.loadDefaultTypeStyles` | | `textSaveDefaultTypeStyles` | `type.saveDefaultTypeStyles` | | `recordMeasurements` | `image.analysis.recordMeasurements` | +| `CropPhotosAuto0001` | `file.automate.cropAndStraightenPhotos` | These events and Link/Unlink accept either an empty descriptor or an explicit current-layer target. Save retains which form was imported. Other targets or @@ -44,6 +45,15 @@ Isolate Layers toggles the panel view. Type defaults are saved in the current session. Record Measurements uses the current selection/ruler/count and data point configuration. +Crop and Straighten Photos runs the existing native scan operation once. It +requires a selected, visible layer with no pixel or full lock, including locks +and visibility inherited from groups. It creates a document for each detected +photo within the current selection and leaves the source document unchanged. +The separately recorded `CropPhotos0001` helper remains a complete kept Photoshop +step. Playback stops at that unsupported helper before subsequent duplicate/crop +steps can run. This mapping covers the parent event, not complete recordings +that contain those generated helper steps. + ## Type to Shape and radius-only Shape Blur | Photoshop form | PhotoCraft command | From 82e613fca8ed79635f740d4c927042617036e815 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 14:34:32 -0800 Subject: [PATCH 06/12] docs: explain ATN adapters and reference survey scope --- crates/engine/src/cmd/atn_cmds/events.rs | 11 +++++++++++ crates/engine/src/cmd/atn_cmds/steps_make.rs | 2 ++ crates/engine/src/cmd/layer_multi_cmds/structure.rs | 1 + crates/engine/src/cmd/photo_cmds.rs | 1 + docs/atn.md | 9 +++++---- 5 files changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index d5a63f6350..5309d35e45 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -179,6 +179,7 @@ fn clipping_to(_: &str, p: &Value) -> Option { // current-layer target. Save must retain that distinction; native behavior is identical. const NO_TARGET: &str = "_atnNoTarget"; +/// Accept only bare or current-layer targets, retaining their key-presence distinction for save. fn target_params(d: &Descriptor) -> Option> { let mut p = Map::new(); if d.items.is_empty() { @@ -189,6 +190,7 @@ fn target_params(d: &Descriptor) -> Option> { Some(p) } +/// Restore the bare or explicit current-layer descriptor selected by the private transport bit. fn target_descriptor(p: &Value) -> Option { match p.get(NO_TARGET) { None => Some(desc("null").with("null", target_ref("Lyr "))), @@ -198,14 +200,17 @@ fn target_descriptor(p: &Value) -> Option { } // Native-parameter allowlist adapted from #10628; refuse unrepresented options on export. +/// Refuse native options that the selected Photoshop form cannot represent. fn params(p: &Value, allowed: &[&str]) -> bool { p.as_object().is_some_and(|p| p.keys().all(|key| allowed.contains(&key.as_str()))) } +/// Import a target-only event, refusing other targets and extra descriptor settings. fn target_only_from(d: &Descriptor, id: &str) -> Mapped { target_params(d).map_or(Mapped::Unsupported { harmless: false }, |p| step(id, Value::Object(p))) } +/// Export a current-target native step only when no unrepresented options are present. fn target_only_to(_: &str, p: &Value) -> Option { if !params(p, &[NO_TARGET]) { return None; @@ -215,6 +220,7 @@ fn target_only_to(_: &str, p: &Value) -> Option { const SHAPE_BLUR: &[F] = &[F("Rds ", "radius", Kind::Px)]; +/// Map the radius-only Shape Blur form; keep custom assets or extra keys unsupported. fn shape_blur_from(d: &Descriptor) -> Mapped { let unsupported = Mapped::Unsupported { harmless: false }; let Some(p) = fields_from(d, SHAPE_BLUR) else { return unsupported }; @@ -222,6 +228,7 @@ fn shape_blur_from(d: &Descriptor) -> Mapped { if shape_blur_to("filter.blur.shapeBlur", &p).is_some_and(|expected| d.items == expected.items) { step("filter.blur.shapeBlur", p) } else { unsupported } } +/// Write an optional finite 5–1000 pixel radius, refusing explicit shapes and other options. fn shape_blur_to(_: &str, p: &Value) -> Option { if !params(p, &["radius"]) { return None; @@ -237,12 +244,14 @@ fn shape_blur_to(_: &str, p: &Value) -> Option { // Recorded Link and Unlink need explicit state: replaying the UI toggle can // perform the opposite operation. Target matching follows #10628's adapter. +/// Import Link or Unlink as an explicit operation rather than the state-dependent UI toggle. fn link_from(d: &Descriptor, linked: bool) -> Mapped { let Some(mut p) = target_params(d) else { return Mapped::Unsupported { harmless: false } }; p.insert("linked".into(), Value::Bool(linked)); step("layer.linkLayers", Value::Object(p)) } +/// Export only the matching explicit link state and supported current-layer target form. fn link_to(p: &Value, linked: bool) -> Option { if !params(p, &["linked", NO_TARGET]) || p.get("linked") != Some(&Value::Bool(linked)) { return None; @@ -250,6 +259,7 @@ fn link_to(p: &Value, linked: bool) -> Option { target_descriptor(p) } +/// Map canonical Smart Object file descriptors, refusing unrepresented paths, targets or keys. 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" }; @@ -269,6 +279,7 @@ fn smart_path_from(d: &Descriptor, id: &str) -> Mapped { if d.items == expected.items { step(id, p) } else { unsupported } } +/// Export path-only native parameters using the existing Open/Place path encoding. fn smart_path_to(id: &str, p: &Value) -> Option { let p = p.as_object()?; let path = p.get("path")?.as_str()?; diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 098bd6ab9a..a1525c6953 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -143,6 +143,7 @@ fn type_shape_descriptor() -> Descriptor { desc("null").with("null", class_ref("contentLayer")).with("Usng", target_ref("textLayer")) } +/// Map supported Make forms, including the exact target-text-to-content-layer references. pub(super) fn make_from(d: &Descriptor) -> Mapped { if d.items == type_shape_descriptor().items { return none("type.convertToShape"); @@ -230,6 +231,7 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped { } } +/// Build supported Make descriptors; Type to Shape exports only without native options. pub(super) fn make_to(id: &str, p: &Value) -> Option { if id == "type.convertToShape" { return p.as_object().filter(|p| p.is_empty()).map(|_| type_shape_descriptor()); diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index c52f7a3a1d..f5d4b2325f 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -3,6 +3,7 @@ use super::{Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, Re // ---------- structural commands ---------- +/// Set an explicit link state idempotently, or toggle when omitted, with singleton cleanup and Undo. pub(super) fn link_layers(s: &mut Session, p: &Value) -> Result { let requested = match p.get("linked") { None => None, diff --git a/crates/engine/src/cmd/photo_cmds.rs b/crates/engine/src/cmd/photo_cmds.rs index e5e0b0da69..9dd7da094b 100644 --- a/crates/engine/src/cmd/photo_cmds.rs +++ b/crates/engine/src/cmd/photo_cmds.rs @@ -874,6 +874,7 @@ fn mask_unselected(sel: &Surface, area: Rect, w: usize, h: usize, rgba: &mut [[f true } +/// Validate the selected layer, then open cropped scan photos without editing the source document. fn crop_and_straighten(s: &mut Session, _p: &Value) -> Result { crop_ready(s)?; let st = s.active().ok_or(EngineError::NoDocument)?; diff --git a/docs/atn.md b/docs/atn.md index 6d5b86ec7e..1c3518c3f6 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -206,7 +206,7 @@ run. This covers the parent event, not complete recordings with generated helper ## Known gaps in mapped events -A mapped event can still lose a setting. Every mapped event was checked on 2026-11-01: the 5 296 steps of +A mapped event can still lose a setting. The original 117-event mapping was checked on 2026-11-01: the 5 296 steps of the `.atn` corpus (sets the reference application recorded) and factory descriptors measured in the reference application went through `actions.load` and `actions.save`, and each saved descriptor was compared with the original. Then every step PhotoCraft saves for the cases in @@ -642,12 +642,13 @@ and class `null` that version 16 files use for code events; nested classes get t keeps writing version 16. Version 7 files (a different layout with 8-bit strings) and sets wrapped in MacBinary stay rejected. -## Event reference: events not mapped yet +## Event reference: original unmapped events -Each entry below is an event the reference application records that PhotoCraft does not map yet: its +Each entry below describes an event that was unmapped in the original reference survey: its 4-character code and string ID, the PhotoCraft command it should map to, and every key the step carries, in the order it is recorded, with type, unit, factory default and allowed values. When an event is -implemented, move it to the table above in the same change. +implemented, add it to the supported table while retaining the measured reference. +Current support and limits are described under [Newer event mapping boundaries](#newer-event-mapping-boundaries). ### How these values were measured From e6f23fd8e235247b8ec0ef5360718bfe3838817a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 15:26:29 -0800 Subject: [PATCH 07/12] feat(engine): map limited Artboard-from-Group ATN forms Preserve the target-only call and exactly reconstruct empty-guide settings. Apply preset tags without resizing, retain fractional RGB, and refuse unresolved guide state before mutation. Nonempty associations and unproved flag values remain unfinished. --- crates/engine/src/cmd/artboard_cmds.rs | 23 +++- crates/engine/src/cmd/atn_cmds.rs | 1 + crates/engine/src/cmd/atn_cmds/events.rs | 9 ++ .../engine/src/cmd/atn_cmds/steps_artboard.rs | 65 ++++++++++ crates/engine/src/cmd/atn_cmds/tests.rs | 2 + crates/engine/tests/it/atn_newer_events.rs | 122 ++++++++++++++++++ docs/atn.md | 20 ++- 7 files changed, 234 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/cmd/atn_cmds/steps_artboard.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 2f05ddfae0..89e7a15d00 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -301,18 +301,35 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// Convert a plain group without resizing its content bounds; refuse unresolved recorded guide associations before editing. fn artboard_from_group(s: &mut Session, p: &Value) -> Result { + let cmd = "layer.new.artboardFromGroup"; let d = s.active().ok_or(EngineError::NoDocument)?; let id = p.get("layer").and_then(Value::as_u64).map(LayerId).or(d.active_layer).ok_or(EngineError::Other("no active layer".into()))?; + let preset = match p.get("preset") { + None => String::new(), + Some(value) => value.as_str().ok_or_else(|| bad(cmd, "preset must be text"))?.to_string(), + }; + if p.get("changeBackground").is_some_and(|value| value != &Value::Bool(true)) { + return Err(bad(cmd, "only an explicit true background-change flag is supported")); + } + if let Some(guides) = p.get("guideIDs") { + if !guides.as_array().is_some_and(Vec::is_empty) { + return Err(bad(cmd, "recorded guide associations are not supported")); + } + if !d.doc.guides.horizontal.is_empty() || !d.doc.guides.vertical.is_empty() { + return Err(bad(cmd, "an explicit empty guide association requires a document without guides")); + } + } let canvas = d.doc.bounds(); - let background = background_param(p, "layer.new.artboardFromGroup")?.unwrap_or_default(); + let background = background_param(p, cmd)?.unwrap_or_default(); let rect = s.edit("Artboard from Group", |doc, active| { if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) { return Err(EngineError::Other("artboards are made from a top-level layer group".into())); } let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let rect = crate::layer_multi_cmds::layer_bounds(l).unwrap_or(canvas); - set_artboard(l, Artboard { rect, background, preset: String::new() }); + set_artboard(l, Artboard { rect, background, preset }); fit_canvas(doc); *active = Some(id); Ok(rect) @@ -703,7 +720,7 @@ pub fn specs() -> Vec { "layer.new.artboardFromGroup", "Artboard from Group…", &["Layer", "New"], - r##"{"layer":id? (a top-level group; default active),"background":…?} → {layer, rect}"##, + r##"{"layer":id? (a top-level group; default active),"background":…?,"color":[r,g,b]|"#rrggbb"?,"preset":str? (tag only; does not resize),"guideIDs":[]? (recorded empty association; requires no document guides),"changeBackground":true? (recorded apply flag; other values refused)} → {layer, rect}"##, has_plain_group, artboard_from_group ), diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 42a4722479..c0e6ed5712 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -32,6 +32,7 @@ mod descriptors; mod events; mod fields; mod files; +mod steps_artboard; mod steps_doc; mod steps_image; mod steps_layer; diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 5309d35e45..a80056260d 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -2,6 +2,7 @@ const DIFFUSE_MODE: &[(&str, &str)] = &[("Nrml", "normal"), ("DrkO", "darkenOnly 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, path_text, path_value, ref_class, target_ref}; use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; +use super::steps_artboard::{artboard_from, artboard_to}; 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, crop_from, crop_to, export_from, export_to, image_size_from, image_size_to, merge_visible_from, merge_visible_to, open_from, open_to, paste_from, paste_to, @@ -488,6 +489,14 @@ pub(super) const EVENTS: &[Event] = &[ target_event!("textSaveDefaultTypeStyles", "Save Default Type Styles", "type.saveDefaultTypeStyles"), target_event!("recordMeasurements", "Record Measurements", "image.analysis.recordMeasurements"), target_event!("CropPhotosAuto0001", "Crop and Straighten Photos", "file.automate.cropAndStraightenPhotos"), + Event { + code: "", + name: "artboardFromLayerGroupEvent", + label: "Artboard from Group", + ids: &["layer.new.artboardFromGroup"], + from: artboard_from, + to: artboard_to, + }, Event { code: "", name: "linkSelectedLayers", label: "Link Layers", ids: &["layer.linkLayers"], from: |d| link_from(d, true), to: |_, p| link_to(p, true) }, Event { code: "", diff --git a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs new file mode 100644 index 0000000000..8d2964d95a --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs @@ -0,0 +1,65 @@ +//! Strict Artboard from Group forms whose settings the existing native model can apply. + +use super::descriptors::{desc, get_num, get_obj, get_text, target_ref, text}; +use super::fields::{Mapped, none, step}; +use super::{D, Descriptor, Value, json}; + +const COMMAND: &str = "layer.new.artboardFromGroup"; + +/// Import the current-target form or the verified empty-guide settings form, keeping other forms whole. +pub(super) fn artboard_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + if d.items == desc("null").with("null", target_ref("Lyr ")).items { + return none(COMMAND); + } + let Some(board) = get_obj(d, "artboard") else { return unsupported }; + let Some(color) = get_obj(board, "Clr ") else { return unsupported }; + let Some(preset) = get_text(board, "artboardPresetName") else { return unsupported }; + let background = match board.get("artboardBackgroundType") { + Some(D::Integer(1)) => "white", + Some(D::Integer(2)) => "black", + Some(D::Integer(3)) => "transparent", + Some(D::Integer(4)) => "custom", + _ => return unsupported, + }; + let rgb: Option> = ["Rd ", "Grn ", "Bl "].iter().map(|key| get_num(color, key).map(|n| n / 255.0)).collect(); + let Some(rgb) = rgb else { return unsupported }; + let p = json!({"background": background, "color": rgb, "preset": preset, "guideIDs": [], "changeBackground": true}); + // Reconstruction checks every ordered key, nested class, value type and the evidenced flag. + if artboard_to(COMMAND, &p).is_some_and(|expected| expected.items == d.items) { step(COMMAND, p) } else { unsupported } +} + +/// Export only current-target steps or complete, representable empty-guide settings without quantizing RGB. +pub(super) fn artboard_to(_: &str, p: &Value) -> Option { + let p = p.as_object()?; + let d = desc("null").with("null", target_ref("Lyr ")); + if p.is_empty() { + return Some(d); + } + if p.len() != 5 || p.get("changeBackground") != Some(&Value::Bool(true)) || !p.get("guideIDs")?.as_array()?.is_empty() { + return None; + } + let preset = p.get("preset")?.as_str()?; + let background = match p.get("background")?.as_str()? { + "white" => 1, + "black" => 2, + "transparent" => 3, + "custom" => 4, + _ => return None, + }; + let rgb = p.get("color")?.as_array()?; + if rgb.len() != 3 { + return None; + } + let rgb: Vec = rgb.iter().map(Value::as_f64).collect::>()?; + if !rgb.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n)) { + return None; + } + let color = ["Rd ", "Grn ", "Bl "].into_iter().zip(rgb).fold(desc("RGBC"), |d, (key, n)| d.with(key, D::Double(n * 255.0))); + let board = desc("artboard") + .with("guideIDs", D::List(vec![])) + .with("artboardPresetName", text(preset)) + .with("Clr ", D::Descriptor(color)) + .with("artboardBackgroundType", D::Integer(background)); + Some(d.with("artboard", D::Descriptor(board)).with("changeBackground", D::Integer(1))) +} diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index cf677baf5b..d47a0a0d49 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -567,6 +567,8 @@ fn every_mapped_command_exports_and_imports_back() { ("image.analysis.recordMeasurements", json!({})), ("file.automate.cropAndStraightenPhotos", json!({})), ("file.automate.cropAndStraightenPhotos", json!({"_atnNoTarget": true})), + ("layer.new.artboardFromGroup", json!({})), + ("layer.new.artboardFromGroup", json!({"background":"white","color":[1,1,1],"preset":"","guideIDs":[],"changeBackground":true})), ("layer.new.layerViaCopy", json!({})), ("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("layer.newAdjustmentLayer.hueSaturation", json!({})), diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 1ecdf41e81..ed63f3d333 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -422,6 +422,128 @@ fn crop_parent_runs_once_and_the_kept_helper_stops_the_duplicate_crop_tail() { assert_eq!(s.documents()[0].doc, source); } +/// Two sparse marks leave a transparent gap where the converted board's background is observable. +fn artboard_fixture() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 12, "height": 10, "background": "transparent"})).unwrap(); + let st = s.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let mut child = Layer::raster("Pixels", doc.pixel_format()); + let surface = child.surface_mut().unwrap(); + for rect in [photocraft_doc::Rect::new(2, 2, 3, 3), photocraft_doc::Rect::new(5, 5, 6, 6)] { + surface.fill_rect(rect, &[1.0, 0.0, 0.0, 1.0]); + } + let group = Layer::group("Group", vec![child]); + let id = group.id; + doc.layers = vec![group]; + s.restore_layer_selection(Some(id), &[id], Some(id)).unwrap(); + s +} + +/// The reference's ordered settings keys, with fractional RGB that must not be rounded to hex. +fn artboard_descriptor(background: i32, guides: Vec, flag: D) -> Descriptor { + let color = Descriptor::new("RGBC").with("Rd ", D::Double(63.75)).with("Grn ", D::Double(127.5)).with("Bl ", D::Double(191.25)); + let board = Descriptor::new("artboard") + .with("guideIDs", D::List(guides)) + .with("artboardPresetName", D::Text(UnicodeString::new_nul("iPhone 14"))) + .with("Clr ", D::Descriptor(color)) + .with("artboardBackgroundType", D::Integer(background)); + Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(board)).with("changeBackground", flag) +} + +/// Conversion preserves the group's geometry/content while applying every admitted setting and Undo. +#[test] +fn artboard_empty_guide_settings_roundtrip_apply_background_and_preset_without_resizing() { + for (background, expected) in [(1, [1.0, 1.0, 1.0, 1.0]), (2, [0.0, 0.0, 0.0, 1.0]), (3, [0.0; 4]), (4, [0.25, 0.5, 0.75, 1.0])] { + let mut s = artboard_fixture(); + let before = s.active().unwrap().doc.clone(); + let id = s.active().unwrap().active_layer.unwrap(); + let d = artboard_descriptor(background, vec![], D::Integer(1)); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].0, "layer.new.artboardFromGroup"); + assert_eq!(s.actions.list[0].steps[0].1["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + play(&mut s); + let doc = &s.active().unwrap().doc; + let board = doc.layer(id).unwrap().artboard().unwrap(); + assert_eq!(board.rect, photocraft_doc::Rect::new(2, 2, 6, 6), "preset is a tag, not a request to resize the group"); + assert_eq!(board.preset, "iPhone 14"); + assert_eq!(doc.size, before.size); + assert_eq!(doc.layer(id).unwrap().children(), before.layer(id).unwrap().children()); + let pixel = photocraft_compose::render(doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; + for (actual, expected) in pixel.into_iter().zip(expected) { + assert!((actual - expected).abs() < 0.005, "background {background}: {pixel:?}"); + } + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +/// The target-only call uses the existing menu behavior without synthesizing settings. +#[test] +fn artboard_target_only_form_keeps_existing_native_group_behavior() { + let mut s = artboard_fixture(); + let before = s.active().unwrap().doc.clone(); + let d = Descriptor::new("null").with("null", target()); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps, [("layer.new.artboardFromGroup".into(), json!({}))]); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + play(&mut s); + assert!(s.active().unwrap().doc.layers[0].artboard().is_some()); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Unproved settings remain byte-preserving kept steps and cannot partially edit the document. +#[test] +fn artboard_unproven_associations_flags_and_extra_settings_stay_whole() { + for d in [ + artboard_descriptor(1, vec![D::Integer(7)], D::Integer(1)), + artboard_descriptor(1, vec![], D::Integer(0)), + artboard_descriptor(1, vec![], D::Integer(2)), + artboard_descriptor(1, vec![], D::Boolean(true)), + artboard_descriptor(5, vec![], D::Integer(1)), + artboard_descriptor(1, vec![], D::Integer(1)).with("extra", D::Boolean(true)), + Descriptor::new("null"), + ] { + let mut s = artboard_fixture(); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"].as_array().unwrap().len(), 1); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + 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, "{report}"); + assert_eq!(report["failed"]["id"], "actions.photoshopStep"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + for p in [json!({"layer":1}), json!({"preset":"iPhone 14"}), json!({"guideIDs":[]}), json!({"changeBackground":false})] { + let action = Action::new("A", vec![("layer.new.artboardFromGroup".into(), p)]); + assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); + } +} + +/// An explicit empty association cannot silently acquire the document's spatially inferred guides. +#[test] +fn artboard_empty_association_refuses_existing_guides_before_editing() { + let mut s = artboard_fixture(); + Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.horizontal.push(3.0); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", artboard_descriptor(4, vec![], D::Integer(1))))["unsupported"], json!([])); + let report = s.execute("actions.play", json!({"action":"A","set":"Links"})).unwrap(); + assert_eq!(report["ran"], 0, "{report}"); + assert_eq!(report["failed"]["id"], "layer.new.artboardFromGroup"); + assert!(report["failed"]["error"].as_str().unwrap().contains("without guides")); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + for p in [json!({"guideIDs":[7]}), json!({"guideIDs":false}), json!({"changeBackground":false}), json!({"preset":7})] { + assert!(s.execute("layer.new.artboardFromGroup", p).is_err()); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } +} + #[test] fn reverse_linked_selection_and_clear_style_events_do_their_edits() { for explicit in [false, true] { diff --git a/docs/atn.md b/docs/atn.md index 1c3518c3f6..86ecf7f311 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -18,7 +18,7 @@ layers and documents, newer and older events and files, and a measured reference map yet, with everything needed to implement them without the reference application. -## Supported events (138) +## Supported events (139) | Code | String ID | Label | PhotoCraft command(s) | |---|---|---|---| @@ -160,13 +160,23 @@ the reference application. | (string ID only) | placedLayerRelinkToFile | Relink to File | `layer.smartObjects.relinkToFile` | | (string ID only) | placedLayerReplaceContents | Replace Contents | `layer.smartObjects.replaceContents` | | (string ID only) | shapeBlur | Shape Blur (radius-only form) | `filter.blur.shapeBlur` | +| (string ID only) | artboardFromLayerGroupEvent | Artboard from Group (limited forms below) | `layer.new.artboardFromGroup` | ### Newer event mapping boundaries -The two **Measured** tables under [Newer events](#newer-events-string-id-only) -now map except for `artboardFromLayerGroupEvent`. Its `guideIDs` association and -`changeBackground` behavior are not established by the reference, so the whole -step remains kept. No guide IDs are discarded or guessed. +Twenty-two of the 23 requested forms in the two **Measured** tables under +[Newer events](#newer-events-string-id-only) are fully mapped. Artboard from Group +has an intermediate mapping for the canonical current-layer target alone, or a +complete settings object with empty `guideIDs` and integer `changeBackground: 1`. +The latter requires a document without guides, so the existing spatial guide +export cannot manufacture an association. The preset is retained as a tag without +resizing the group; RGB background channels retain fractional values. Only forms +that reconstruct exactly are admitted. Unrepresented native options refuse export. + +Nonempty guide associations and other flag values remain complete kept steps. +The Artboard row is still unfinished: [Adobe documents guide IDs as object identities](https://developer.adobe.com/photoshop/uxp/2022/ps-reference/classes/guide), +separate from list positions, and the current native model has no corresponding +identity/ownership binding. No guide ID is discarded or treated as an array index. The sixteen target-only events accept an empty descriptor or the current-layer `null` reference (`Lyr `/`Ordn.Trgt`). Save retains which form was imported. From d82f32db36ba4db76e77d6c59a269b3485b2ca16 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 2 Nov 2026 01:01:07 +0100 Subject: [PATCH 08/12] docs(atn): Artboard from Group guides and changeBackground measured; editArtboardEvent Guide ids are session metadata that playback ignores; changeBackground 1 or absent applies the background type and colour, any other value gives white. Background types 1..4 = white, black, transparent, other. The recorded step carries the last used background. Properties panel background changes record editArtboardEvent. Co-Authored-By: Claude Opus 5.5 --- docs/atn.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/docs/atn.md b/docs/atn.md index 61c2403a19..0327969095 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -298,7 +298,7 @@ layer reference, `Ordn.Trgt`); mapping them needs only the event name. | `placedLayerConvertToLinked` | Layer > Smart Objects > Convert to Linked | `null`: target layer; `Usng`: path of the file written | | `placedLayerRelinkToFile` | Layer > Smart Objects > Relink to File | `null`: path; `LyrI`: session layer id | | `placedLayerReplaceContents` | Layer > Smart Objects > Replace Contents | `null`: path; `LyrI`: session layer id | -| `artboardFromLayerGroupEvent` | Layer > New > Artboard from Group | `null` target; `artboard` (object: `guideIDs` list, `artboardPresetName` text, `Clr ` RGB background colour, `artboardBackgroundType` long, 1 = white); `changeBackground` long | +| `artboardFromLayerGroupEvent` | Layer > New > Artboard from Group | `null` target; `artboard` (object: `guideIDs` list, `artboardPresetName` text, `Clr ` RGB background colour, `artboardBackgroundType` long: 1 white, 2 black, 3 transparent, 4 other = `Clr `); `changeBackground` long. See *Artboard from Group: guides and background* below. | | `shapeBlur` | Filter > Blur > Shape Blur | `Rds ` radius in pixels (factory 10); the shape itself comes from the dialog | | Make `contentLayer` with `Usng` = reference to `textLayer` `Ordn.Trgt` | Type > Convert to Shape (recorded as Make, not as `convertToShape`) | `null`: class `contentLayer`; `Usng`: the type layer | @@ -311,6 +311,7 @@ layer reference, `Ordn.Trgt`); mapping them needs only the event name. | Layer > New > Frame from Layers | Make, `null` = class `framedGroupSection`, `From` = layer **by name**, `layerSectionStart`, `layerSectionEnd` long, `Nm ` text | the dialog also shows width and height, which are not recorded | | Layer > New > Artboard from Layers | Make, `null` = class `artboardSection`, `From` = layer target, `layerSectionStart`, `layerSectionEnd`, `Nm ` | | | Layer > New > Artboard | Make, `null` = class `artboardSection`, `layerSectionStart`, `layerSectionEnd`, `Nm `, `artboardRect` (`Top `, `Left`, `Btom`, `Rght` doubles, pixels) | | +| Properties panel > Artboard Background Color (Artboard selected) | `editArtboardEvent` | `null` target; `artboard` (object: `artboardRect` `Top `/`Left`/`Btom`/`Rght` pixels, `guideIDs` list, `artboardPresetName` text, `Clr `, `artboardBackgroundType` 1..4 as above); `changeSizes` long (8 when only the background changed), `changeBackground` 1. `Clr ` is only meaningful with type 4: with types 1..3 it holds the previously used colour | | Layer > Smart Objects > Stack Mode > mode | `applyImageStackPluginRenderer`: `imageStackPlugin` **class** with the mode's code, `Nm ` text = the menu name (localised, except "Entropy") | codes: Range `rang`, Entropy `entr`, Kurtosis `kurt`, Maximum `maxx`, Median `medn`, Minimum `minn`, Mean `avrg`, Skewness `skew`, Standard Deviation `stdv`, Summation `summ`, Variance `vari` | | Layer > Smart Objects > Stack Mode > None | `imageStackConvertSmartObject` | none | | Layer > Video Layers > New Blank Video Layer, Insert Blank Frame, Delete Frame, Show / Hide Altered Video | `addBlankVideoLayer`, `insertBlankFrame`, `deleteFrame`, `showAlteredVideo` / `hideAlteredVideo` | none | @@ -346,6 +347,20 @@ layer reference, `Ordn.Trgt`); mapping them needs only the event name. **Not recorded:** importing or applying inside Image > Variables > Data Sets (only the separate menu commands record). +**Artboard from Group: guides and background** (measured 2026-11-02, script runs and a recording through the menu): + +- **Recorded form:** the menu item opens no dialog. The step always has `guideIDs` empty, `artboardPresetName` "", `changeBackground` 1, and the + background type and colour **last used** for an artboard (the Properties panel choice is sticky: after picking Black for one artboard, the + next Artboard from Group records type 2 and makes a black artboard). Guides in the document do not change the recorded step. +- **`guideIDs`:** session metadata, not a playback input. Guide ids are a counter for the whole application session (a new document's + guides got 5, 6, 7 after an earlier one's 2, 3, 4). Playing the step with the document's own guide ids, an unknown id (99999) or an + empty list gives the same result: no error, the guides stay document guides (`kind` document), and the new artboard's `guideIDs` is empty. + An implementation can ignore the list on playback and write `[]`. +- **`changeBackground`:** 1 or absent applies `artboardBackgroundType` and `Clr `. Any other value (0, 2, 3, -1, 7 tried) ignores both and + makes a white artboard (type 1, `Clr ` 255/255/255), and the step's result then has no `changeBackground` key. + `artboardBackgroundType` absent with `changeBackground` 1 gives type 1 (white). +- The artboard takes the group's bounds; `Clr ` is stored on the artboard as given even when the type is 1..3. + ## Measured through dialogs and recordings Measured on 2026-11-01 in two ways: by running the event with its dialog and pressing OK (the reference From ed71465b8907690ad2a88ad6e8d3eef3a60a41fe Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 16:58:20 -0800 Subject: [PATCH 09/12] Apply measured Artboard background settings without resizing --- crates/engine/src/cmd/artboard_cmds.rs | 20 +- crates/engine/src/cmd/atn_cmds/events.rs | 3 +- .../engine/src/cmd/atn_cmds/steps_artboard.rs | 139 ++++++++++---- crates/engine/src/cmd/atn_cmds/tests.rs | 6 +- crates/engine/tests/it/atn_newer_events.rs | 173 ++++++++++++++---- docs/atn.md | 29 +-- docs/development.md | 6 + 7 files changed, 276 insertions(+), 100 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 89e7a15d00..e8821925e4 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -301,7 +301,7 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } -/// Convert a plain group without resizing its content bounds; refuse unresolved recorded guide associations before editing. +/// Convert a plain group at its content bounds; recorded guide IDs are ignored session metadata. fn artboard_from_group(s: &mut Session, p: &Value) -> Result { let cmd = "layer.new.artboardFromGroup"; let d = s.active().ok_or(EngineError::NoDocument)?; @@ -310,19 +310,17 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { None => String::new(), Some(value) => value.as_str().ok_or_else(|| bad(cmd, "preset must be text"))?.to_string(), }; - if p.get("changeBackground").is_some_and(|value| value != &Value::Bool(true)) { - return Err(bad(cmd, "only an explicit true background-change flag is supported")); - } + let apply_background = match p.get("changeBackground") { + None | Some(Value::Bool(true)) => true, + Some(value) => value.as_i64().and_then(|n| i32::try_from(n).ok()).ok_or_else(|| bad(cmd, "changeBackground must be an integer"))? == 1, + }; if let Some(guides) = p.get("guideIDs") { - if !guides.as_array().is_some_and(Vec::is_empty) { - return Err(bad(cmd, "recorded guide associations are not supported")); - } - if !d.doc.guides.horizontal.is_empty() || !d.doc.guides.vertical.is_empty() { - return Err(bad(cmd, "an explicit empty guide association requires a document without guides")); + if !guides.as_array().is_some_and(|ids| ids.iter().all(|id| id.as_i64().is_some_and(|n| i32::try_from(n).is_ok()))) { + return Err(bad(cmd, "guideIDs must be a list of integers")); } } let canvas = d.doc.bounds(); - let background = background_param(p, cmd)?.unwrap_or_default(); + let background = if apply_background { background_param(p, cmd)?.unwrap_or_default() } else { ArtboardBackground::White }; let rect = s.edit("Artboard from Group", |doc, active| { if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) { return Err(EngineError::Other("artboards are made from a top-level layer group".into())); @@ -720,7 +718,7 @@ pub fn specs() -> Vec { "layer.new.artboardFromGroup", "Artboard from Group…", &["Layer", "New"], - r##"{"layer":id? (a top-level group; default active),"background":…?,"color":[r,g,b]|"#rrggbb"?,"preset":str? (tag only; does not resize),"guideIDs":[]? (recorded empty association; requires no document guides),"changeBackground":true? (recorded apply flag; other values refused)} → {layer, rect}"##, + r##"{"layer":id? (a top-level group; default active),"background":…?,"color":[r,g,b]|"#rrggbb"?,"preset":str? (tag only; does not resize),"guideIDs":[int]? (ignored recording metadata),"changeBackground":int? (1 or absent applies background/color; other integers give white; legacy true = 1)} → {layer, rect}"##, has_plain_group, artboard_from_group ), diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 2cf8017606..60b518fe1c 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -2,7 +2,7 @@ const DIFFUSE_MODE: &[(&str, &str)] = &[("Nrml", "normal"), ("DrkO", "darkenOnly 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, path_text, path_value, ref_class, target_ref}; use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; -use super::steps_artboard::{artboard_from, artboard_to}; +use super::steps_artboard::{artboard_edit_from, artboard_edit_to, artboard_from, artboard_to}; 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, crop_from, crop_to, export_from, export_to, image_size_from, image_size_to, merge_visible_from, merge_visible_to, open_from, open_to, paste_from, paste_to, @@ -500,6 +500,7 @@ pub(super) const EVENTS: &[Event] = &[ from: artboard_from, to: artboard_to, }, + Event { code: "", name: "editArtboardEvent", label: "Edit Artboard", ids: &["layer.artboard.set"], from: artboard_edit_from, to: artboard_edit_to }, Event { code: "", name: "linkSelectedLayers", label: "Link Layers", ids: &["layer.linkLayers"], from: |d| link_from(d, true), to: |_, p| link_to(p, true) }, Event { code: "", diff --git a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs index 8d2964d95a..43115b3b1c 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs @@ -1,45 +1,37 @@ -//! Strict Artboard from Group forms whose settings the existing native model can apply. +//! Measured Artboard conversion and background-only Properties edits. use super::descriptors::{desc, get_num, get_obj, get_text, target_ref, text}; use super::fields::{Mapped, none, step}; use super::{D, Descriptor, Value, json}; -const COMMAND: &str = "layer.new.artboardFromGroup"; +const FROM_GROUP: &str = "layer.new.artboardFromGroup"; +const EDIT: &str = "layer.artboard.set"; -/// Import the current-target form or the verified empty-guide settings form, keeping other forms whole. -pub(super) fn artboard_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - if d.items == desc("null").with("null", target_ref("Lyr ")).items { - return none(COMMAND); - } - let Some(board) = get_obj(d, "artboard") else { return unsupported }; - let Some(color) = get_obj(board, "Clr ") else { return unsupported }; - let Some(preset) = get_text(board, "artboardPresetName") else { return unsupported }; +/// Keep recorded colors and ignored guide IDs, including an omitted background type. +fn settings_from(board: &Descriptor, preset_key: &str) -> Option { + let color = get_obj(board, "Clr ")?; + let preset = get_text(board, "artboardPresetName")?; let background = match board.get("artboardBackgroundType") { - Some(D::Integer(1)) => "white", + None | Some(D::Integer(1)) => "white", Some(D::Integer(2)) => "black", Some(D::Integer(3)) => "transparent", Some(D::Integer(4)) => "custom", - _ => return unsupported, + _ => return None, }; - let rgb: Option> = ["Rd ", "Grn ", "Bl "].iter().map(|key| get_num(color, key).map(|n| n / 255.0)).collect(); - let Some(rgb) = rgb else { return unsupported }; - let p = json!({"background": background, "color": rgb, "preset": preset, "guideIDs": [], "changeBackground": true}); - // Reconstruction checks every ordered key, nested class, value type and the evidenced flag. - if artboard_to(COMMAND, &p).is_some_and(|expected| expected.items == d.items) { step(COMMAND, p) } else { unsupported } + let Some(D::List(guides)) = board.get("guideIDs") else { return None }; + let guides: Vec = guides.iter().map(|v| if let D::Integer(n) = v { Some(*n) } else { None }).collect::>()?; + let rgb: Vec = ["Rd ", "Grn ", "Bl "].iter().map(|key| get_num(color, key).map(|n| n / 255.0)).collect::>()?; + let mut p = json!({"background": background, "color": rgb, "guideIDs": guides}); + p[preset_key] = preset.into(); + if board.get("artboardBackgroundType").is_none() { + p["backgroundTypeOmitted"] = true.into(); + } + Some(p) } -/// Export only current-target steps or complete, representable empty-guide settings without quantizing RGB. -pub(super) fn artboard_to(_: &str, p: &Value) -> Option { - let p = p.as_object()?; - let d = desc("null").with("null", target_ref("Lyr ")); - if p.is_empty() { - return Some(d); - } - if p.len() != 5 || p.get("changeBackground") != Some(&Value::Bool(true)) || !p.get("guideIDs")?.as_array()?.is_empty() { - return None; - } - let preset = p.get("preset")?.as_str()?; +/// Rebuild only settings whose native meaning still agrees with the saved wire form. +fn settings_to(p: &Value, preset_key: &str) -> Option { + let preset = p.get(preset_key)?.as_str()?; let background = match p.get("background")?.as_str()? { "white" => 1, "black" => 2, @@ -47,6 +39,7 @@ pub(super) fn artboard_to(_: &str, p: &Value) -> Option { "custom" => 4, _ => return None, }; + let guides = p.get("guideIDs")?.as_array()?.iter().map(|v| Some(D::Integer(i32::try_from(v.as_i64()?).ok()?))).collect::>>()?; let rgb = p.get("color")?.as_array()?; if rgb.len() != 3 { return None; @@ -56,10 +49,86 @@ pub(super) fn artboard_to(_: &str, p: &Value) -> Option { return None; } let color = ["Rd ", "Grn ", "Bl "].into_iter().zip(rgb).fold(desc("RGBC"), |d, (key, n)| d.with(key, D::Double(n * 255.0))); - let board = desc("artboard") - .with("guideIDs", D::List(vec![])) - .with("artboardPresetName", text(preset)) - .with("Clr ", D::Descriptor(color)) - .with("artboardBackgroundType", D::Integer(background)); - Some(d.with("artboard", D::Descriptor(board)).with("changeBackground", D::Integer(1))) + let board = desc("artboard").with("guideIDs", D::List(guides)).with("artboardPresetName", text(preset)).with("Clr ", D::Descriptor(color)); + match p.get("backgroundTypeOmitted") { + None => Some(board.with("artboardBackgroundType", D::Integer(background))), + Some(Value::Bool(true)) if background == 1 => Some(board), + _ => None, + } +} + +/// Import target-only conversion or complete recorded settings, preserving flag absence and values. +pub(super) fn artboard_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + if d.items == desc("null").with("null", target_ref("Lyr ")).items { + return none(FROM_GROUP); + } + let Some(mut p) = get_obj(d, "artboard").and_then(|b| settings_from(b, "preset")) else { return unsupported }; + match d.get("changeBackground") { + None => {} + Some(D::Integer(n)) => p["changeBackground"] = (*n).into(), + _ => return unsupported, + } + if artboard_to(FROM_GROUP, &p).is_some_and(|expected| expected.items == d.items) { step(FROM_GROUP, p) } else { unsupported } +} + +/// Save complete recorded conversion settings; unknown native options must not disappear. +pub(super) fn artboard_to(_: &str, p: &Value) -> Option { + let fields = p.as_object()?; + let d = desc("null").with("null", target_ref("Lyr ")); + if fields.is_empty() { + return Some(d); + } + if fields.keys().any(|k| !["background", "color", "preset", "guideIDs", "changeBackground", "backgroundTypeOmitted"].contains(&k.as_str())) { + return None; + } + let d = d.with("artboard", D::Descriptor(settings_to(p, "preset")?)); + match p.get("changeBackground") { + None => Some(d), + // Older native action files used true for the recorded integer 1. + Some(Value::Bool(true)) => Some(d.with("changeBackground", D::Integer(1))), + Some(value) => Some(d.with("changeBackground", D::Integer(i32::try_from(value.as_i64()?).ok()?))), + } +} + +/// Background-only edits retain recorded geometry as metadata, never as native resize parameters. +pub(super) fn artboard_edit_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(board) = get_obj(d, "artboard") else { return unsupported }; + let Some(rect) = get_obj(board, "artboardRect") else { return unsupported }; + let Some(mut p) = settings_from(board, "recordedPreset") else { return unsupported }; + let Some(edges) = ["Top ", "Left", "Btom", "Rght"].iter().map(|key| get_num(rect, key)).collect::>>() else { return unsupported }; + p["recordedRect"] = json!(edges); + p["changeSizes"] = 8.into(); + p["changeBackground"] = 1.into(); + if artboard_edit_to(EDIT, &p).is_some_and(|expected| expected.items == d.items) { step(EDIT, p) } else { unsupported } +} + +/// Export only the measured background-edit flags and exact recorded rectangle, without quantization. +pub(super) fn artboard_edit_to(_: &str, p: &Value) -> Option { + let fields = p.as_object()?; + if fields.keys().any(|k| { + !["background", "color", "recordedPreset", "guideIDs", "recordedRect", "changeSizes", "changeBackground", "backgroundTypeOmitted"].contains(&k.as_str()) + }) || p.get("changeSizes")?.as_i64()? != 8 + || p.get("changeBackground")?.as_i64()? != 1 + { + return None; + } + let edges = p.get("recordedRect")?.as_array()?; + if edges.len() != 4 { + return None; + } + let rect = ["Top ", "Left", "Btom", "Rght"] + .into_iter() + .zip(edges) + .try_fold(desc("classFloatRect"), |d, (key, value)| Some(d.with(key, D::Double(value.as_f64().filter(|v| v.is_finite())?))))?; + let mut board = desc("artboard").with("artboardRect", D::Descriptor(rect)); + board.items.extend(settings_to(p, "recordedPreset")?.items); + Some( + desc("null") + .with("null", target_ref("Lyr ")) + .with("artboard", D::Descriptor(board)) + .with("changeSizes", D::Integer(8)) + .with("changeBackground", D::Integer(1)), + ) } diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 71b0edc15d..598f1c2d24 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -576,7 +576,11 @@ fn every_mapped_command_exports_and_imports_back() { ("file.automate.cropAndStraightenPhotos", json!({})), ("file.automate.cropAndStraightenPhotos", json!({"_atnNoTarget": true})), ("layer.new.artboardFromGroup", json!({})), - ("layer.new.artboardFromGroup", json!({"background":"white","color":[1,1,1],"preset":"","guideIDs":[],"changeBackground":true})), + ("layer.new.artboardFromGroup", json!({"background":"white","color":[1,1,1],"preset":"","guideIDs":[],"changeBackground":1})), + ( + "layer.artboard.set", + json!({"background":"custom","color":[0.25,0.5,0.75],"recordedPreset":"","guideIDs":[],"recordedRect":[2,2,6,6],"changeSizes":8,"changeBackground":1}), + ), ("layer.new.layerViaCopy", json!({})), ("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("layer.newAdjustmentLayer.hueSaturation", json!({})), diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index ed63f3d333..816935cce8 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -64,6 +64,7 @@ fn file(event: &str, descriptor: Descriptor) -> Vec { ..Default::default() }], warnings: vec![], + ..Default::default() }) .unwrap() } @@ -442,40 +443,56 @@ fn artboard_fixture() -> Session { /// The reference's ordered settings keys, with fractional RGB that must not be rounded to hex. fn artboard_descriptor(background: i32, guides: Vec, flag: D) -> Descriptor { + Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(artboard_settings(Some(background), guides))).with("changeBackground", flag) +} + +/// Background types 1..3 still record the last custom RGB value; absent type means white. +fn artboard_settings(background: Option, guides: Vec) -> Descriptor { let color = Descriptor::new("RGBC").with("Rd ", D::Double(63.75)).with("Grn ", D::Double(127.5)).with("Bl ", D::Double(191.25)); let board = Descriptor::new("artboard") .with("guideIDs", D::List(guides)) .with("artboardPresetName", D::Text(UnicodeString::new_nul("iPhone 14"))) - .with("Clr ", D::Descriptor(color)) - .with("artboardBackgroundType", D::Integer(background)); - Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(board)).with("changeBackground", flag) + .with("Clr ", D::Descriptor(color)); + match background { + Some(n) => board.with("artboardBackgroundType", D::Integer(n)), + None => board, + } } /// Conversion preserves the group's geometry/content while applying every admitted setting and Undo. #[test] -fn artboard_empty_guide_settings_roundtrip_apply_background_and_preset_without_resizing() { +fn artboard_recorded_flags_and_guides_roundtrip_without_resizing() { for (background, expected) in [(1, [1.0, 1.0, 1.0, 1.0]), (2, [0.0, 0.0, 0.0, 1.0]), (3, [0.0; 4]), (4, [0.25, 0.5, 0.75, 1.0])] { - let mut s = artboard_fixture(); - let before = s.active().unwrap().doc.clone(); - let id = s.active().unwrap().active_layer.unwrap(); - let d = artboard_descriptor(background, vec![], D::Integer(1)); - assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); - assert_eq!(s.actions.list[0].steps[0].0, "layer.new.artboardFromGroup"); - assert_eq!(s.actions.list[0].steps[0].1["color"], json!([0.25, 0.5, 0.75])); - assert_eq!(saved_item(&mut s).descriptor, Some(d)); - play(&mut s); - let doc = &s.active().unwrap().doc; - let board = doc.layer(id).unwrap().artboard().unwrap(); - assert_eq!(board.rect, photocraft_doc::Rect::new(2, 2, 6, 6), "preset is a tag, not a request to resize the group"); - assert_eq!(board.preset, "iPhone 14"); - assert_eq!(doc.size, before.size); - assert_eq!(doc.layer(id).unwrap().children(), before.layer(id).unwrap().children()); - let pixel = photocraft_compose::render(doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; - for (actual, expected) in pixel.into_iter().zip(expected) { - assert!((actual - expected).abs() < 0.005, "background {background}: {pixel:?}"); + for flag in [None, Some(0), Some(1), Some(2), Some(3), Some(-1), Some(7)] { + let mut s = artboard_fixture(); + Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.horizontal.push(3.0); + Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.vertical.push(4.0); + let before = s.active().unwrap().doc.clone(); + let id = s.active().unwrap().active_layer.unwrap(); + let mut d = artboard_descriptor(background, vec![D::Integer(2), D::Integer(99999)], D::Integer(flag.unwrap_or(1))); + if flag.is_none() { + d.items.pop(); + } + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].0, "layer.new.artboardFromGroup"); + assert_eq!(s.actions.list[0].steps[0].1["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + play(&mut s); + let doc = &s.active().unwrap().doc; + let board = doc.layer(id).unwrap().artboard().unwrap(); + assert_eq!(board.rect, photocraft_doc::Rect::new(2, 2, 6, 6), "preset is a tag, not a request to resize the group"); + assert_eq!(board.preset, "iPhone 14"); + assert_eq!(doc.size, before.size); + assert_eq!(doc.layer(id).unwrap().children(), before.layer(id).unwrap().children()); + assert_eq!(doc.guides, before.guides); + let pixel = photocraft_compose::render(doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; + let applied = flag.is_none_or(|n| n == 1); + for (actual, expected) in pixel.into_iter().zip(if applied { expected } else { [1.0; 4] }) { + assert!((actual - expected).abs() < 0.005, "background {background}, flag {flag:?}: {pixel:?}"); + } + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); } - assert!(s.undo()); - assert_eq!(s.active().unwrap().doc, before); } } @@ -496,11 +513,9 @@ fn artboard_target_only_form_keeps_existing_native_group_behavior() { /// Unproved settings remain byte-preserving kept steps and cannot partially edit the document. #[test] -fn artboard_unproven_associations_flags_and_extra_settings_stay_whole() { +fn artboard_unmeasured_types_and_extra_settings_stay_whole() { for d in [ - artboard_descriptor(1, vec![D::Integer(7)], D::Integer(1)), - artboard_descriptor(1, vec![], D::Integer(0)), - artboard_descriptor(1, vec![], D::Integer(2)), + artboard_descriptor(1, vec![D::Double(7.0)], D::Integer(1)), artboard_descriptor(1, vec![], D::Boolean(true)), artboard_descriptor(5, vec![], D::Integer(1)), artboard_descriptor(1, vec![], D::Integer(1)).with("extra", D::Boolean(true)), @@ -523,27 +538,107 @@ fn artboard_unproven_associations_flags_and_extra_settings_stay_whole() { } } -/// An explicit empty association cannot silently acquire the document's spatially inferred guides. +/// Omitted type means white rather than the color-only native call's custom background. #[test] -fn artboard_empty_association_refuses_existing_guides_before_editing() { +fn artboard_omitted_type_defaults_to_white_and_invalid_native_settings_are_atomic() { let mut s = artboard_fixture(); - Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.horizontal.push(3.0); let before = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", artboard_descriptor(4, vec![], D::Integer(1))))["unsupported"], json!([])); - let report = s.execute("actions.play", json!({"action":"A","set":"Links"})).unwrap(); - assert_eq!(report["ran"], 0, "{report}"); - assert_eq!(report["failed"]["id"], "layer.new.artboardFromGroup"); - assert!(report["failed"]["error"].as_str().unwrap().contains("without guides")); + let d = + Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(artboard_settings(None, vec![]))).with("changeBackground", D::Integer(1)); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + let mut changed = s.actions.list[0].steps[0].1.clone(); + changed["background"] = "black".into(); + assert!(atn_cmds::export("Links", &[&Action::new("A", vec![("layer.new.artboardFromGroup".into(), changed)])], &[], false).is_err()); + play(&mut s); + assert_eq!(photocraft_compose::render(&s.active().unwrap().doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0], [1.0; 4]); + assert!(s.undo()); assert_eq!(s.active().unwrap().doc, before); - assert_eq!(s.active().unwrap().history.past_len(), history); - for p in [json!({"guideIDs":[7]}), json!({"guideIDs":false}), json!({"changeBackground":false}), json!({"preset":7})] { + let history = s.active().unwrap().history.past_len(); + for p in [ + json!({"guideIDs":[7.5]}), + json!({"guideIDs":false}), + json!({"changeBackground":false}), + json!({"changeBackground":2147483648i64}), + json!({"preset":7}), + ] { assert!(s.execute("layer.new.artboardFromGroup", p).is_err()); assert_eq!(s.active().unwrap().doc, before); assert_eq!(s.active().unwrap().history.past_len(), history); } } +/// Recorded geometry deliberately differs from the target: flag 8 changes only its background. +fn artboard_edit_descriptor(background: i32, change_sizes: i32) -> Descriptor { + let rect = Descriptor::new("classFloatRect") + .with("Top ", D::Double(40.5)) + .with("Left", D::Double(60.25)) + .with("Btom", D::Double(340.5)) + .with("Rght", D::Double(260.25)); + let mut board = Descriptor::new("artboard").with("artboardRect", D::Descriptor(rect)); + board.items.extend(artboard_settings(Some(background), vec![D::Integer(99999)]).items); + Descriptor::new("null") + .with("null", target()) + .with("artboard", D::Descriptor(board)) + .with("changeSizes", D::Integer(change_sizes)) + .with("changeBackground", D::Integer(1)) +} + +/// Background edits preserve all wire fields, target geometry, children and guides, with one Undo. +#[test] +fn artboard_background_edit_roundtrips_without_replaying_recorded_geometry() { + for (kind, expected) in [(1, [1.0; 4]), (2, [0.0, 0.0, 0.0, 1.0]), (3, [0.0; 4]), (4, [0.25, 0.5, 0.75, 1.0])] { + let mut s = artboard_fixture(); + s.execute("layer.new.artboardFromGroup", json!({})).unwrap(); + Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.horizontal.push(3.0); + let before = s.active().unwrap().doc.clone(); + let id = s.active().unwrap().active_layer.unwrap(); + let history = s.active().unwrap().history.past_len(); + let d = artboard_edit_descriptor(kind, 8); + assert_eq!(load(&mut s, &file("editArtboardEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].0, "layer.artboard.set"); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + play(&mut s); + let doc = &s.active().unwrap().doc; + let board = doc.layer(id).unwrap().artboard().unwrap(); + assert_eq!(board.rect, before.layer(id).unwrap().artboard().unwrap().rect); + assert_eq!(board.preset, before.layer(id).unwrap().artboard().unwrap().preset); + assert_eq!(doc.layer(id).unwrap().children(), before.layer(id).unwrap().children()); + assert_eq!(doc.size, before.size); + assert_eq!(doc.guides, before.guides); + let pixel = photocraft_compose::render(doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; + for (actual, expected) in pixel.into_iter().zip(expected) { + assert!((actual - expected).abs() < 0.005, "{kind}: {pixel:?}"); + } + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +/// Unmeasured geometry modes remain whole; edited native resize options cannot be silently omitted. +#[test] +fn artboard_edit_refuses_unmeasured_modes_and_lossy_native_exports() { + let mut s = artboard_fixture(); + for d in [artboard_edit_descriptor(1, 4), artboard_edit_descriptor(5, 8), artboard_edit_descriptor(1, 8).with("extra", D::Integer(1))] { + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + assert_eq!(load(&mut s, &file("editArtboardEvent", d.clone()))["unsupported"].as_array().unwrap().len(), 1); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + let result = s.execute("actions.play", json!({"set":"Links","action":"A"})).unwrap(); + assert_eq!(result["ran"], 0); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + load(&mut s, &file("editArtboardEvent", artboard_edit_descriptor(4, 8))); + let params = s.actions.list[0].steps[0].1.clone(); + for (key, value) in [("rect", json!([0, 0, 100, 100])), ("preset", json!("iPhone 14")), ("changeSizes", json!(4)), ("changeBackground", json!(0))] { + let mut edited = params.clone(); + edited[key] = value; + assert!(atn_cmds::export("Links", &[&Action::new("A", vec![("layer.artboard.set".into(), edited)])], &[], false).is_err()); + } +} + #[test] fn reverse_linked_selection_and_clear_style_events_do_their_edits() { for explicit in [false, true] { diff --git a/docs/atn.md b/docs/atn.md index c08a76ac5a..00e2852689 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -160,23 +160,26 @@ the reference application. | (string ID only) | placedLayerRelinkToFile | Relink to File | `layer.smartObjects.relinkToFile` | | (string ID only) | placedLayerReplaceContents | Replace Contents | `layer.smartObjects.replaceContents` | | (string ID only) | shapeBlur | Shape Blur (radius-only form) | `filter.blur.shapeBlur` | -| (string ID only) | artboardFromLayerGroupEvent | Artboard from Group (limited forms below) | `layer.new.artboardFromGroup` | +| (string ID only) | artboardFromLayerGroupEvent | Artboard from Group | `layer.new.artboardFromGroup` | +| (string ID only) | editArtboardEvent | Artboard background color (flags 8/1) | `layer.artboard.set` | ### Newer event mapping boundaries -Twenty-two of the 23 requested forms in the two **Measured** tables under -[Newer events](#newer-events-string-id-only) are fully mapped. Artboard from Group -has an intermediate mapping for the canonical current-layer target alone, or a -complete settings object with empty `guideIDs` and integer `changeBackground: 1`. -The latter requires a document without guides, so the existing spatial guide -export cannot manufacture an association. The preset is retained as a tag without -resizing the group; RGB background channels retain fractional values. Only forms -that reconstruct exactly are admitted. Unrepresented native options refuse export. +The 23 requested forms in the two **Measured** tables under +[Newer events](#newer-events-string-id-only) are mapped. Artboard from Group +retains the current-layer target, preset tag, fractional RGB, background type +and integer `changeBackground`, including absence. A flag of 1 or absence applies +the background; other integers give white. An omitted type defaults to white. +Recorded guide IDs are preserved on save and ignored on playback, as measured +in [the guide/background reference below](#newer-events-string-id-only). +Existing document guides remain unchanged. The preset does not resize the group. -Nonempty guide associations and other flag values remain complete kept steps. -The Artboard row is still unfinished: [Adobe documents guide IDs as object identities](https://developer.adobe.com/photoshop/uxp/2022/ps-reference/classes/guide), -separate from list positions, and the current native model has no corresponding -identity/ownership binding. No guide ID is discarded or treated as an array index. +The additional `editArtboardEvent` maps background-only changes with `changeSizes` +8 and `changeBackground` 1. Its rectangle and preset remain recording metadata: +they do not move or resize the target artboard. Colors remain in the saved step +even for white, black or transparent backgrounds. Other flags, extra settings, +unknown targets and forms that cannot reconstruct exactly remain whole kept +steps. Native geometry edits without a matching wire form refuse export. The sixteen target-only events accept an empty descriptor or the current-layer `null` reference (`Lyr `/`Ordn.Trgt`). Save retains which form was imported. diff --git a/docs/development.md b/docs/development.md index 277d20b954..16a92b1312 100644 --- a/docs/development.md +++ b/docs/development.md @@ -631,6 +631,12 @@ PhotoCraft equivalent. Events outside the table load as `actions.photoshopStep` steps that keep the descriptor verbatim (so Save Actions writes them back) and fail at playback with the step's Photoshop name. +Artboard from Group action settings follow [the measured guide/background behavior](atn.md#newer-events-string-id-only): +guide IDs are ignored session metadata, 1 or absent `changeBackground` applies the +background, and other integer flags give white. The group's bounds are retained. +Background-only `editArtboardEvent` uses the existing Artboard edit command; its +recorded rectangle/preset are retained for saving, without resizing the target. + `crates/psd/tests/it/atn_contract.rs` checks the parser's public API against four small, independently encoded fixtures in `crates/psd/tests/fixtures/atn/` (provenance and checksums in its README): `cargo test -p photocraft-psd --test it atn_contract::`. From c06d7d1e34821c2d51c3befb412adba50b4f96ba Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 17:00:10 -0800 Subject: [PATCH 10/12] Simplify recorded guide validation --- crates/engine/src/cmd/artboard_cmds.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index e8821925e4..c3ba0dd2dd 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -314,10 +314,10 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { None | Some(Value::Bool(true)) => true, Some(value) => value.as_i64().and_then(|n| i32::try_from(n).ok()).ok_or_else(|| bad(cmd, "changeBackground must be an integer"))? == 1, }; - if let Some(guides) = p.get("guideIDs") { - if !guides.as_array().is_some_and(|ids| ids.iter().all(|id| id.as_i64().is_some_and(|n| i32::try_from(n).is_ok()))) { - return Err(bad(cmd, "guideIDs must be a list of integers")); - } + if let Some(guides) = p.get("guideIDs") + && !guides.as_array().is_some_and(|ids| ids.iter().all(|id| id.as_i64().is_some_and(|n| i32::try_from(n).is_ok()))) + { + return Err(bad(cmd, "guideIDs must be a list of integers")); } let canvas = d.doc.bounds(); let background = if apply_background { background_param(p, cmd)?.unwrap_or_default() } else { ArtboardBackground::White }; From 7b0d68c8e3cd00d99d3ff7dabcb8a2f8aeee7ff4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 17:42:52 -0800 Subject: [PATCH 11/12] Fix Artboard action round trips and singleton links --- crates/engine/src/cmd/artboard_cmds.rs | 1 + .../engine/src/cmd/atn_cmds/steps_artboard.rs | 35 +++++++-- crates/engine/src/cmd/atn_cmds/tests.rs | 7 ++ .../src/cmd/layer_multi_cmds/structure.rs | 5 +- crates/engine/tests/it/atn_newer_events.rs | 71 ++++++++++++++++++- docs/atn.md | 3 + docs/file-format-parity.md | 4 +- 7 files changed, 115 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index c3ba0dd2dd..bc4d9e8980 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -332,6 +332,7 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { *active = Some(id); Ok(rect) })?; + crate::layer_multi_cmds::set_selection(s, vec![id], Some(id), Some(id))?; Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } diff --git a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs index 43115b3b1c..b03adcffc2 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs @@ -20,8 +20,12 @@ fn settings_from(board: &Descriptor, preset_key: &str) -> Option { }; let Some(D::List(guides)) = board.get("guideIDs") else { return None }; let guides: Vec = guides.iter().map(|v| if let D::Integer(n) = v { Some(*n) } else { None }).collect::>()?; - let rgb: Vec = ["Rd ", "Grn ", "Bl "].iter().map(|key| get_num(color, key).map(|n| n / 255.0)).collect::>()?; + let recorded: Vec = ["Rd ", "Grn ", "Bl "].iter().map(|key| get_num(color, key)).collect::>()?; + let rgb: Vec = recorded.iter().map(|n| n / 255.0).collect(); let mut p = json!({"background": background, "color": rgb, "guideIDs": guides}); + if recorded.iter().zip(&rgb).any(|(recorded, native)| *recorded != native * 255.0) { + p["recordedColor"] = json!(recorded); + } p[preset_key] = preset.into(); if board.get("artboardBackgroundType").is_none() { p["backgroundTypeOmitted"] = true.into(); @@ -48,7 +52,17 @@ fn settings_to(p: &Value, preset_key: &str) -> Option { if !rgb.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n)) { return None; } - let color = ["Rd ", "Grn ", "Bl "].into_iter().zip(rgb).fold(desc("RGBC"), |d, (key, n)| d.with(key, D::Double(n * 255.0))); + let recorded = match p.get("recordedColor") { + None => rgb.iter().map(|n| n * 255.0).collect(), + Some(value) => { + let values = value.as_array()?.iter().map(Value::as_f64).collect::>>()?; + if values.len() != 3 || values.iter().zip(&rgb).any(|(wire, native)| !(0.0..=255.0).contains(wire) || wire / 255.0 != *native) { + return None; + } + values + } + }; + let color = ["Rd ", "Grn ", "Bl "].into_iter().zip(recorded).fold(desc("RGBC"), |d, (key, n)| d.with(key, D::Double(n))); let board = desc("artboard").with("guideIDs", D::List(guides)).with("artboardPresetName", text(preset)).with("Clr ", D::Descriptor(color)); match p.get("backgroundTypeOmitted") { None => Some(board.with("artboardBackgroundType", D::Integer(background))), @@ -72,17 +86,25 @@ pub(super) fn artboard_from(d: &Descriptor) -> Mapped { if artboard_to(FROM_GROUP, &p).is_some_and(|expected| expected.items == d.items) { step(FROM_GROUP, p) } else { unsupported } } -/// Save complete recorded conversion settings; unknown native options must not disappear. +/// Fill behavior-neutral metadata for native settings; unknown options must not disappear. pub(super) fn artboard_to(_: &str, p: &Value) -> Option { let fields = p.as_object()?; let d = desc("null").with("null", target_ref("Lyr ")); if fields.is_empty() { return Some(d); } - if fields.keys().any(|k| !["background", "color", "preset", "guideIDs", "changeBackground", "backgroundTypeOmitted"].contains(&k.as_str())) { + if fields.keys().any(|k| !["background", "color", "recordedColor", "preset", "guideIDs", "changeBackground", "backgroundTypeOmitted"].contains(&k.as_str())) + { return None; } - let d = d.with("artboard", D::Descriptor(settings_to(p, "preset")?)); + let mut settings = p.clone(); + let fields = settings.as_object_mut()?; + let background = if fields.contains_key("color") { "custom" } else { "white" }; + // Native custom-without-color means white. Other types ignore this last-used color. + for (key, value) in [("background", json!(background)), ("color", json!([1.0, 1.0, 1.0])), ("preset", json!("")), ("guideIDs", json!([]))] { + fields.entry(key).or_insert(value); + } + let d = d.with("artboard", D::Descriptor(settings_to(&settings, "preset")?)); match p.get("changeBackground") { None => Some(d), // Older native action files used true for the recorded integer 1. @@ -108,7 +130,8 @@ pub(super) fn artboard_edit_from(d: &Descriptor) -> Mapped { pub(super) fn artboard_edit_to(_: &str, p: &Value) -> Option { let fields = p.as_object()?; if fields.keys().any(|k| { - !["background", "color", "recordedPreset", "guideIDs", "recordedRect", "changeSizes", "changeBackground", "backgroundTypeOmitted"].contains(&k.as_str()) + !["background", "color", "recordedColor", "recordedPreset", "guideIDs", "recordedRect", "changeSizes", "changeBackground", "backgroundTypeOmitted"] + .contains(&k.as_str()) }) || p.get("changeSizes")?.as_i64()? != 8 || p.get("changeBackground")?.as_i64()? != 1 { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 598f1c2d24..19e269a14c 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -737,6 +737,13 @@ fn every_mapped_command_exports_and_imports_back() { Mapped::Unsupported { .. } => panic!("{id} does not import back"), } } + // Partial native backgrounds need no recorded preset, guide IDs or last-used color. + for background in ["white", "black", "transparent", "custom"] { + let item = export_item("layer.new.artboardFromGroup", &json!({"background":background}), "S").unwrap(); + let Mapped::Steps(steps) = (event_for(&item.event).unwrap().from)(item.descriptor.as_ref().unwrap()) else { panic!("Artboard did not import") }; + assert_eq!(steps, [("layer.new.artboardFromGroup".into(), json!({"background":background,"color":[1.0,1.0,1.0],"preset":"","guideIDs":[]}))]); + assert_eq!(export_item(&steps[0].0, &steps[0].1, "S").unwrap().descriptor, item.descriptor); + } // Every command the table claims to export has a case above. let covered: std::collections::BTreeSet<&str> = cases.iter().map(|(id, _)| *id).collect(); let mut missing: Vec<&str> = EVENTS.iter().flat_map(|e| e.ids.iter().copied()).filter(|id| !covered.contains(id)).collect(); diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index f5d4b2325f..228372e293 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -17,13 +17,14 @@ pub(super) fn link_layers(s: &mut Session, p: &Value) -> Result { let same_group = first.is_some() && groups.iter().all(|group| *group == first); // A recorded Link/Unlink is an operation, not the UI's state-dependent toggle. // An explicit repeat must neither allocate a group nor add an undo entry. - if requested == Some(true) && same_group || requested == Some(false) && groups.iter().all(Option::is_none) { + let linked_group = same_group && doc.walk().iter().filter(|(_, _, layer)| layer.link_group == first).take(2).count() == 2; + if requested == Some(true) && linked_group || requested == Some(false) && groups.iter().all(Option::is_none) { return Ok(json!({"linked": requested == Some(true)})); } let label = if requested == Some(false) { "Unlink Layers" } else { "Link Layers" }; let linked = s.edit(label, |doc, _| { // Already one link group (or a single linked layer): unlink, like Photoshop's toggle. - let unlink = requested.map_or(same_group, |linked| !linked); + let unlink = requested.map_or(same_group, |linked| !linked) || sel.len() < 2; // A loaded file can store any id up to u64::MAX, so the new id must not be a bare // max + 1 (#961). Unlinking needs no new id at all. let next = if unlink { None } else { Some(doc.unused_link_group().ok_or_else(|| bad("layer.linkLayers", "no free link group id is left"))?) }; diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 816935cce8..55f6149f55 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -130,6 +130,26 @@ fn unlink_cleans_singletons_preserves_other_groups_and_undoes() { assert!(!one.is_enabled("layer.linkLayers"), "the UI toggle still requires two unlinked layers"); } +/// Explicit Link cleans an orphan without touching a real group's unselected member. +#[test] +fn explicit_link_cleans_a_singleton_but_preserves_a_linked_pair() { + for initial in [vec![Some(77)], vec![Some(77), None], vec![Some(77), Some(77)]] { + let mut s = fixture(&initial, &[0]); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let linked = initial == [Some(77), Some(77)]; + assert_eq!(s.execute("layer.linkLayers", json!({"linked": true})).unwrap()["linked"], linked); + if linked { + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } else { + assert!(groups(&s).iter().all(Option::is_none)); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } + } +} + #[test] fn invalid_link_state_fails_without_editing() { let mut s = fixture(&[None, None], &[0, 1]); @@ -511,6 +531,55 @@ fn artboard_target_only_form_keeps_existing_native_group_behavior() { assert_eq!(s.active().unwrap().doc, before); } +/// A conversion selects its result, so a following Delete cannot remove another selected layer. +#[test] +fn artboard_from_group_replaces_the_previous_layer_selection() { + let mut s = artboard_fixture(); + let group = s.active().unwrap().active_layer.unwrap(); + let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc); + let other = Layer::raster("Other", doc.pixel_format()); + let id = other.id; + doc.layers.push(other); + s.restore_layer_selection(Some(group), &[id, group], Some(id)).unwrap(); + load(&mut s, &file("artboardFromLayerGroupEvent", Descriptor::new("null").with("null", target()))); + play(&mut s); + assert_eq!(s.active().unwrap().selected_layers(), vec![group]); + s.execute("layer.delete", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(id).is_some()); + assert!(s.active().unwrap().doc.layer(group).is_none()); +} + +/// Preserve fractional wire values exactly while playback uses normalized native RGB. +#[test] +fn artboard_fractional_colors_survive_import_save_and_playback() { + let rgb = [7.97, 31.88, 127.6]; + for event in ["artboardFromLayerGroupEvent", "editArtboardEvent"] { + let mut s = artboard_fixture(); + let mut d = if event == "editArtboardEvent" { + s.execute("layer.new.artboardFromGroup", json!({})).unwrap(); + artboard_edit_descriptor(4, 8) + } else { + artboard_descriptor(4, vec![], D::Integer(1)) + }; + let D::Descriptor(board) = &mut d.items.iter_mut().find(|(key, _)| key.is("artboard")).unwrap().1 else { unreachable!() }; + board.items.iter_mut().find(|(key, _)| key.is("Clr ")).unwrap().1 = + D::Descriptor(["Rd ", "Grn ", "Bl "].into_iter().zip(rgb).fold(Descriptor::new("RGBC"), |color, (key, n)| color.with(key, D::Double(n)))); + assert_eq!(load(&mut s, &file(event, d.clone()))["unsupported"], json!([])); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + let (id, mut changed) = s.actions.list[0].steps[0].clone(); + changed["color"][0] = 0.5.into(); + assert!(atn_cmds::export("Links", &[&Action::new("Changed", vec![(id, changed)])], &[], false).is_err()); + let before = s.active().unwrap().doc.clone(); + play(&mut s); + let pixel = photocraft_compose::render(&s.active().unwrap().doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; + for (actual, expected) in pixel.into_iter().zip(rgb.map(|n| n as f32 / 255.0)) { + assert!((actual - expected).abs() < 0.005, "{event}: {pixel:?}"); + } + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + /// Unproved settings remain byte-preserving kept steps and cannot partially edit the document. #[test] fn artboard_unmeasured_types_and_extra_settings_stay_whole() { @@ -532,7 +601,7 @@ fn artboard_unmeasured_types_and_extra_settings_stay_whole() { assert_eq!(s.active().unwrap().doc, before); assert_eq!(s.active().unwrap().history.past_len(), history); } - for p in [json!({"layer":1}), json!({"preset":"iPhone 14"}), json!({"guideIDs":[]}), json!({"changeBackground":false})] { + for p in [json!({"layer":1}), json!({"preset":7}), json!({"guideIDs":[7.5]}), json!({"changeBackground":false})] { let action = Action::new("A", vec![("layer.new.artboardFromGroup".into(), p)]); assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); } diff --git a/docs/atn.md b/docs/atn.md index 00e2852689..9d12d25bd2 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -440,6 +440,9 @@ commands record). makes a white artboard (type 1, `Clr ` 255/255/255), and the step's result then has no `changeBackground` key. `artboardBackgroundType` absent with `changeBackground` 1 gives type 1 (white). - The artboard takes the group's bounds; `Clr ` is stored on the artboard as given even when the type is 1..3. +- PhotoCraft preserves fractional recorded RGB values exactly. Native actions with partial settings export an empty preset and guide list when absent. + An absent native color exports as white: it matches the native custom-color fallback and is visually ignored for white, black and transparent backgrounds. + This is canonical export metadata, not a claim about the reference application's remembered color. Imported steps retain their recorded color instead. ## Measured through dialogs and recordings diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 51e931496a..f31262f535 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -148,8 +148,8 @@ Embedded SVG and PDF-compatible AI/PDF/EPS payloads can use an explicit VectorCr | Date | Change | Summary | |---|---|---| -| 2026-11-01 | minor | `.atn`: 22 newer measured forms mapped, including explicit Link/Unlink, Smart Object file operations, Make Type to Shape, radius-only Shape Blur and the Crop Photos parent; 138 supported event names. Artboard from Group and generated Crop helper steps remain kept. | -| 2026-11-01 | minor | `.atn`: event reference [atn.md](atn.md): the 117 supported events, and measured keys, defaults, ranges and enum values for 101 events not mapped yet | +| 2026-11-01 | minor | `.atn`: 23 newer measured forms mapped, including explicit Link/Unlink, Smart Object file operations, Make Type to Shape, radius-only Shape Blur, Artboard from Group and the Crop Photos parent; 139 supported event names. Artboard forms with unmeasured settings and generated Crop helper steps remain kept. | +| 2026-11-01 | minor | `.atn`: event reference [atn.md](atn.md): the 139 supported events, and measured keys, defaults, ranges and enum values for 101 events not mapped yet | | 2026-10-26 | minor | Embedded AI/PDF/EPS save-back retains native format and a separate source-bound display preview; original sources remain undoable. Native Adobe interoperability and standalone EPS/DCS remain unverified; no corpus floor or percentage changed. | | 2026-10-22 | minor | Embedded PSD vectors gain explicit bounded SVG editor/save-back; standalone EPS/DCS and native-format fidelity remain open. | | 2026-10-22 | minor | TIFF: flat pages up to 300,000 px a side open (was 2^30 px, about 32,768²): `codecs::TiffBands` decodes a group of rows at a time into the layer's tiles. The 117,504 × 22,464 px banner from #8456 opens in 3.3 s at 11.45 GB peak for a 10.56 GB layer; 30,000² 6.8 s / 6.43 GB → 1.1 s / 3.86 GB; 36 MP 220 → 52 ms. Layered TIFFs still decode whole (#8169) | From 3746a341e496bde2b96818b7136396b9c6727b1b Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 18:34:08 -0800 Subject: [PATCH 12/12] Preserve implicit white Artboard backgrounds in actions --- .../engine/src/cmd/atn_cmds/steps_artboard.rs | 3 +++ crates/engine/src/cmd/atn_cmds/tests.rs | 4 ++-- crates/engine/tests/it/atn_newer_events.rs | 17 +++++++++++++++++ docs/atn.md | 1 + 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs index b03adcffc2..de7b7be9e3 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs @@ -99,6 +99,9 @@ pub(super) fn artboard_to(_: &str, p: &Value) -> Option { } let mut settings = p.clone(); let fields = settings.as_object_mut()?; + if !fields.contains_key("color") && fields.get("background").and_then(Value::as_str) == Some("custom") { + fields.insert("background".into(), json!("white")); + } let background = if fields.contains_key("color") { "custom" } else { "white" }; // Native custom-without-color means white. Other types ignore this last-used color. for (key, value) in [("background", json!(background)), ("color", json!([1.0, 1.0, 1.0])), ("preset", json!("")), ("guideIDs", json!([]))] { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 19e269a14c..91566906db 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -738,10 +738,10 @@ fn every_mapped_command_exports_and_imports_back() { } } // Partial native backgrounds need no recorded preset, guide IDs or last-used color. - for background in ["white", "black", "transparent", "custom"] { + for (background, imported_background) in [("white", "white"), ("black", "black"), ("transparent", "transparent"), ("custom", "white")] { let item = export_item("layer.new.artboardFromGroup", &json!({"background":background}), "S").unwrap(); let Mapped::Steps(steps) = (event_for(&item.event).unwrap().from)(item.descriptor.as_ref().unwrap()) else { panic!("Artboard did not import") }; - assert_eq!(steps, [("layer.new.artboardFromGroup".into(), json!({"background":background,"color":[1.0,1.0,1.0],"preset":"","guideIDs":[]}))]); + assert_eq!(steps, [("layer.new.artboardFromGroup".into(), json!({"background":imported_background,"color":[1.0,1.0,1.0],"preset":"","guideIDs":[]}))]); assert_eq!(export_item(&steps[0].0, &steps[0].1, "S").unwrap().descriptor, item.descriptor); } // Every command the table claims to export has a case above. diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 55f6149f55..e864751340 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -549,6 +549,23 @@ fn artboard_from_group_replaces_the_previous_layer_selection() { assert!(s.active().unwrap().doc.layer(group).is_none()); } +/// A missing custom color means White; an explicit white color remains Custom through save/load. +#[test] +fn artboard_partial_custom_background_preserves_the_document_variant() { + for params in [json!({"background":"custom"}), json!({"background":"custom","color":[1,1,1]})] { + let mut s = artboard_fixture(); + s.execute("layer.new.artboardFromGroup", params.clone()).unwrap(); + let expected = s.active().unwrap().doc.clone(); + assert!(s.undo()); + let action = Action::new("A", vec![("layer.new.artboardFromGroup".into(), params)]); + let (bytes, skipped) = atn_cmds::export("Links", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty()); + assert_eq!(load(&mut s, &bytes)["unsupported"], json!([])); + play(&mut s); + assert_eq!(s.active().unwrap().doc, expected); + } +} + /// Preserve fractional wire values exactly while playback uses normalized native RGB. #[test] fn artboard_fractional_colors_survive_import_save_and_playback() { diff --git a/docs/atn.md b/docs/atn.md index 9d12d25bd2..a4f3cd72f0 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -442,6 +442,7 @@ commands record). - The artboard takes the group's bounds; `Clr ` is stored on the artboard as given even when the type is 1..3. - PhotoCraft preserves fractional recorded RGB values exactly. Native actions with partial settings export an empty preset and guide list when absent. An absent native color exports as white: it matches the native custom-color fallback and is visually ignored for white, black and transparent backgrounds. + A custom background without a color uses the White variant (type 1); an explicit custom white color keeps type 4. This is canonical export metadata, not a claim about the reference application's remembered color. Imported steps retain their recorded color instead. ## Measured through dialogs and recordings