diff --git a/crates/engine/src/cmd/atn_cmds/steps_layer.rs b/crates/engine/src/cmd/atn_cmds/steps_layer.rs index 9d9bf5f3f7..e486cb3d44 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_layer.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_layer.rs @@ -6,9 +6,10 @@ use super::descriptors::{ use super::events::pixel_target; use super::fields::{F, Kind, Mapped, fields_to, none, step, steps}; use super::steps_make::is_tool_class; -use super::tables::{FILL_CONTENTS, INTERPOLATION, MENU_ITEMS, STROKE_LOCATION, blend_label, blend_ps, lookup, lookup_back}; +use super::tables::{CHANNELS, FILL_CONTENTS, INTERPOLATION, MENU_ITEMS, STROKE_LOCATION, blend_label, blend_ps, channel_of, lookup, lookup_back}; use super::{D, Descriptor, Id, Map, ReferenceItem, UnicodeString, Value, json}; +/// Translate supported selection targets, retaining unknown references as Photoshop steps. pub(super) fn select_from(d: &Descriptor) -> Mapped { let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; match (ref_class(r).as_deref(), target(r)) { @@ -29,6 +30,12 @@ pub(super) fn select_from(d: &Descriptor) -> Mapped { "RGB" | "CMYK" | "Lab" | "Gry" => step("channel.target", json!({"channel": "composite"})), // Re-selecting the channel that is already targeted changes nothing. "Trgt" => Mapped::Unsupported { harmless: true }, + _ if r.len() == 1 + && d.get("selectionModifier").is_none() + && matches!(r.first(), Some(ReferenceItem::Enumerated { type_id, .. }) if type_id.is("Chnl")) => + { + channel_of(&o).map_or(Mapped::Unsupported { harmless: false }, |channel| step("channel.target", json!({"channel": {"color": channel}}))) + } _ => Mapped::Unsupported { harmless: false }, }, // History › Step Backward / Step Forward. @@ -60,6 +67,7 @@ pub(super) fn select_from(d: &Descriptor) -> Mapped { } } +/// Encode selections whose target and selection mode can be represented faithfully in ATN. pub(super) fn select_to(id: &str, p: &Value) -> Option { let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); let enumerated = |cls: &str, ty: &str, v: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: code(ty), value: code(v) }]); @@ -80,10 +88,17 @@ pub(super) fn select_to(id: &str, p: &Value) -> Option { d.with("MkVs", D::Boolean(false)) } "channel.target" => { - let v = match jstr(p, "channel") { - Some("mask") => "Msk ", - None | Some("composite") => "RGB ", - Some(_) => return None, + if p.get("colors").is_some() || p.get("extend").is_some_and(|v| v != &Value::Bool(false)) { + return None; + } + let v = match p.get("channel") { + None => "RGB ", + Some(Value::String(channel)) => match channel.as_str() { + "mask" => "Msk ", + "composite" => "RGB ", + _ => return None, + }, + Some(channel) => lookup_back(CHANNELS, &channel.get("color")?.as_str()?.to_ascii_lowercase())?, }; desc("null").with("null", enumerated("Chnl", "Chnl", v)).with("MkVs", D::Boolean(false)) } diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index f9e633244c..1e7abf35be 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3175,3 +3175,93 @@ fn long_names_are_clipped_instead_of_copied_into_every_diagnostic() { assert_eq!(imp.unsupported.len(), 50); assert!(imp.unsupported.iter().all(|u| u.action.chars().count() == MAX_NAME_CHARS)); } + +/// Native component references import, select the same target as the command and export again. +#[test] +fn select_color_components_import_play_and_round_trip() { + for (mode, channels) in [ + ("rgb", &["red", "green", "blue"][..]), + ("cmyk", &["cyan", "magenta", "yellow", "black"][..]), + ("lab", &["lightness", "a", "b"][..]), + ("gray", &["gray"][..]), + ] { + for depth in [8, 16, 32] { + for channel in channels { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1, "mode": mode, "depth": depth})).unwrap(); + let expected = s.execute("channel.target", json!({"channel": channel})).unwrap(); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + let selection = desc("null").with("null", channel_ref(Some(channel))); + let data = set_of("Components", vec![("Pick", vec![item("select", "Select", Some(selection))])]); + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"], json!([]), "{mode}/{depth}/{channel}"); + let played = s.execute("actions.play", json!({"action": "Pick"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(s.execute("channel.list", json!({})).unwrap(), expected, "{mode}/{depth}/{channel}"); + let saved = s.execute("actions.save", json!({"set": "Components"})).unwrap(); + let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + assert_eq!(import(&bytes).unwrap().actions[0].steps, s.actions.list[0].steps); + } + } + } +} + +/// Unknown targets and selection modes retain their failure instead of selecting another channel. +#[test] +fn select_color_components_preserve_unsupported_selection_shapes() { + let chained = vec![ + ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code("Cyn") }, + ReferenceItem::Identifier { class: class("Dcmn"), id: 7 }, + ]; + for selection in [ + desc("null").with("null", channel_ord("Xxxx")), + desc("null").with("null", channel_ref(Some("cyan"))).with("selectionModifier", enm("selectionModifierType", "addToSelection")), + desc("null").with("null", D::Reference(chained)), + desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Ordn"), value: code("Cyn") }])), + ] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1, "mode": "cmyk"})).unwrap(); + let data = set_of("Unknown", vec![("Pick", vec![item("select", "Select", Some(selection.clone()))])]); + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"].as_array().unwrap().len(), 1); + assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP); + let target = s.execute("channel.list", json!({})).unwrap(); + let played = s.execute("actions.play", json!({"action": "Pick"})).unwrap(); + assert_eq!(played["failed"]["id"], PHOTOSHOP_STEP); + assert_eq!(s.execute("channel.list", json!({})).unwrap(), target); + let saved = s.execute("actions.save", json!({"set": "Unknown"})).unwrap(); + let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0].descriptor.as_ref(), Some(&selection)); + } + for params in [ + json!({"channel": {"color": "cyan"}, "extend": true}), + json!({"channel": {"color": "cyan"}, "colors": [0, 1]}), + json!({"channel": 0}), + json!({"channel": null}), + json!({"channel": {"alpha": 0}}), + json!({"channel": "cyan"}), + ] { + assert!(super::steps_layer::select_to("channel.target", ¶ms).is_none(), "{params}"); + } + assert!(super::steps_layer::select_to("channel.target", &json!({"channel": {"color": "CYAN"}, "extend": false})).is_some()); + let gray = set_of("Gray", vec![("Pick", vec![item("select", "Select", Some(desc("null").with("null", channel_ord("Gry"))))])]); + let bytes = photocraft_paint::tile::b64_decode(&gray).unwrap(); + assert_eq!(import(&bytes).unwrap().actions[0].steps[0], ("channel.target".into(), json!({"channel": "composite"}))); +} + +/// A CMYK component cannot retarget a same-named alpha channel when replayed on RGB. +#[test] +fn select_color_components_do_not_fall_back_to_alpha_names() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1, "mode": "rgb"})).unwrap(); + s.execute("channel.new", json!({"name": "cyan"})).unwrap(); + for channel in [json!("cyan"), json!(0), json!({"alpha": 0})] { + assert_eq!(s.execute("channel.target", json!({"channel": channel})).unwrap()["target"]["kind"], "alpha"); + } + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + let data = set_of("Components", vec![("Pick", vec![item("select", "Select", Some(desc("null").with("null", channel_ref(Some("cyan")))))])]); + assert_eq!(s.execute("actions.load", json!({"data": data})).unwrap()["unsupported"], json!([])); + let played = s.execute("actions.play", json!({"action": "Pick"})).unwrap(); + assert_eq!(played["failed"]["id"], "channel.target"); + assert_eq!(s.execute("channel.list", json!({})).unwrap()["target"]["kind"], "composite"); +} diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs index 49a45cba6a..f909fab5cd 100644 --- a/crates/engine/src/cmd/channel_cmds.rs +++ b/crates/engine/src/cmd/channel_cmds.rs @@ -206,7 +206,7 @@ pub fn specs() -> Vec { "Target Channel", [], None, - r##"{"channel":"composite"|"mask"|"vectorMask"|"red|green|blue|…"|index|name="composite","colors":[index,…]?,"extend":bool=false} (colors selects native colour components only; extend toggles one colour channel, as Shift-click; all components select the composite)"##, + r##"{"channel":"composite"|"mask"|"vectorMask"|"red|green|blue|…"|index|name|{"color":index|name}|{"alpha":index}="composite","colors":[index,…]?,"extend":bool=false} (a color object selects only a native component, never a named alpha channel; colors selects native colour components only; extend toggles one colour channel, as Shift-click; all components select the composite)"##, has_doc, target_cmd ), diff --git a/crates/engine/src/cmd/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs index 58708475da..cee0461f59 100644 --- a/crates/engine/src/cmd/channel_cmds/refs.rs +++ b/crates/engine/src/cmd/channel_cmds/refs.rs @@ -20,12 +20,17 @@ pub enum ChanRef { VectorMask, } +/// Resolve channel references; a color-name object cannot fall back to a named alpha channel. pub fn parse_ref(v: &Value, doc: &Document) -> Option { let mode = edit_mode(doc); match v { Value::Number(n) => n.as_u64().map(|i| ChanRef::Alpha(i as usize)), Value::Object(o) => { - if let Some(k) = o.get("color").and_then(Value::as_u64) { + if let Some(name) = o.get("color").and_then(Value::as_str) { + let names = color_names(mode); + let k = names.iter().position(|n| n.eq_ignore_ascii_case(name))?; + Some(if names.len() == 1 { ChanRef::Composite } else { ChanRef::Color(k) }) + } else if let Some(k) = o.get("color").and_then(Value::as_u64) { Some(ChanRef::Color(k as usize)) } else { o.get("alpha").and_then(Value::as_u64).map(|i| ChanRef::Alpha(i as usize))