diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 2f05ddfae05..89e7a15d009 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -301,18 +301,35 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// Convert a plain group without resizing its content bounds; refuse unresolved recorded guide associations before editing. fn artboard_from_group(s: &mut Session, p: &Value) -> Result { + let cmd = "layer.new.artboardFromGroup"; let d = s.active().ok_or(EngineError::NoDocument)?; let id = p.get("layer").and_then(Value::as_u64).map(LayerId).or(d.active_layer).ok_or(EngineError::Other("no active layer".into()))?; + let preset = match p.get("preset") { + None => String::new(), + Some(value) => value.as_str().ok_or_else(|| bad(cmd, "preset must be text"))?.to_string(), + }; + if p.get("changeBackground").is_some_and(|value| value != &Value::Bool(true)) { + return Err(bad(cmd, "only an explicit true background-change flag is supported")); + } + if let Some(guides) = p.get("guideIDs") { + if !guides.as_array().is_some_and(Vec::is_empty) { + return Err(bad(cmd, "recorded guide associations are not supported")); + } + if !d.doc.guides.horizontal.is_empty() || !d.doc.guides.vertical.is_empty() { + return Err(bad(cmd, "an explicit empty guide association requires a document without guides")); + } + } let canvas = d.doc.bounds(); - let background = background_param(p, "layer.new.artboardFromGroup")?.unwrap_or_default(); + let background = background_param(p, cmd)?.unwrap_or_default(); let rect = s.edit("Artboard from Group", |doc, active| { if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) { return Err(EngineError::Other("artboards are made from a top-level layer group".into())); } let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let rect = crate::layer_multi_cmds::layer_bounds(l).unwrap_or(canvas); - set_artboard(l, Artboard { rect, background, preset: String::new() }); + set_artboard(l, Artboard { rect, background, preset }); fit_canvas(doc); *active = Some(id); Ok(rect) @@ -703,7 +720,7 @@ pub fn specs() -> Vec { "layer.new.artboardFromGroup", "Artboard from Group…", &["Layer", "New"], - r##"{"layer":id? (a top-level group; default active),"background":…?} → {layer, rect}"##, + r##"{"layer":id? (a top-level group; default active),"background":…?,"color":[r,g,b]|"#rrggbb"?,"preset":str? (tag only; does not resize),"guideIDs":[]? (recorded empty association; requires no document guides),"changeBackground":true? (recorded apply flag; other values refused)} → {layer, rect}"##, has_plain_group, artboard_from_group ), diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 42a4722479f..c0e6ed57129 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -32,6 +32,7 @@ mod descriptors; mod events; mod fields; mod files; +mod steps_artboard; mod steps_doc; mod steps_image; mod steps_layer; diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 5309d35e451..a80056260d3 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -2,6 +2,7 @@ const DIFFUSE_MODE: &[(&str, &str)] = &[("Nrml", "normal"), ("DrkO", "darkenOnly use super::adjustments::{adjustment_by_class, adjustment_steps, levels_from, levels_to, shadows_highlights_from, shadows_highlights_to}; use super::descriptors::{desc, get_bool, get_ref, jbool, layer_ref, layer_target, path_text, path_value, ref_class, target_ref}; use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; +use super::steps_artboard::{artboard_from, artboard_to}; use super::steps_doc::{ align_from, align_to, canvas_size_from, canvas_size_to, close_from, close_to, conditional_from, conditional_to, convert_mode_from, convert_mode_to, crop_from, crop_to, export_from, export_to, image_size_from, image_size_to, merge_visible_from, merge_visible_to, open_from, open_to, paste_from, paste_to, @@ -488,6 +489,14 @@ pub(super) const EVENTS: &[Event] = &[ target_event!("textSaveDefaultTypeStyles", "Save Default Type Styles", "type.saveDefaultTypeStyles"), target_event!("recordMeasurements", "Record Measurements", "image.analysis.recordMeasurements"), target_event!("CropPhotosAuto0001", "Crop and Straighten Photos", "file.automate.cropAndStraightenPhotos"), + Event { + code: "", + name: "artboardFromLayerGroupEvent", + label: "Artboard from Group", + ids: &["layer.new.artboardFromGroup"], + from: artboard_from, + to: artboard_to, + }, Event { code: "", name: "linkSelectedLayers", label: "Link Layers", ids: &["layer.linkLayers"], from: |d| link_from(d, true), to: |_, p| link_to(p, true) }, Event { code: "", diff --git a/crates/engine/src/cmd/atn_cmds/steps_artboard.rs b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs new file mode 100644 index 00000000000..8d2964d95ad --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_artboard.rs @@ -0,0 +1,65 @@ +//! Strict Artboard from Group forms whose settings the existing native model can apply. + +use super::descriptors::{desc, get_num, get_obj, get_text, target_ref, text}; +use super::fields::{Mapped, none, step}; +use super::{D, Descriptor, Value, json}; + +const COMMAND: &str = "layer.new.artboardFromGroup"; + +/// Import the current-target form or the verified empty-guide settings form, keeping other forms whole. +pub(super) fn artboard_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + if d.items == desc("null").with("null", target_ref("Lyr ")).items { + return none(COMMAND); + } + let Some(board) = get_obj(d, "artboard") else { return unsupported }; + let Some(color) = get_obj(board, "Clr ") else { return unsupported }; + let Some(preset) = get_text(board, "artboardPresetName") else { return unsupported }; + let background = match board.get("artboardBackgroundType") { + Some(D::Integer(1)) => "white", + Some(D::Integer(2)) => "black", + Some(D::Integer(3)) => "transparent", + Some(D::Integer(4)) => "custom", + _ => return unsupported, + }; + let rgb: Option> = ["Rd ", "Grn ", "Bl "].iter().map(|key| get_num(color, key).map(|n| n / 255.0)).collect(); + let Some(rgb) = rgb else { return unsupported }; + let p = json!({"background": background, "color": rgb, "preset": preset, "guideIDs": [], "changeBackground": true}); + // Reconstruction checks every ordered key, nested class, value type and the evidenced flag. + if artboard_to(COMMAND, &p).is_some_and(|expected| expected.items == d.items) { step(COMMAND, p) } else { unsupported } +} + +/// Export only current-target steps or complete, representable empty-guide settings without quantizing RGB. +pub(super) fn artboard_to(_: &str, p: &Value) -> Option { + let p = p.as_object()?; + let d = desc("null").with("null", target_ref("Lyr ")); + if p.is_empty() { + return Some(d); + } + if p.len() != 5 || p.get("changeBackground") != Some(&Value::Bool(true)) || !p.get("guideIDs")?.as_array()?.is_empty() { + return None; + } + let preset = p.get("preset")?.as_str()?; + let background = match p.get("background")?.as_str()? { + "white" => 1, + "black" => 2, + "transparent" => 3, + "custom" => 4, + _ => return None, + }; + let rgb = p.get("color")?.as_array()?; + if rgb.len() != 3 { + return None; + } + let rgb: Vec = rgb.iter().map(Value::as_f64).collect::>()?; + if !rgb.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n)) { + return None; + } + let color = ["Rd ", "Grn ", "Bl "].into_iter().zip(rgb).fold(desc("RGBC"), |d, (key, n)| d.with(key, D::Double(n * 255.0))); + let board = desc("artboard") + .with("guideIDs", D::List(vec![])) + .with("artboardPresetName", text(preset)) + .with("Clr ", D::Descriptor(color)) + .with("artboardBackgroundType", D::Integer(background)); + Some(d.with("artboard", D::Descriptor(board)).with("changeBackground", D::Integer(1))) +} diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index cf677baf5b9..d47a0a0d492 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -567,6 +567,8 @@ fn every_mapped_command_exports_and_imports_back() { ("image.analysis.recordMeasurements", json!({})), ("file.automate.cropAndStraightenPhotos", json!({})), ("file.automate.cropAndStraightenPhotos", json!({"_atnNoTarget": true})), + ("layer.new.artboardFromGroup", json!({})), + ("layer.new.artboardFromGroup", json!({"background":"white","color":[1,1,1],"preset":"","guideIDs":[],"changeBackground":true})), ("layer.new.layerViaCopy", json!({})), ("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("layer.newAdjustmentLayer.hueSaturation", json!({})), diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 1ecdf41e810..ed63f3d3338 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -422,6 +422,128 @@ fn crop_parent_runs_once_and_the_kept_helper_stops_the_duplicate_crop_tail() { assert_eq!(s.documents()[0].doc, source); } +/// Two sparse marks leave a transparent gap where the converted board's background is observable. +fn artboard_fixture() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 12, "height": 10, "background": "transparent"})).unwrap(); + let st = s.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let mut child = Layer::raster("Pixels", doc.pixel_format()); + let surface = child.surface_mut().unwrap(); + for rect in [photocraft_doc::Rect::new(2, 2, 3, 3), photocraft_doc::Rect::new(5, 5, 6, 6)] { + surface.fill_rect(rect, &[1.0, 0.0, 0.0, 1.0]); + } + let group = Layer::group("Group", vec![child]); + let id = group.id; + doc.layers = vec![group]; + s.restore_layer_selection(Some(id), &[id], Some(id)).unwrap(); + s +} + +/// The reference's ordered settings keys, with fractional RGB that must not be rounded to hex. +fn artboard_descriptor(background: i32, guides: Vec, flag: D) -> Descriptor { + let color = Descriptor::new("RGBC").with("Rd ", D::Double(63.75)).with("Grn ", D::Double(127.5)).with("Bl ", D::Double(191.25)); + let board = Descriptor::new("artboard") + .with("guideIDs", D::List(guides)) + .with("artboardPresetName", D::Text(UnicodeString::new_nul("iPhone 14"))) + .with("Clr ", D::Descriptor(color)) + .with("artboardBackgroundType", D::Integer(background)); + Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(board)).with("changeBackground", flag) +} + +/// Conversion preserves the group's geometry/content while applying every admitted setting and Undo. +#[test] +fn artboard_empty_guide_settings_roundtrip_apply_background_and_preset_without_resizing() { + for (background, expected) in [(1, [1.0, 1.0, 1.0, 1.0]), (2, [0.0, 0.0, 0.0, 1.0]), (3, [0.0; 4]), (4, [0.25, 0.5, 0.75, 1.0])] { + let mut s = artboard_fixture(); + let before = s.active().unwrap().doc.clone(); + let id = s.active().unwrap().active_layer.unwrap(); + let d = artboard_descriptor(background, vec![], D::Integer(1)); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps[0].0, "layer.new.artboardFromGroup"); + assert_eq!(s.actions.list[0].steps[0].1["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + play(&mut s); + let doc = &s.active().unwrap().doc; + let board = doc.layer(id).unwrap().artboard().unwrap(); + assert_eq!(board.rect, photocraft_doc::Rect::new(2, 2, 6, 6), "preset is a tag, not a request to resize the group"); + assert_eq!(board.preset, "iPhone 14"); + assert_eq!(doc.size, before.size); + assert_eq!(doc.layer(id).unwrap().children(), before.layer(id).unwrap().children()); + let pixel = photocraft_compose::render(doc, photocraft_doc::Rect::new(3, 3, 4, 4)).px[0]; + for (actual, expected) in pixel.into_iter().zip(expected) { + assert!((actual - expected).abs() < 0.005, "background {background}: {pixel:?}"); + } + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +/// The target-only call uses the existing menu behavior without synthesizing settings. +#[test] +fn artboard_target_only_form_keeps_existing_native_group_behavior() { + let mut s = artboard_fixture(); + let before = s.active().unwrap().doc.clone(); + let d = Descriptor::new("null").with("null", target()); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); + assert_eq!(s.actions.list[0].steps, [("layer.new.artboardFromGroup".into(), json!({}))]); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + play(&mut s); + assert!(s.active().unwrap().doc.layers[0].artboard().is_some()); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Unproved settings remain byte-preserving kept steps and cannot partially edit the document. +#[test] +fn artboard_unproven_associations_flags_and_extra_settings_stay_whole() { + for d in [ + artboard_descriptor(1, vec![D::Integer(7)], D::Integer(1)), + artboard_descriptor(1, vec![], D::Integer(0)), + artboard_descriptor(1, vec![], D::Integer(2)), + artboard_descriptor(1, vec![], D::Boolean(true)), + artboard_descriptor(5, vec![], D::Integer(1)), + artboard_descriptor(1, vec![], D::Integer(1)).with("extra", D::Boolean(true)), + Descriptor::new("null"), + ] { + let mut s = artboard_fixture(); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"].as_array().unwrap().len(), 1); + assert_eq!(saved_item(&mut s).descriptor, Some(d)); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let report = s.execute("actions.play", json!({"action":"A","set":"Links"})).unwrap(); + assert_eq!(report["ran"], 0, "{report}"); + assert_eq!(report["failed"]["id"], "actions.photoshopStep"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + for p in [json!({"layer":1}), json!({"preset":"iPhone 14"}), json!({"guideIDs":[]}), json!({"changeBackground":false})] { + let action = Action::new("A", vec![("layer.new.artboardFromGroup".into(), p)]); + assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); + } +} + +/// An explicit empty association cannot silently acquire the document's spatially inferred guides. +#[test] +fn artboard_empty_association_refuses_existing_guides_before_editing() { + let mut s = artboard_fixture(); + Arc::make_mut(&mut s.active_mut().unwrap().doc).guides.horizontal.push(3.0); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", artboard_descriptor(4, vec![], D::Integer(1))))["unsupported"], json!([])); + let report = s.execute("actions.play", json!({"action":"A","set":"Links"})).unwrap(); + assert_eq!(report["ran"], 0, "{report}"); + assert_eq!(report["failed"]["id"], "layer.new.artboardFromGroup"); + assert!(report["failed"]["error"].as_str().unwrap().contains("without guides")); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + for p in [json!({"guideIDs":[7]}), json!({"guideIDs":false}), json!({"changeBackground":false}), json!({"preset":7})] { + assert!(s.execute("layer.new.artboardFromGroup", p).is_err()); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } +} + #[test] fn reverse_linked_selection_and_clear_style_events_do_their_edits() { for explicit in [false, true] { diff --git a/docs/atn.md b/docs/atn.md index 1c3518c3f69..86ecf7f3117 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -18,7 +18,7 @@ layers and documents, newer and older events and files, and a measured reference map yet, with everything needed to implement them without the reference application. -## Supported events (138) +## Supported events (139) | Code | String ID | Label | PhotoCraft command(s) | |---|---|---|---| @@ -160,13 +160,23 @@ the reference application. | (string ID only) | placedLayerRelinkToFile | Relink to File | `layer.smartObjects.relinkToFile` | | (string ID only) | placedLayerReplaceContents | Replace Contents | `layer.smartObjects.replaceContents` | | (string ID only) | shapeBlur | Shape Blur (radius-only form) | `filter.blur.shapeBlur` | +| (string ID only) | artboardFromLayerGroupEvent | Artboard from Group (limited forms below) | `layer.new.artboardFromGroup` | ### Newer event mapping boundaries -The two **Measured** tables under [Newer events](#newer-events-string-id-only) -now map except for `artboardFromLayerGroupEvent`. Its `guideIDs` association and -`changeBackground` behavior are not established by the reference, so the whole -step remains kept. No guide IDs are discarded or guessed. +Twenty-two of the 23 requested forms in the two **Measured** tables under +[Newer events](#newer-events-string-id-only) are fully mapped. Artboard from Group +has an intermediate mapping for the canonical current-layer target alone, or a +complete settings object with empty `guideIDs` and integer `changeBackground: 1`. +The latter requires a document without guides, so the existing spatial guide +export cannot manufacture an association. The preset is retained as a tag without +resizing the group; RGB background channels retain fractional values. Only forms +that reconstruct exactly are admitted. Unrepresented native options refuse export. + +Nonempty guide associations and other flag values remain complete kept steps. +The Artboard row is still unfinished: [Adobe documents guide IDs as object identities](https://developer.adobe.com/photoshop/uxp/2022/ps-reference/classes/guide), +separate from list positions, and the current native model has no corresponding +identity/ownership binding. No guide ID is discarded or treated as an array index. The sixteen target-only events accept an empty descriptor or the current-layer `null` reference (`Lyr `/`Ordn.Trgt`). Save retains which form was imported.