diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 0ad2bc2f92..f9e31e4cd0 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -301,22 +301,38 @@ 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 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)?; let id = crate::commands::layer_param(s, p)?; + 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(), + }; + 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") + && !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, "layer.new.artboardFromGroup")?.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())); } 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) })?; + 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()]})) } @@ -697,7 +713,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":[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.rs b/crates/engine/src/cmd/atn_cmds.rs index c2bd3fcf6d..41078987cd 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -33,6 +33,7 @@ mod events; mod fields; mod files; +mod steps_artboard; mod steps_channels; mod steps_direct_adjustments; mod steps_distort; diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 7c78e4a7f2..87d327c2e5 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -1,8 +1,10 @@ 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::{class, code, desc, get_bool, get_obj, get_ref, jbool, layer_ref, layer_target, ref_class, trimmed}; +use super::descriptors::{ + class, code, desc, get_bool, get_obj, get_ref, jbool, layer_ref, layer_target, path_text, path_value, ref_class, target_ref, trimmed, +}; use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; - +use super::steps_artboard::{artboard_edit_from, artboard_edit_to, artboard_from, artboard_to}; use super::steps_channels::{match_color_from, match_color_to, merge_spot_from, merge_spot_to, split_from, split_to, trap_from, trap_to}; use super::steps_direct_adjustments::{gradient_from, gradient_to, replace_from, replace_to}; use super::steps_distort::{PINCH, POLAR, SPHERIZE, TWIRL, ZIGZAG, keys_from, keys_to, wave_from, wave_to}; @@ -24,7 +26,7 @@ use super::steps_layer::{ use super::steps_make::{locking_from, locking_to, make_from, make_to, set_from, set_to}; use super::steps_other::{DE_INTERLACE, HSB_HSL, bare_from, bare_to, custom_from, custom_to, enums_from, enums_to}; use super::tables::{NOISE, OFFSET_FILL, SMART_BLUR_MODE, SMART_BLUR_QUALITY, TRIM}; -use super::{AtnEvent, D, Descriptor, Id, ReferenceItem, STOP_MESSAGE, Value, json}; +use super::{AtnEvent, D, Descriptor, Id, Map, ReferenceItem, 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 @@ -226,6 +228,124 @@ fn spell_check_to(_: &str, p: &Value) -> Option { Some(desc("null").with("null", spell_check_ref()).with("Usng", D::Descriptor(desc("spellCheck").with("checkAll", D::Boolean(all))))) } +// 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"; + +/// 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() { + p.insert(NO_TARGET.into(), Value::Bool(true)); + } else if d.items != desc("null").with("null", target_ref("Lyr ")).items { + return None; + } + 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 "))), + Some(Value::Bool(true)) => Some(desc("null")), + Some(_) => None, + } +} + +// 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; + } + target_descriptor(p) +} + +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 }; + 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 } +} + +/// 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; + } + 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. +/// 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; + } + 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" }; + 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 } +} + +/// 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()?; + 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) => { @@ -240,6 +360,12 @@ macro_rules! selection_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] = &[ selection_event!("AddT", "addTo", "Add to Selection", &["select.rect"], |d| super::steps_selection::selection_from(d, "add"), |_, p| { @@ -392,6 +518,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", @@ -636,11 +763,39 @@ 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"), + 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: "editArtboardEvent", label: "Edit Artboard", ids: &["layer.artboard.set"], from: artboard_edit_from, to: artboard_edit_to }, + 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", label: "Make", ids: &[ + "type.convertToShape", "layer.new.layer", "layer.new.group", "layer.groupLayers", @@ -755,6 +910,42 @@ 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", + 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 ", 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..de7b7be9e3 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs @@ -0,0 +1,160 @@ +//! 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 FROM_GROUP: &str = "layer.new.artboardFromGroup"; +const EDIT: &str = "layer.artboard.set"; + +/// 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") { + None | Some(D::Integer(1)) => "white", + Some(D::Integer(2)) => "black", + Some(D::Integer(3)) => "transparent", + Some(D::Integer(4)) => "custom", + _ => return None, + }; + 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 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(); + } + Some(p) +} + +/// 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, + "transparent" => 3, + "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; + } + 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 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))), + 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 } +} + +/// 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", "recordedColor", "preset", "guideIDs", "changeBackground", "backgroundTypeOmitted"].contains(&k.as_str())) + { + return None; + } + 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!([]))] { + 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. + 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", "recordedColor", "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/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 07c71040a5..9ce3bbb8f7 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -172,8 +172,16 @@ 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")]; -/// Import Make events only when their geometry and options can be represented faithfully. +fn type_shape_descriptor() -> Descriptor { + desc("null").with("null", class_ref("contentLayer")).with("Usng", target_ref("textLayer")) +} + +/// Import Make events only when their geometry and options can be represented faithfully, +/// 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"); + } if let Some(mapped) = duplicate_layer_from_descriptor(d) { return mapped; } @@ -300,8 +308,12 @@ fn recorded_percent(opacity: f64) -> f64 { if (level - level.round()).abs() < 1e-6 && (whole * 255.0 / 100.0).round() == level.round() { whole } else { percent } } -/// Write a creation step, refusing native options the target descriptor cannot carry. +/// Write a creation step, refusing native options the target descriptor cannot carry; 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()); + } 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 78a9c3d528..adfdc38c92 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -617,8 +617,33 @@ 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})), + ("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!({})), + ("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":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!({})), @@ -707,6 +732,14 @@ 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"})), + ("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", "scaleStyles": true})), ("file.placeEmbedded", json!({"path": "/tmp/logo.png", "scale": 50})), @@ -860,6 +893,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, 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":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. 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.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..228372e293 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -3,13 +3,28 @@ use super::{Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, Re // ---------- structural commands ---------- -pub(super) fn link_layers(s: &mut Session) -> Result { +/// 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, + 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. + 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 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) || 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/src/cmd/photo_cmds.rs b/crates/engine/src/cmd/photo_cmds.rs index 2aa2a383b8..9dd7da094b 100644 --- a/crates/engine/src/cmd/photo_cmds.rs +++ b/crates/engine/src/cmd/photo_cmds.rs @@ -874,7 +874,9 @@ 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)?; let doc = st.doc.clone(); let fmt = doc.pixel_format(); @@ -942,13 +944,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 +990,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/src/session/execute.rs b/crates/engine/src/session/execute.rs index 239fa2124f..ce8fc43666 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -160,6 +160,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..e864751340 --- /dev/null +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -0,0 +1,1203 @@ +//! #10700: recorded Link and Unlink must not replay as a state-dependent toggle. +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}, + 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 { + target_class("Lyr ") +} + +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(ordinal), + }]) +} + +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: 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![], + ..Default::default() + }) + .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() +} + +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}"); +} + +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]); + 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"); +} + +/// 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]); + 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!([])); + play(&mut replay); + 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(); + play(&mut replay); + 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").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)), + 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()); + } +} + +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"), + ("CropPhotosAuto0001", "file.automate.cropAndStraightenPhotos"), +]; + +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()); + } +} + +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); +} + +/// 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 { + 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)); + 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_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])] { + 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); + } + } +} + +/// 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); +} + +/// 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()); +} + +/// 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() { + 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() { + for d in [ + 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)), + 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":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()); + } +} + +/// Omitted type means white rather than the color-only native call's custom background. +#[test] +fn artboard_omitted_type_defaults_to_white_and_invalid_native_settings_are_atomic() { + let mut s = artboard_fixture(); + let before = s.active().unwrap().doc.clone(); + 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); + 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] { + 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); + } +} + +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"] { + 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/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 69d8ffc4ab..8e8553d509 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -4,6 +4,7 @@ mod affinity; mod artboard_export_names; mod atn_crystallize_cell_size; mod atn_direct_adjustments; +mod atn_newer_events; mod atn_reference_forms; mod atn_ripple_amount; mod atn_selective_color; diff --git a/docs/atn.md b/docs/atn.md index bda87a551d..24fac80a92 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 (146) +## Supported events (168) | Code | String ID | Label | PhotoCraft command(s) | |---|---|---|---| @@ -99,7 +99,7 @@ the reference application. | `CtTL` | cutToLayer | Layer Via Cut | `layer.new.layerViaCut` | | `LnsF` | lensFlare | Lens Flare | `filter.render.lensFlare` | | `Lvls` | levels | Levels | `image.adjustments.levels`, `image.autoTone`, `image.autoContrast` | -| `Mk ` | make | Make | `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot` | +| `Mk ` | make | Make | `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape` | | (string ID only) | animationFramesFromLayers | Make Frames from Layers | | | (string ID only) | matchColor | Match Color | `image.adjustments.matchColor` | | `Mxm ` | maximum | Maximum | `filter.other.maximum` | @@ -168,6 +168,83 @@ the reference application. | (string ID only) | vibrance | Vibrance | `image.adjustments.vibrance` | | `Wave` | wave | Wave | `filter.distort.wave` | | `ZgZg` | zigZag | ZigZag | `filter.distort.zigZag` | +| (string ID only) | reverse | Reverse | `layer.arrange.reverse` | +| (string ID only) | linkSelectedLayers | Link Layers (toggles, as measured) | `layer.linkLayers` | +| (string ID only) | unlinkSelectedLayers | Unlink Layers | `layer.linkLayers {"linked":false}` | +| (string ID only) | selectLinkedLayers | Select Linked Layers | `layer.selectLinkedLayers` | +| (string ID only) | disableLayerStyle | Clear Layer Style | `layer.layerStyle.clear` | +| (string ID only) | placedLayerMakeCopy | New Smart Object via Copy | `layer.smartObjects.newSmartObjectViaCopy` | +| (string ID only) | placedLayerConvertToLayers | Convert to Layers | `layer.smartObjects.convertToLayers` | +| (string ID only) | placedLayerConvertToEmbedded | Embed Linked | `layer.smartObjects.convertToEmbedded` | +| (string ID only) | placedLayerUpdateAllModified | Update All Modified Content | `layer.smartObjects.updateAllModifiedContent` | +| (string ID only) | rasterizeAll | Rasterize All Layers | `layer.rasterize.allLayers` | +| (string ID only) | addBlankVideoLayer | New Blank Video Layer | `layer.videoLayers.newBlankVideoLayer` | +| (string ID only) | isolateLayers | Isolate Layers | `select.isolateLayers` | +| (string ID only) | textLoadDefaultTypeStyles | Load Default Type Styles | `type.loadDefaultTypeStyles` | +| (string ID only) | textSaveDefaultTypeStyles | Save Default Type Styles | `type.saveDefaultTypeStyles` | +| (string ID only) | recordMeasurements | Record Measurements | `image.analysis.recordMeasurements` | +| (string ID only) | CropPhotosAuto0001 | Crop and Straighten Photos | `file.automate.cropAndStraightenPhotos` | +| (string ID only) | placedLayerExportContents | Export Contents | `layer.smartObjects.exportContents` | +| (string ID only) | placedLayerConvertToLinked | Convert to Linked | `layer.smartObjects.convertToLinked` | +| (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 | `layer.new.artboardFromGroup` | +| (string ID only) | editArtboardEvent | Artboard background color (flags 8/1) | `layer.artboard.set` | + +### Newer event mapping boundaries + +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. + +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. +Unknown targets or extra keys stay complete kept steps. Unrepresented native +options are refused on export. Playback uses the native command's preconditions +and current state. Isolate Layers toggles the panel view; type defaults remain +session settings; Record Measurements uses the current measurement configuration. + +Link Layers plays as the toggle the reference application performs (played twice on the same +layers it links, then unlinks them; see the measurements below). Unlink is explicit and +idempotent: it keeps an already unlinked selection unlinked and clears singleton link groups. +Undo restores an edit. Explicit native layer lists cannot be exported as these targeted events. + +The four Smart Object file events use Open/Place's `Pth `/`txtu` path encoding. +Export Contents uses `null` for its path; Convert to Linked uses the current-layer +`null` reference and `Usng` for its path; Relink and Replace use `null` for the path. +A positive integer `LyrI` is a recording-session hint, never a PhotoCraft layer +identity, and is omitted on save under the normalization rule below. Undecodable +paths or extra keys keep the entire step. File access happens at playback; a +missing or unusable file reports the native command's error. + +Convert Type to Shape retains Make's `contentLayer` class reference and `Usng` +target `textLayer` reference; it does not export a separate `convertToShape` +event. Other Make mappings, including Solid Color and Pattern fills, are unchanged. +Shape Blur maps only the measured radius form (`Rds ` pixels, 5–1000; omitted +radius uses the native factory value 10). Later dialog forms carrying +`customShape` or `keyOriginType` remain kept. Native explicit shape choices cannot +be saved as radius-only descriptors; no custom asset lookup or new kernel is added. + +Crop and Straighten Photos executes the native scan operation once, creating one +document per photo found inside the selection and leaving the source unchanged. +It requires a selected, visible layer with no pixel or full lock, including +inherited group state, and remains unavailable for Indexed Color documents. +The separate `CropPhotos0001` helper remains a complete kept Photoshop step. +Playback stops at that enabled helper before subsequent duplicate/crop steps can +run. This covers the parent event, not complete recordings with generated helpers. ### Settings retained by mapped events @@ -314,7 +391,7 @@ Nested values as recorded (example values): ## 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 @@ -400,13 +477,16 @@ name form today; the index, ID and ordinal forms load as kept steps. ## Newer events (string ID only) -The events the reference application records for the menu items PhotoCraft has that are neither mapped -nor in the reference below: 63 candidates from PhotoCraft's menu catalogue, each run in the reference +The original survey covered menu events that were neither mapped nor in the reference below: +63 candidates from PhotoCraft's menu catalogue, each run in the reference application without a dialog on a document prepared for it (layers, a selection, a smart object, a type layer, a layer style or a group) on 2026-11-01. 27 more menu items record no event of their own (puppet warp and warp splits, combine shapes, scripts such as Load Files into Stack and Statistics, artboard and video export, missing-font commands): they cannot be recorded or play as a script step. +The two Measured tables remain the recording reference. The mappings and remaining +limits added since that survey are listed under [Newer event mapping boundaries](#newer-event-mapping-boundaries). + **Measured: no settings beyond the target.** A step with these events carries at most `null` (the target layer reference, `Ordn.Trgt`); mapping them needs only the event name. @@ -510,6 +590,11 @@ commands record). with more than one layer is refused. - **Load Actions** with a set whose name is already in the panel adds a second set of that name; nothing is replaced. +- 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 Measured on 2026-11-01 in two ways: by running the event with its dialog and pressing OK (the reference @@ -746,6 +831,7 @@ and string ID, the PhotoCraft command it maps to (or should map to), and every k order it is recorded, with type, unit, factory default and allowed values. The Supported events table says which of them PhotoCraft maps today; for the others an entry has everything needed to implement them. When an event is implemented, add it to that table in the same change. +Current support and limits of the newer events are described under [Newer event mapping boundaries](#newer-event-mapping-boundaries). ### How these values were measured diff --git a/docs/development.md b/docs/development.md index df313b1805..e9400a1b20 100644 --- a/docs/development.md +++ b/docs/development.md @@ -643,6 +643,12 @@ the document profile, retains alpha and untouched native pixels, and uses one un A zero tone shift validates its inputs without changing pixels. The existing RGB option keeps its previous behavior. Explicit Lab bounds require a composite pixel-layer target. +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 small, independently encoded version-16 fixtures (the version-12 ones are read by `atn_v12::`) in `crates/psd/tests/fixtures/atn/` (provenance and checksums in its README): `cargo test -p photocraft-psd --test it atn_contract::`. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index efd87a88fa..dad1a33192 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -151,6 +151,7 @@ The original reference entry retains its source date and historical totals; curr | Date | Change | Summary | |---|---|---| +| 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; supported in batch 13; Link Layers keeps the measured toggle. Artboard forms with unmeasured settings and generated Crop helper steps remain kept. | | 2026-11-01 | minor | Recorded direct Gradient Map and Lab-range Replace Color load, play and retain their measured settings on save; unsupported forms remain preserved (part of #10607). | | 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-10-31 | minor | `.atn` Group B: four Render events load, play and save; 120 supported and 97 unmapped. Supported-table columns corrected against the event registry; the original 117/101 reference entry remains historical. |