diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 89e7a15d009..e8821925e45 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -301,7 +301,7 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } -/// Convert a plain group without resizing its content bounds; refuse unresolved recorded guide associations before editing. +/// Convert a plain group at its content bounds; recorded guide IDs are ignored session metadata. fn artboard_from_group(s: &mut Session, p: &Value) -> Result { let cmd = "layer.new.artboardFromGroup"; let d = s.active().ok_or(EngineError::NoDocument)?; @@ -310,19 +310,17 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { None => String::new(), Some(value) => value.as_str().ok_or_else(|| bad(cmd, "preset must be text"))?.to_string(), }; - if p.get("changeBackground").is_some_and(|value| value != &Value::Bool(true)) { - return Err(bad(cmd, "only an explicit true background-change flag is supported")); - } + let apply_background = match p.get("changeBackground") { + None | Some(Value::Bool(true)) => true, + Some(value) => value.as_i64().and_then(|n| i32::try_from(n).ok()).ok_or_else(|| bad(cmd, "changeBackground must be an integer"))? == 1, + }; if let Some(guides) = p.get("guideIDs") { - if !guides.as_array().is_some_and(Vec::is_empty) { - return Err(bad(cmd, "recorded guide associations are not supported")); - } - if !d.doc.guides.horizontal.is_empty() || !d.doc.guides.vertical.is_empty() { - return Err(bad(cmd, "an explicit empty guide association requires a document without guides")); + if !guides.as_array().is_some_and(|ids| ids.iter().all(|id| id.as_i64().is_some_and(|n| i32::try_from(n).is_ok()))) { + return Err(bad(cmd, "guideIDs must be a list of integers")); } } let canvas = d.doc.bounds(); - let background = background_param(p, cmd)?.unwrap_or_default(); + let background = if apply_background { background_param(p, cmd)?.unwrap_or_default() } else { ArtboardBackground::White }; let rect = s.edit("Artboard from Group", |doc, active| { if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) { return Err(EngineError::Other("artboards are made from a top-level layer group".into())); @@ -720,7 +718,7 @@ pub fn specs() -> Vec { "layer.new.artboardFromGroup", "Artboard from Group…", &["Layer", "New"], - r##"{"layer":id? (a top-level group; default active),"background":…?,"color":[r,g,b]|"#rrggbb"?,"preset":str? (tag only; does not resize),"guideIDs":[]? (recorded empty association; requires no document guides),"changeBackground":true? (recorded apply flag; other values refused)} → {layer, rect}"##, + r##"{"layer":id? (a top-level group; default active),"background":…?,"color":[r,g,b]|"#rrggbb"?,"preset":str? (tag only; does not resize),"guideIDs":[int]? (ignored recording metadata),"changeBackground":int? (1 or absent applies background/color; other integers give white; legacy true = 1)} → {layer, rect}"##, has_plain_group, artboard_from_group ), diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 2cf80176069..60b518fe1cf 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -2,7 +2,7 @@ const DIFFUSE_MODE: &[(&str, &str)] = &[("Nrml", "normal"), ("DrkO", "darkenOnly use super::adjustments::{adjustment_by_class, adjustment_steps, levels_from, levels_to, shadows_highlights_from, shadows_highlights_to}; use super::descriptors::{desc, get_bool, get_ref, jbool, layer_ref, layer_target, path_text, path_value, ref_class, target_ref}; use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; -use super::steps_artboard::{artboard_from, artboard_to}; +use super::steps_artboard::{artboard_edit_from, artboard_edit_to, artboard_from, artboard_to}; use super::steps_doc::{ align_from, align_to, canvas_size_from, canvas_size_to, close_from, close_to, conditional_from, conditional_to, convert_mode_from, convert_mode_to, crop_from, crop_to, export_from, export_to, image_size_from, image_size_to, merge_visible_from, merge_visible_to, open_from, open_to, paste_from, paste_to, @@ -500,6 +500,7 @@ pub(super) const EVENTS: &[Event] = &[ from: artboard_from, to: artboard_to, }, + Event { code: "", name: "editArtboardEvent", label: "Edit Artboard", ids: &["layer.artboard.set"], from: artboard_edit_from, to: artboard_edit_to }, Event { code: "", name: "linkSelectedLayers", label: "Link Layers", ids: &["layer.linkLayers"], from: |d| link_from(d, true), to: |_, p| link_to(p, true) }, Event { code: "", diff --git a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs index 8d2964d95ad..43115b3b1c2 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs @@ -1,45 +1,37 @@ -//! Strict Artboard from Group forms whose settings the existing native model can apply. +//! Measured Artboard conversion and background-only Properties edits. use super::descriptors::{desc, get_num, get_obj, get_text, target_ref, text}; use super::fields::{Mapped, none, step}; use super::{D, Descriptor, Value, json}; -const COMMAND: &str = "layer.new.artboardFromGroup"; +const FROM_GROUP: &str = "layer.new.artboardFromGroup"; +const EDIT: &str = "layer.artboard.set"; -/// Import the current-target form or the verified empty-guide settings form, keeping other forms whole. -pub(super) fn artboard_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - if d.items == desc("null").with("null", target_ref("Lyr ")).items { - return none(COMMAND); - } - let Some(board) = get_obj(d, "artboard") else { return unsupported }; - let Some(color) = get_obj(board, "Clr ") else { return unsupported }; - let Some(preset) = get_text(board, "artboardPresetName") else { return unsupported }; +/// Keep recorded colors and ignored guide IDs, including an omitted background type. +fn settings_from(board: &Descriptor, preset_key: &str) -> Option { + let color = get_obj(board, "Clr ")?; + let preset = get_text(board, "artboardPresetName")?; let background = match board.get("artboardBackgroundType") { - Some(D::Integer(1)) => "white", + None | Some(D::Integer(1)) => "white", Some(D::Integer(2)) => "black", Some(D::Integer(3)) => "transparent", Some(D::Integer(4)) => "custom", - _ => return unsupported, + _ => return None, }; - let rgb: Option> = ["Rd ", "Grn ", "Bl "].iter().map(|key| get_num(color, key).map(|n| n / 255.0)).collect(); - let Some(rgb) = rgb else { return unsupported }; - let p = json!({"background": background, "color": rgb, "preset": preset, "guideIDs": [], "changeBackground": true}); - // Reconstruction checks every ordered key, nested class, value type and the evidenced flag. - if artboard_to(COMMAND, &p).is_some_and(|expected| expected.items == d.items) { step(COMMAND, p) } else { unsupported } + let Some(D::List(guides)) = board.get("guideIDs") else { return None }; + let guides: Vec = guides.iter().map(|v| if let D::Integer(n) = v { Some(*n) } else { None }).collect::>()?; + let rgb: Vec = ["Rd ", "Grn ", "Bl "].iter().map(|key| get_num(color, key).map(|n| n / 255.0)).collect::>()?; + let mut p = json!({"background": background, "color": rgb, "guideIDs": guides}); + p[preset_key] = preset.into(); + if board.get("artboardBackgroundType").is_none() { + p["backgroundTypeOmitted"] = true.into(); + } + Some(p) } -/// Export only current-target steps or complete, representable empty-guide settings without quantizing RGB. -pub(super) fn artboard_to(_: &str, p: &Value) -> Option { - let p = p.as_object()?; - let d = desc("null").with("null", target_ref("Lyr ")); - if p.is_empty() { - return Some(d); - } - if p.len() != 5 || p.get("changeBackground") != Some(&Value::Bool(true)) || !p.get("guideIDs")?.as_array()?.is_empty() { - return None; - } - let preset = p.get("preset")?.as_str()?; +/// Rebuild only settings whose native meaning still agrees with the saved wire form. +fn settings_to(p: &Value, preset_key: &str) -> Option { + let preset = p.get(preset_key)?.as_str()?; let background = match p.get("background")?.as_str()? { "white" => 1, "black" => 2, @@ -47,6 +39,7 @@ pub(super) fn artboard_to(_: &str, p: &Value) -> Option { "custom" => 4, _ => return None, }; + let guides = p.get("guideIDs")?.as_array()?.iter().map(|v| Some(D::Integer(i32::try_from(v.as_i64()?).ok()?))).collect::>>()?; let rgb = p.get("color")?.as_array()?; if rgb.len() != 3 { return None; @@ -56,10 +49,86 @@ pub(super) fn artboard_to(_: &str, p: &Value) -> Option { return None; } let color = ["Rd ", "Grn ", "Bl "].into_iter().zip(rgb).fold(desc("RGBC"), |d, (key, n)| d.with(key, D::Double(n * 255.0))); - let board = desc("artboard") - .with("guideIDs", D::List(vec![])) - .with("artboardPresetName", text(preset)) - .with("Clr ", D::Descriptor(color)) - .with("artboardBackgroundType", D::Integer(background)); - Some(d.with("artboard", D::Descriptor(board)).with("changeBackground", D::Integer(1))) + let board = desc("artboard").with("guideIDs", D::List(guides)).with("artboardPresetName", text(preset)).with("Clr ", D::Descriptor(color)); + match p.get("backgroundTypeOmitted") { + None => Some(board.with("artboardBackgroundType", D::Integer(background))), + Some(Value::Bool(true)) if background == 1 => Some(board), + _ => None, + } +} + +/// Import target-only conversion or complete recorded settings, preserving flag absence and values. +pub(super) fn artboard_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + if d.items == desc("null").with("null", target_ref("Lyr ")).items { + return none(FROM_GROUP); + } + let Some(mut p) = get_obj(d, "artboard").and_then(|b| settings_from(b, "preset")) else { return unsupported }; + match d.get("changeBackground") { + None => {} + Some(D::Integer(n)) => p["changeBackground"] = (*n).into(), + _ => return unsupported, + } + if artboard_to(FROM_GROUP, &p).is_some_and(|expected| expected.items == d.items) { step(FROM_GROUP, p) } else { unsupported } +} + +/// Save complete recorded conversion settings; unknown native options must not disappear. +pub(super) fn artboard_to(_: &str, p: &Value) -> Option { + let fields = p.as_object()?; + let d = desc("null").with("null", target_ref("Lyr ")); + if fields.is_empty() { + return Some(d); + } + if fields.keys().any(|k| !["background", "color", "preset", "guideIDs", "changeBackground", "backgroundTypeOmitted"].contains(&k.as_str())) { + return None; + } + let d = d.with("artboard", D::Descriptor(settings_to(p, "preset")?)); + match p.get("changeBackground") { + None => Some(d), + // Older native action files used true for the recorded integer 1. + Some(Value::Bool(true)) => Some(d.with("changeBackground", D::Integer(1))), + Some(value) => Some(d.with("changeBackground", D::Integer(i32::try_from(value.as_i64()?).ok()?))), + } +} + +/// Background-only edits retain recorded geometry as metadata, never as native resize parameters. +pub(super) fn artboard_edit_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(board) = get_obj(d, "artboard") else { return unsupported }; + let Some(rect) = get_obj(board, "artboardRect") else { return unsupported }; + let Some(mut p) = settings_from(board, "recordedPreset") else { return unsupported }; + let Some(edges) = ["Top ", "Left", "Btom", "Rght"].iter().map(|key| get_num(rect, key)).collect::>>() else { return unsupported }; + p["recordedRect"] = json!(edges); + p["changeSizes"] = 8.into(); + p["changeBackground"] = 1.into(); + if artboard_edit_to(EDIT, &p).is_some_and(|expected| expected.items == d.items) { step(EDIT, p) } else { unsupported } +} + +/// Export only the measured background-edit flags and exact recorded rectangle, without quantization. +pub(super) fn artboard_edit_to(_: &str, p: &Value) -> Option { + let fields = p.as_object()?; + if fields.keys().any(|k| { + !["background", "color", "recordedPreset", "guideIDs", "recordedRect", "changeSizes", "changeBackground", "backgroundTypeOmitted"].contains(&k.as_str()) + }) || p.get("changeSizes")?.as_i64()? != 8 + || p.get("changeBackground")?.as_i64()? != 1 + { + return None; + } + let edges = p.get("recordedRect")?.as_array()?; + if edges.len() != 4 { + return None; + } + let rect = ["Top ", "Left", "Btom", "Rght"] + .into_iter() + .zip(edges) + .try_fold(desc("classFloatRect"), |d, (key, value)| Some(d.with(key, D::Double(value.as_f64().filter(|v| v.is_finite())?))))?; + let mut board = desc("artboard").with("artboardRect", D::Descriptor(rect)); + board.items.extend(settings_to(p, "recordedPreset")?.items); + Some( + desc("null") + .with("null", target_ref("Lyr ")) + .with("artboard", D::Descriptor(board)) + .with("changeSizes", D::Integer(8)) + .with("changeBackground", D::Integer(1)), + ) } diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 71b0edc15d7..598f1c2d249 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -576,7 +576,11 @@ fn every_mapped_command_exports_and_imports_back() { ("file.automate.cropAndStraightenPhotos", json!({})), ("file.automate.cropAndStraightenPhotos", json!({"_atnNoTarget": true})), ("layer.new.artboardFromGroup", json!({})), - ("layer.new.artboardFromGroup", json!({"background":"white","color":[1,1,1],"preset":"","guideIDs":[],"changeBackground":true})), + ("layer.new.artboardFromGroup", json!({"background":"white","color":[1,1,1],"preset":"","guideIDs":[],"changeBackground":1})), + ( + "layer.artboard.set", + json!({"background":"custom","color":[0.25,0.5,0.75],"recordedPreset":"","guideIDs":[],"recordedRect":[2,2,6,6],"changeSizes":8,"changeBackground":1}), + ), ("layer.new.layerViaCopy", json!({})), ("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("layer.newAdjustmentLayer.hueSaturation", json!({})), diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index ed63f3d3338..816935cce8c 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -64,6 +64,7 @@ fn file(event: &str, descriptor: Descriptor) -> Vec { ..Default::default() }], warnings: vec![], + ..Default::default() }) .unwrap() } @@ -442,40 +443,56 @@ fn artboard_fixture() -> Session { /// The reference's ordered settings keys, with fractional RGB that must not be rounded to hex. fn artboard_descriptor(background: i32, guides: Vec, flag: D) -> Descriptor { + Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(artboard_settings(Some(background), guides))).with("changeBackground", flag) +} + +/// Background types 1..3 still record the last custom RGB value; absent type means white. +fn artboard_settings(background: Option, guides: Vec) -> Descriptor { let color = Descriptor::new("RGBC").with("Rd ", D::Double(63.75)).with("Grn ", D::Double(127.5)).with("Bl ", D::Double(191.25)); let board = Descriptor::new("artboard") .with("guideIDs", D::List(guides)) .with("artboardPresetName", D::Text(UnicodeString::new_nul("iPhone 14"))) - .with("Clr ", D::Descriptor(color)) - .with("artboardBackgroundType", D::Integer(background)); - Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(board)).with("changeBackground", flag) + .with("Clr ", D::Descriptor(color)); + match background { + Some(n) => board.with("artboardBackgroundType", D::Integer(n)), + None => board, + } } /// Conversion preserves the group's geometry/content while applying every admitted setting and Undo. #[test] -fn artboard_empty_guide_settings_roundtrip_apply_background_and_preset_without_resizing() { +fn artboard_recorded_flags_and_guides_roundtrip_without_resizing() { for (background, expected) in [(1, [1.0, 1.0, 1.0, 1.0]), (2, [0.0, 0.0, 0.0, 1.0]), (3, [0.0; 4]), (4, [0.25, 0.5, 0.75, 1.0])] { - let mut s = artboard_fixture(); - let before = s.active().unwrap().doc.clone(); - let id = s.active().unwrap().active_layer.unwrap(); - let d = artboard_descriptor(background, vec![], D::Integer(1)); - assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); - assert_eq!(s.actions.list[0].steps[0].0, "layer.new.artboardFromGroup"); - assert_eq!(s.actions.list[0].steps[0].1["color"], json!([0.25, 0.5, 0.75])); - assert_eq!(saved_item(&mut s).descriptor, Some(d)); - play(&mut s); - let doc = &s.active().unwrap().doc; - let board = doc.layer(id).unwrap().artboard().unwrap(); - assert_eq!(board.rect, photocraft_doc::Rect::new(2, 2, 6, 6), "preset is a tag, not a request to resize the group"); - assert_eq!(board.preset, "iPhone 14"); - assert_eq!(doc.size, before.size); - assert_eq!(doc.layer(id).unwrap().children(), before.layer(id).unwrap().children()); - let pixel = photocraft_compose::render(doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; - for (actual, expected) in pixel.into_iter().zip(expected) { - assert!((actual - expected).abs() < 0.005, "background {background}: {pixel:?}"); + for flag in [None, Some(0), Some(1), Some(2), Some(3), Some(-1), Some(7)] { + let mut s = artboard_fixture(); + Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.horizontal.push(3.0); + Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.vertical.push(4.0); + let before = s.active().unwrap().doc.clone(); + let id = s.active().unwrap().active_layer.unwrap(); + let mut d = artboard_descriptor(background, vec![D::Integer(2), D::Integer(99999)], D::Integer(flag.unwrap_or(1))); + if flag.is_none() { + d.items.pop(); + } + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].0, "layer.new.artboardFromGroup"); + assert_eq!(s.actions.list[0].steps[0].1["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + play(&mut s); + let doc = &s.active().unwrap().doc; + let board = doc.layer(id).unwrap().artboard().unwrap(); + assert_eq!(board.rect, photocraft_doc::Rect::new(2, 2, 6, 6), "preset is a tag, not a request to resize the group"); + assert_eq!(board.preset, "iPhone 14"); + assert_eq!(doc.size, before.size); + assert_eq!(doc.layer(id).unwrap().children(), before.layer(id).unwrap().children()); + assert_eq!(doc.guides, before.guides); + let pixel = photocraft_compose::render(doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; + let applied = flag.is_none_or(|n| n == 1); + for (actual, expected) in pixel.into_iter().zip(if applied { expected } else { [1.0; 4] }) { + assert!((actual - expected).abs() < 0.005, "background {background}, flag {flag:?}: {pixel:?}"); + } + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); } - assert!(s.undo()); - assert_eq!(s.active().unwrap().doc, before); } } @@ -496,11 +513,9 @@ fn artboard_target_only_form_keeps_existing_native_group_behavior() { /// Unproved settings remain byte-preserving kept steps and cannot partially edit the document. #[test] -fn artboard_unproven_associations_flags_and_extra_settings_stay_whole() { +fn artboard_unmeasured_types_and_extra_settings_stay_whole() { for d in [ - artboard_descriptor(1, vec![D::Integer(7)], D::Integer(1)), - artboard_descriptor(1, vec![], D::Integer(0)), - artboard_descriptor(1, vec![], D::Integer(2)), + artboard_descriptor(1, vec![D::Double(7.0)], D::Integer(1)), artboard_descriptor(1, vec![], D::Boolean(true)), artboard_descriptor(5, vec![], D::Integer(1)), artboard_descriptor(1, vec![], D::Integer(1)).with("extra", D::Boolean(true)), @@ -523,27 +538,107 @@ fn artboard_unproven_associations_flags_and_extra_settings_stay_whole() { } } -/// An explicit empty association cannot silently acquire the document's spatially inferred guides. +/// Omitted type means white rather than the color-only native call's custom background. #[test] -fn artboard_empty_association_refuses_existing_guides_before_editing() { +fn artboard_omitted_type_defaults_to_white_and_invalid_native_settings_are_atomic() { let mut s = artboard_fixture(); - Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.horizontal.push(3.0); let before = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", artboard_descriptor(4, vec![], D::Integer(1))))["unsupported"], json!([])); - let report = s.execute("actions.play", json!({"action":"A","set":"Links"})).unwrap(); - assert_eq!(report["ran"], 0, "{report}"); - assert_eq!(report["failed"]["id"], "layer.new.artboardFromGroup"); - assert!(report["failed"]["error"].as_str().unwrap().contains("without guides")); + let d = + Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(artboard_settings(None, vec![]))).with("changeBackground", D::Integer(1)); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + let mut changed = s.actions.list[0].steps[0].1.clone(); + changed["background"] = "black".into(); + assert!(atn_cmds::export("Links", &[&Action::new("A", vec![("layer.new.artboardFromGroup".into(), changed)])], &[], false).is_err()); + play(&mut s); + assert_eq!(photocraft_compose::render(&s.active().unwrap().doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0], [1.0; 4]); + assert!(s.undo()); assert_eq!(s.active().unwrap().doc, before); - assert_eq!(s.active().unwrap().history.past_len(), history); - for p in [json!({"guideIDs":[7]}), json!({"guideIDs":false}), json!({"changeBackground":false}), json!({"preset":7})] { + let history = s.active().unwrap().history.past_len(); + for p in [ + json!({"guideIDs":[7.5]}), + json!({"guideIDs":false}), + json!({"changeBackground":false}), + json!({"changeBackground":2147483648i64}), + json!({"preset":7}), + ] { assert!(s.execute("layer.new.artboardFromGroup", p).is_err()); assert_eq!(s.active().unwrap().doc, before); assert_eq!(s.active().unwrap().history.past_len(), history); } } +/// Recorded geometry deliberately differs from the target: flag 8 changes only its background. +fn artboard_edit_descriptor(background: i32, change_sizes: i32) -> Descriptor { + let rect = Descriptor::new("classFloatRect") + .with("Top ", D::Double(40.5)) + .with("Left", D::Double(60.25)) + .with("Btom", D::Double(340.5)) + .with("Rght", D::Double(260.25)); + let mut board = Descriptor::new("artboard").with("artboardRect", D::Descriptor(rect)); + board.items.extend(artboard_settings(Some(background), vec![D::Integer(99999)]).items); + Descriptor::new("null") + .with("null", target()) + .with("artboard", D::Descriptor(board)) + .with("changeSizes", D::Integer(change_sizes)) + .with("changeBackground", D::Integer(1)) +} + +/// Background edits preserve all wire fields, target geometry, children and guides, with one Undo. +#[test] +fn artboard_background_edit_roundtrips_without_replaying_recorded_geometry() { + for (kind, expected) in [(1, [1.0; 4]), (2, [0.0, 0.0, 0.0, 1.0]), (3, [0.0; 4]), (4, [0.25, 0.5, 0.75, 1.0])] { + let mut s = artboard_fixture(); + s.execute("layer.new.artboardFromGroup", json!({})).unwrap(); + Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.horizontal.push(3.0); + let before = s.active().unwrap().doc.clone(); + let id = s.active().unwrap().active_layer.unwrap(); + let history = s.active().unwrap().history.past_len(); + let d = artboard_edit_descriptor(kind, 8); + assert_eq!(load(&mut s, &file("editArtboardEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].0, "layer.artboard.set"); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + play(&mut s); + let doc = &s.active().unwrap().doc; + let board = doc.layer(id).unwrap().artboard().unwrap(); + assert_eq!(board.rect, before.layer(id).unwrap().artboard().unwrap().rect); + assert_eq!(board.preset, before.layer(id).unwrap().artboard().unwrap().preset); + assert_eq!(doc.layer(id).unwrap().children(), before.layer(id).unwrap().children()); + assert_eq!(doc.size, before.size); + assert_eq!(doc.guides, before.guides); + let pixel = photocraft_compose::render(doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; + for (actual, expected) in pixel.into_iter().zip(expected) { + assert!((actual - expected).abs() < 0.005, "{kind}: {pixel:?}"); + } + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +/// Unmeasured geometry modes remain whole; edited native resize options cannot be silently omitted. +#[test] +fn artboard_edit_refuses_unmeasured_modes_and_lossy_native_exports() { + let mut s = artboard_fixture(); + for d in [artboard_edit_descriptor(1, 4), artboard_edit_descriptor(5, 8), artboard_edit_descriptor(1, 8).with("extra", D::Integer(1))] { + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + assert_eq!(load(&mut s, &file("editArtboardEvent", d.clone()))["unsupported"].as_array().unwrap().len(), 1); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + let result = s.execute("actions.play", json!({"set":"Links","action":"A"})).unwrap(); + assert_eq!(result["ran"], 0); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + load(&mut s, &file("editArtboardEvent", artboard_edit_descriptor(4, 8))); + let params = s.actions.list[0].steps[0].1.clone(); + for (key, value) in [("rect", json!([0, 0, 100, 100])), ("preset", json!("iPhone 14")), ("changeSizes", json!(4)), ("changeBackground", json!(0))] { + let mut edited = params.clone(); + edited[key] = value; + assert!(atn_cmds::export("Links", &[&Action::new("A", vec![("layer.artboard.set".into(), edited)])], &[], false).is_err()); + } +} + #[test] fn reverse_linked_selection_and_clear_style_events_do_their_edits() { for explicit in [false, true] { diff --git a/docs/atn.md b/docs/atn.md index c08a76ac5ac..00e28526890 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -160,23 +160,26 @@ the reference application. | (string ID only) | placedLayerRelinkToFile | Relink to File | `layer.smartObjects.relinkToFile` | | (string ID only) | placedLayerReplaceContents | Replace Contents | `layer.smartObjects.replaceContents` | | (string ID only) | shapeBlur | Shape Blur (radius-only form) | `filter.blur.shapeBlur` | -| (string ID only) | artboardFromLayerGroupEvent | Artboard from Group (limited forms below) | `layer.new.artboardFromGroup` | +| (string ID only) | artboardFromLayerGroupEvent | Artboard from Group | `layer.new.artboardFromGroup` | +| (string ID only) | editArtboardEvent | Artboard background color (flags 8/1) | `layer.artboard.set` | ### Newer event mapping boundaries -Twenty-two of the 23 requested forms in the two **Measured** tables under -[Newer events](#newer-events-string-id-only) are fully mapped. Artboard from Group -has an intermediate mapping for the canonical current-layer target alone, or a -complete settings object with empty `guideIDs` and integer `changeBackground: 1`. -The latter requires a document without guides, so the existing spatial guide -export cannot manufacture an association. The preset is retained as a tag without -resizing the group; RGB background channels retain fractional values. Only forms -that reconstruct exactly are admitted. Unrepresented native options refuse export. +The 23 requested forms in the two **Measured** tables under +[Newer events](#newer-events-string-id-only) are mapped. Artboard from Group +retains the current-layer target, preset tag, fractional RGB, background type +and integer `changeBackground`, including absence. A flag of 1 or absence applies +the background; other integers give white. An omitted type defaults to white. +Recorded guide IDs are preserved on save and ignored on playback, as measured +in [the guide/background reference below](#newer-events-string-id-only). +Existing document guides remain unchanged. The preset does not resize the group. -Nonempty guide associations and other flag values remain complete kept steps. -The Artboard row is still unfinished: [Adobe documents guide IDs as object identities](https://developer.adobe.com/photoshop/uxp/2022/ps-reference/classes/guide), -separate from list positions, and the current native model has no corresponding -identity/ownership binding. No guide ID is discarded or treated as an array index. +The additional `editArtboardEvent` maps background-only changes with `changeSizes` +8 and `changeBackground` 1. Its rectangle and preset remain recording metadata: +they do not move or resize the target artboard. Colors remain in the saved step +even for white, black or transparent backgrounds. Other flags, extra settings, +unknown targets and forms that cannot reconstruct exactly remain whole kept +steps. Native geometry edits without a matching wire form refuse export. The sixteen target-only events accept an empty descriptor or the current-layer `null` reference (`Lyr `/`Ordn.Trgt`). Save retains which form was imported. diff --git a/docs/development.md b/docs/development.md index 277d20b9540..16a92b13125 100644 --- a/docs/development.md +++ b/docs/development.md @@ -631,6 +631,12 @@ PhotoCraft equivalent. Events outside the table load as `actions.photoshopStep` steps that keep the descriptor verbatim (so Save Actions writes them back) and fail at playback with the step's Photoshop name. +Artboard from Group action settings follow [the measured guide/background behavior](atn.md#newer-events-string-id-only): +guide IDs are ignored session metadata, 1 or absent `changeBackground` applies the +background, and other integer flags give white. The group's bounds are retained. +Background-only `editArtboardEvent` uses the existing Artboard edit command; its +recorded rectangle/preset are retained for saving, without resizing the target. + `crates/psd/tests/it/atn_contract.rs` checks the parser's public API against four small, independently encoded fixtures in `crates/psd/tests/fixtures/atn/` (provenance and checksums in its README): `cargo test -p photocraft-psd --test it atn_contract::`.