diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index af2626f870..d4e14c1e36 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -239,6 +239,7 @@ fn registry() -> &'static Registry { // ---------- the table ---------- #[allow(clippy::too_many_lines)] +/// Register the core file, edit, layer and document commands. fn build() -> Vec { let mut v = vec![ // File @@ -1070,8 +1071,7 @@ fn build() -> Vec { let idx = match (given("document"), given("offset")) { (Some(_), Some(_)) => return Err(bad("document.activate", "give `document` or `offset`, not both")), (None, None) => return Err(bad("document.activate", "needs `document` (a tab index) or `offset`")), - // Refuse offsets past the opening-order ends rather than wrap, so an action that - // copies from one document never silently pastes into the wrong one (#7103). + // Recorded offsets wrap in opening order, independently of dragged tabs. (None, Some(o)) => { let o = o.as_i64().ok_or_else(|| bad("document.activate", "`offset` must be an integer"))?; s.document_at_offset(o)? diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index d056089b29..941589d9ee 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -281,7 +281,7 @@ pub(super) const EVENTS: &[Event] = &[ adjustment_event!("", "PhtF", "photoFilter", "Photo Filter"), adjustment_event!("", "BanW", "blackAndWhite", "Black & White", "image.adjustments.blackWhite"), adjustment_event!("ChnM", "ChnM", "channelMixer", "Channel Mixer"), - adjustment_event!("GdMp", "GdMp", "gradientMapEvent", "Gradient Map", "image.adjustments.gradientMap"), + adjustment_event!("", "GdMp", "gradientMapEvent", "Gradient Map", "image.adjustments.gradientMap"), adjustment_event!("SlcC", "SlcC", "selectiveColor", "Selective Color"), ev!("Dstt", "desaturate", "Desaturate", "image.adjustments.desaturate", &[]), ev!("Eqlz", "equalize", "Equalize", "image.adjustments.equalize", &[]), @@ -620,7 +620,7 @@ pub(super) const EVENTS: &[Event] = &[ /// `flatness` property, not the flatten event. Import keeps accepting them so actions saved /// before still load; export never writes them. const LEGACY_CODES: &[(&str, &str)] = - &[("BoxB", "boxblur"), ("SrfB", "surfaceBlur"), ("Fltn", "flattenImage"), ("BlnW", "blackAndWhite"), ("PhtF", "photoFilter")]; + &[("BoxB", "boxblur"), ("SrfB", "surfaceBlur"), ("Fltn", "flattenImage"), ("BlnW", "blackAndWhite"), ("PhtF", "photoFilter"), ("GdMp", "gradientMapEvent")]; pub(super) fn event_for(item: &AtnEvent) -> Option<&'static Event> { let id = item.id(); diff --git a/crates/engine/src/cmd/atn_cmds/steps_doc.rs b/crates/engine/src/cmd/atn_cmds/steps_doc.rs index 7707976509..154acaf1b5 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_doc.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_doc.rs @@ -267,6 +267,7 @@ pub(super) fn convert_mode_to(id: &str, p: &Value) -> Option { }) } +/// Import canvas dimensions, anchors and explicit extension-colour choices. pub(super) fn canvas_size_from(d: &Descriptor) -> Mapped { let mut p = Map::new(); for (k, param) in [("Wdth", "width"), ("Hght", "height")] { @@ -296,22 +297,25 @@ pub(super) fn canvas_size_from(d: &Descriptor) -> Mapped { _ => return Mapped::Unsupported { harmless: false }, }; p.insert("anchor".into(), anchor.into()); - if let Some(c) = get_enum(d, "canvasExtensionColorType") { + if d.get("canvasExtensionColorType").is_some() { + let Some(c) = get_enum(d, "canvasExtensionColorType") else { return Mapped::Unsupported { harmless: false } }; match lookup(EXTENSION, &c) { Some(c) => { p.insert("extensionColor".into(), c.into()); } - None => match get_obj(d, "canvasExtensionColor").and_then(color_hex) { + None if c == "Clr" || c == "Othr" => match get_obj(d, "canvasExtensionColor").and_then(color_hex) { Some(hex) => { p.insert("extensionColor".into(), hex.into()); } None => return Mapped::Unsupported { harmless: false }, }, + None => return Mapped::Unsupported { harmless: false }, } } step("image.canvasSize", Value::Object(p)) } +/// Write canvas geometry and canonical extension-colour identifiers. pub(super) fn canvas_size_to(_: &str, p: &Value) -> Option { let anchor = jstr(p, "anchor").unwrap_or("center"); let v = if anchor.starts_with("top") { @@ -342,7 +346,7 @@ pub(super) fn canvas_size_to(_: &str, p: &Value) -> Option { if let Some(c) = jstr(p, "extensionColor") { d = match lookup_back(EXTENSION, c) { Some(e) => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", e)), - None => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", "Othr")).with("canvasExtensionColor", D::Descriptor(color_desc(c)?)), + None => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", "Clr ")).with("canvasExtensionColor", D::Descriptor(color_desc(c)?)), }; } Some(d) @@ -537,12 +541,14 @@ pub(super) fn reset_to(_: &str, _: &Value) -> Option { Some(desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: Id::new("Clrs") }]))) } +/// Resolve an assigned or converted profile, preserving a supported rendering intent. pub(super) fn profile_from(d: &Descriptor, id: &str) -> Mapped { let name = get_text(d, "T ").or_else(|| get_text(d, "profile")); let Some(profile) = name.as_deref().and_then(|n| lookup(PROFILES, n)) else { return Mapped::Unsupported { harmless: false } }; let mut p = json!({"profile": profile}); if id == "edit.convertToProfile" { - if let Some(i) = get_enum(d, "Inte").and_then(|i| lookup(INTENT, &i)) { + if d.get("Inte").is_some() { + let Some(i) = get_enum(d, "Inte").and_then(|i| lookup(INTENT, &i)) else { return Mapped::Unsupported { harmless: false } }; p["intent"] = json!(i); } if let Some(b) = get_bool(d, "MpBl") { @@ -552,6 +558,7 @@ pub(super) fn profile_from(d: &Descriptor, id: &str) -> Mapped { step(id, p) } +/// Export the supported profile and canonical rendering-intent identifier. pub(super) fn profile_to(id: &str, p: &Value) -> Option { let name = lookup_back(PROFILES, jstr(p, "profile")?)?; let mut d = desc("null").with("null", target_ref("Dcmn")); diff --git a/crates/engine/src/cmd/atn_cmds/steps_layer.rs b/crates/engine/src/cmd/atn_cmds/steps_layer.rs index 1e18126ae3..cf58be7c58 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_layer.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_layer.rs @@ -57,7 +57,7 @@ pub(super) fn select_from(d: &Descriptor) -> Mapped { }, // Switching to another open document: its offset from the active one, -1 for the previous // opened document and 1 for the next, independently of dragged tabs (#7103). - (Some("Dcmn"), Target::Offset(o)) => step("document.activate", json!({"offset": o})), + (Some("Dcmn"), Target::Offset(o)) if o != 0 => step("document.activate", json!({"offset": o})), _ => Mapped::Unsupported { harmless: false }, } } @@ -105,6 +105,10 @@ pub(super) fn select_to(id: &str, p: &Value) -> Option { // An absolute tab index has no Photoshop equivalent; an offset is what Photoshop records. "document.activate" if p.get("document").is_none_or(Value::is_null) => { let offset = i32::try_from(p.get("offset")?.as_i64()?).ok()?; + // Photoshop rejects zero, though the native command permits that no-op. + if offset == 0 { + return None; + } desc("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset }])) } _ => { diff --git a/crates/engine/src/cmd/atn_cmds/tables.rs b/crates/engine/src/cmd/atn_cmds/tables.rs index 0f3bc278e9..0a6a07abee 100644 --- a/crates/engine/src/cmd/atn_cmds/tables.rs +++ b/crates/engine/src/cmd/atn_cmds/tables.rs @@ -47,8 +47,8 @@ const BLEND_MODES: &[(&str, &str)] = &[ ("color", "Color"), ("Lmns", "Luminosity"), ("luminosity", "Luminosity"), - ("PsTh", "Pass Through"), ("passThrough", "Pass Through"), + ("PsTh", "Pass Through"), ]; pub(super) fn blend_label(ps: &str) -> Option<&'static str> { @@ -125,7 +125,8 @@ pub(super) const OFFSET_FILL: &[(&str, &str)] = &[("Wrp ", "wrap"), ("Rpt ", "re pub(super) const TRIM: &[(&str, &str)] = &[("Trns", "transparent"), ("topLeftPixelColor", "topLeft"), ("bottomRightPixelColor", "bottomRight")]; -pub(super) const EXTENSION: &[(&str, &str)] = &[("Bckg", "background"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Trns", "transparent")]; +pub(super) const EXTENSION: &[(&str, &str)] = + &[("Bckg", "background"), ("FrgC", "foreground"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Trns", "transparent")]; pub(super) const FILL_CONTENTS: &[(&str, &str)] = &[ ("FrgC", "foreground"), @@ -138,9 +139,9 @@ pub(super) const FILL_CONTENTS: &[(&str, &str)] = &[ ("contentAware", "contentAware"), ]; -pub(super) const STROKE_LOCATION: &[(&str, &str)] = &[("Insd", "inside"), ("Cntr", "center"), ("OtsF", "outside")]; +pub(super) const STROKE_LOCATION: &[(&str, &str)] = &[("Insd", "inside"), ("Cntr", "center"), ("Otsd", "outside"), ("OtsF", "outside")]; -pub(super) const INTENT: &[(&str, &str)] = &[("Img ", "perceptual"), ("Clrm", "relative"), ("Grp ", "saturation"), ("AbsC", "absolute")]; +pub(super) const INTENT: &[(&str, &str)] = &[("Img ", "perceptual"), ("Clrm", "relative"), ("Grp ", "saturation"), ("AClr", "absolute"), ("AbsC", "absolute")]; pub(super) const PROFILES: &[(&str, &str)] = &[("sRGB IEC61966-2.1", "srgb"), ("Display P3", "display-p3"), ("Adobe RGB (1998)", "adobe-rgb-compat"), ("ProPhoto RGB", "prophoto-compat")]; diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 6c28a7d3e0..7f30bf21b2 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -4,7 +4,7 @@ use photocraft_psd::descriptor::{Descriptor, Id, ReferenceItem, UnicodeString, V use serde_json::json; #[test] -fn blend_modes_accept_photoshop_string_ids_and_export_canonical_char_ids() { +fn blend_modes_accept_photoshop_string_ids_and_export_canonical_ids() { for (string_id, char_id, label) in [ ("normal", "Nrml", "Normal"), ("dissolve", "Dslv", "Dissolve"), @@ -23,7 +23,7 @@ fn blend_modes_accept_photoshop_string_ids_and_export_canonical_char_ids() { ("saturation", "Strt", "Saturation"), ("color", "Clr", "Color"), ("luminosity", "Lmns", "Luminosity"), - ("passThrough", "PsTh", "Pass Through"), + ("passThrough", "passThrough", "Pass Through"), ] { assert_eq!(blend_label(string_id), Some(label), "{string_id}"); assert_eq!(blend_ps(label), Some(char_id), "{label} remains serialized canonically"); @@ -1586,9 +1586,8 @@ fn select_document_by_offset_imports_plays_and_saves_back() { one.execute("file.new", json!({"width": 8, "height": 8, "name": "template"})).unwrap(); one.execute("actions.load", json!({"data": data})).unwrap(); let r = one.execute("actions.play", json!({"action": "Copy In"})).unwrap(); - assert_eq!(r["failed"]["step"], 0, "{r}"); - assert_eq!(r["failed"]["error"], "no document 1 before the active one, which is 1 of 1", "{r}"); - assert_eq!(one.active().unwrap().doc.layers.len(), 1); + assert!(r.get("failed").is_none(), "{r}"); + assert_eq!(one.active().unwrap().doc.layers.len(), 2, "offsets wrap back to the only open document"); } fn set_of(name: &str, actions: Vec<(&str, Vec)>) -> String { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index a82f6c18e6..d9955a0e42 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -102,15 +102,13 @@ impl Session { /// Resolve a Photoshop action's offset in opening order, returning its current tab index. /// Tab dragging changes `docs`, but must not change which document an imported action edits. + /// Offsets wrap at either end; native zero keeps the active document. pub(crate) fn document_at_offset(&self, offset: i64) -> Result { let id = self.active().ok_or(EngineError::NoDocument)?.doc.id; let active = self.open_document_order.iter().position(|&open| open == id).ok_or(EngineError::NoDocument)?; - let len = self.open_document_order.len(); - let target = i64::try_from(active).ok().and_then(|a| a.checked_add(offset)).and_then(|i| usize::try_from(i).ok()); - let Some(id) = target.and_then(|i| self.open_document_order.get(i)) else { - let side = if offset < 0 { "before" } else { "after" }; - return Err(EngineError::Other(format!("no document {} {side} the active one, which is {} of {len}", offset.unsigned_abs(), active + 1))); - }; + // Widen before addition so even extreme signed offsets wrap without overflow. + let target = (active as i128 + i128::from(offset)).rem_euclid(self.open_document_order.len() as i128) as usize; + let id = &self.open_document_order[target]; self.docs.iter().position(|st| st.doc.id == *id).ok_or(EngineError::NoDocument) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bae9cf4c92..5e8c1095b8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1667,8 +1667,7 @@ fn document_inspect_and_activate_invalid_index() { } /// #7103: Photoshop's Select Document by offset (previous is -1, next +1) walks opening order -/// from the active document. PhotoCraft refuses offsets past either end instead of wrapping -/// onto another document, and bad params leave the active document as it was. +/// from the active document, wrapping at both ends. Bad params preserve the active document. #[test] fn document_activate_by_offset_walks_opening_order() { let mut s = Session::new(); @@ -1688,17 +1687,17 @@ fn document_activate_by_offset_walks_opening_order() { s.execute("document.activate", json!({"document": null, "offset": -1})).unwrap(); assert_eq!(active(&s), "b"); - let err = s.execute("document.activate", json!({"offset": 2})).unwrap_err().to_string(); - assert_eq!(err, "no document 2 after the active one, which is 2 of 3"); - let err = s.execute("document.activate", json!({"offset": -2})).unwrap_err().to_string(); - assert_eq!(err, "no document 2 before the active one, which is 2 of 3"); + for (offset, name) in [(2, "a"), (-2, "c"), (i64::MAX, "c"), (i64::MIN, "c")] { + s.execute("document.activate", json!({"document":1})).unwrap(); + s.execute("document.activate", json!({"offset":offset})).unwrap(); + assert_eq!(active(&s), name, "{offset}"); + } + s.execute("document.activate", json!({"document":1})).unwrap(); for bad in [ json!({}), json!({"offset": null}), json!({"offset": 1.5}), json!({"offset": "1"}), - json!({"offset": i64::MAX}), - json!({"offset": i64::MIN}), json!({"offset": u64::MAX}), json!({"document": 0, "offset": 1}), json!({"document": -1}), @@ -1709,9 +1708,9 @@ fn document_activate_by_offset_walks_opening_order() { // Dragging "c" first changes tab indices, not the opening order a, b, c. s.execute("document.move", json!({"document": 2, "to": 0})).unwrap(); assert_eq!(active(&s), "b"); - let err = s.execute("document.activate", json!({"offset": -2})).unwrap_err().to_string(); - assert_eq!(err, "no document 2 before the active one, which is 2 of 3", "the error reports opening order, not tab position"); - assert_eq!(active(&s), "b", "a failed offset must not activate the visually first tab"); + assert_eq!(s.execute("document.activate", json!({"offset":-2})).unwrap(), json!({"document":0})); + assert_eq!(active(&s), "c", "wrapping follows opening order, not tab position"); + s.execute("document.activate", json!({"document":2})).unwrap(); assert_eq!(s.execute("document.activate", json!({"offset": -1})).unwrap(), json!({"document": 1})); assert_eq!(active(&s), "a"); assert_eq!(s.execute("document.activate", json!({"offset": 2})).unwrap(), json!({"document": 0})); diff --git a/crates/engine/tests/atn_mapped_identifiers.rs b/crates/engine/tests/atn_mapped_identifiers.rs new file mode 100644 index 0000000000..899d214108 --- /dev/null +++ b/crates/engine/tests/atn_mapped_identifiers.rs @@ -0,0 +1,205 @@ +//! Recorded identifiers must match Photoshop, even when a local round trip would accept a typo. + +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; + +fn class(id: &str) -> Class { + Class { name: UnicodeString::new_nul(""), class_id: Id::new(id) } +} + +fn enm(ty: &str, value: &str) -> D { + D::Enumerated { type_id: Id::new(ty), value: Id::new(value) } +} + +fn blue() -> Descriptor { + Descriptor::new("RGBC").with("Rd ", D::Double(0.0)).with("Grn ", D::Double(0.0)).with("Bl ", D::Double(255.0)) +} + +/// Load a reference-shaped descriptor through the public ATN parser. +fn recorded(event: AtnEvent, d: Descriptor) -> Action { + let bytes = atn::write(&AtnFile { + name: UnicodeString::new_nul("Identifiers"), + expanded: false, + actions: vec![AtnAction { + name: UnicodeString::new_nul("Recorded"), + items: vec![AtnItem { event, descriptor: Some(d), ..Default::default() }], + ..Default::default() + }], + warnings: vec![], + }) + .unwrap(); + atn_cmds::import(&bytes).unwrap().actions.remove(0) +} + +/// Parse the actual saved bytes, so matching import/export mistakes cannot cancel out. +fn saved(action: &Action) -> AtnItem { + let (bytes, skipped) = atn_cmds::export("Identifiers", &[action], &[], false).unwrap(); + assert!(skipped.is_empty()); + let file = atn::parse(&bytes).unwrap(); + assert_eq!(file.actions[0].items.len(), 1); + file.actions[0].items[0].clone() +} + +/// Check the enum type and value in saved bytes independently of the command parameters. +fn enum_value<'a>(d: &'a Descriptor, key: &str, ty: &str) -> &'a Id { + let Some(D::Enumerated { type_id, value }) = d.get(key) else { panic!("missing {key} enumeration") }; + assert_eq!(*type_id, Id::new(ty)); + value +} + +/// Canonical event names and old code imports share the existing gradient parameters. +#[test] +fn gradient_map_writes_the_named_event_and_keeps_legacy_code_imports() { + let stop = |location, color| { + D::Descriptor(Descriptor::new("Clrt").with("Lctn", D::Integer(location)).with("Mdpn", D::Integer(50)).with("Clr ", D::Descriptor(color))) + }; + let red = Descriptor::new("RGBC").with("Rd ", D::Double(255.0)).with("Grn ", D::Double(0.0)).with("Bl ", D::Double(0.0)); + let d = Descriptor::new("GdMp") + .with("Grad", D::Descriptor(Descriptor::new("Grdn").with("Clrs", D::List(vec![stop(0, blue()), stop(4096, red)])))) + .with("Rvrs", D::Boolean(true)) + .with("Dthr", D::Boolean(false)); + for event in [AtnEvent::name("gradientMapEvent"), AtnEvent::Code(*b"GdMp")] { + let action = recorded(event, d.clone()); + assert_eq!(action.steps, vec![("image.adjustments.gradientMap".into(), json!({"stops":[[0,"#0000ff"],[1,"#ff0000"]],"reverse":true,"dither":false}))]); + let written = saved(&action); + assert_eq!(written.event, AtnEvent::name("gradientMapEvent")); + assert!(written.descriptor.unwrap().class_id.is("GdMp")); + } + assert_eq!(recorded(AtnEvent::name("GdMp"), d).steps[0].0, atn_cmds::PHOTOSHOP_STEP); +} + +/// The measured outside identifier changes while inside, centre and unknown values stay safe. +#[test] +fn stroke_outside_writes_otsd_without_changing_inside_or_center() { + for (input, location, canonical) in [("Otsd", "outside", "Otsd"), ("OtsF", "outside", "Otsd"), ("Insd", "inside", "Insd"), ("Cntr", "center", "Cntr")] { + let d = Descriptor::new("null") + .with("Wdth", D::UnitFloat { unit: *b"#Pxl", value: 2.0 }) + .with("Lctn", enm("StrL", input)) + .with("Clr ", D::Descriptor(blue())); + let action = recorded(AtnEvent::Code(*b"Strk"), d); + assert_eq!(action.steps[0].0, "edit.stroke"); + assert_eq!(action.steps[0].1["location"], location); + assert_eq!(*enum_value(saved(&action).descriptor.as_ref().unwrap(), "Lctn", "StrL"), Id::new(canonical)); + } + let unknown = Descriptor::new("null").with("Lctn", enm("StrL", "futureLocation")); + let action = recorded(AtnEvent::Code(*b"Strk"), unknown.clone()); + assert_eq!(action.steps[0].0, atn_cmds::PHOTOSHOP_STEP); + assert_eq!(saved(&action).descriptor, Some(unknown)); +} + +/// A group blend uses Photoshop's actual identifier and reaches the native group command. +#[test] +fn pass_through_uses_the_string_identifier_and_replays_on_a_group() { + for input in ["passThrough", "PsTh"] { + let target = D::Reference(vec![ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul("Group") }]); + let d = Descriptor::new("null").with("null", target).with("T ", D::Descriptor(Descriptor::new("Lyr ").with("Md ", enm("BlnM", input)))); + let action = recorded(AtnEvent::Code(*b"setd"), d); + assert_eq!(action.steps, vec![("layer.setProps".into(), json!({"layer":"Group","blend":"Pass Through"}))]); + let written = saved(&action).descriptor.unwrap(); + let Some(D::Descriptor(props)) = written.get("T ") else { panic!("layer properties lost") }; + assert_eq!(*enum_value(props, "Md ", "BlnM"), Id::new("passThrough")); + let mut s = Session::new(); + s.execute("file.new", json!({"width":4,"height":4})).unwrap(); + s.execute("layer.new.group", json!({"name":"Group"})).unwrap(); + s.execute("layer.setProps", json!({"blend":"Normal"})).unwrap(); + let (id, p) = &action.steps[0]; + s.execute(id, p.clone()).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().blend, photocraft_color::BlendMode::PassThrough); + } +} + +fn canvas() -> Descriptor { + Descriptor::new("null") + .with("Wdth", D::UnitFloat { unit: *b"#Pxl", value: 6.0 }) + .with("Hght", D::UnitFloat { unit: *b"#Pxl", value: 4.0 }) + .with("Hrzn", enm("HrzL", "Left")) + .with("Vrtc", enm("VrtL", "Top ")) +} + +/// Foreground and custom extension colours select visibly different new border pixels. +#[test] +fn canvas_extension_identifiers_preserve_foreground_and_custom_color() { + for (input, custom, canonical, expected) in [ + ("FrgC", false, "FrgC", [1.0, 0.0, 0.0, 1.0]), + ("Frgd", false, "FrgC", [1.0, 0.0, 0.0, 1.0]), + ("Clr ", true, "Clr ", [0.0, 0.0, 1.0, 1.0]), + ("Othr", true, "Clr ", [0.0, 0.0, 1.0, 1.0]), + ] { + let mut d = canvas().with("canvasExtensionColorType", enm("canvasExtensionColorType", input)); + if custom { + d = d.with("canvasExtensionColor", D::Descriptor(blue())); + } + let action = recorded(AtnEvent::Code(*b"CnvS"), d); + assert_eq!(action.steps[0].0, "image.canvasSize"); + assert_eq!(*enum_value(saved(&action).descriptor.as_ref().unwrap(), "canvasExtensionColorType", "canvasExtensionColorType"), Id::new(canonical)); + let mut s = Session::new(); + s.execute("file.new", json!({"width":4,"height":4,"background":"white"})).unwrap(); + s.execute("tools.setColors", json!({"foreground":"#ff0000","background":"#00ff00"})).unwrap(); + let (id, p) = &action.steps[0]; + s.execute(id, p.clone()).unwrap(); + let pixel: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x":5,"y":1})).unwrap()).unwrap(); + assert_eq!(pixel, expected); + } + for d in [ + canvas().with("canvasExtensionColorType", enm("canvasExtensionColorType", "futureColor")).with("canvasExtensionColor", D::Descriptor(blue())), + canvas().with("canvasExtensionColorType", D::Integer(1)), + canvas().with("canvasExtensionColorType", enm("canvasExtensionColorType", "Clr ")), + ] { + let action = recorded(AtnEvent::Code(*b"CnvS"), d.clone()); + assert_eq!(action.steps[0].0, atn_cmds::PHOTOSHOP_STEP); + assert_eq!(saved(&action).descriptor, Some(d)); + } +} + +/// Absolute intent writes the measured code and unknown intent values remain preserved steps. +#[test] +fn absolute_colorimetric_writes_aclr_and_rejects_unknown_intents() { + let profile = || Descriptor::new("null").with("T ", D::Text(UnicodeString::new_nul("sRGB IEC61966-2.1"))); + for input in ["AClr", "AbsC"] { + let action = recorded(AtnEvent::name("convertToProfile"), profile().with("Inte", enm("Inte", input))); + assert_eq!(action.steps, vec![("edit.convertToProfile".into(), json!({"profile":"srgb","intent":"absolute"}))]); + assert_eq!(*enum_value(saved(&action).descriptor.as_ref().unwrap(), "Inte", "Inte"), Id::new("AClr")); + } + for value in [enm("Inte", "futureIntent"), D::Integer(1)] { + let d = profile().with("Inte", value); + let action = recorded(AtnEvent::name("convertToProfile"), d.clone()); + assert_eq!(action.steps[0].0, atn_cmds::PHOTOSHOP_STEP); + assert_eq!(saved(&action).descriptor, Some(d)); + } +} + +/// Wrap uses opening order after tab moves, with overflow-safe offsets and valid ATN references. +#[test] +fn document_offsets_wrap_in_opening_order_and_zero_atn_offsets_stay_kept() { + let mut s = Session::new(); + for name in ["a", "b", "c"] { + s.execute("file.new", json!({"width":2,"height":2,"name":name})).unwrap(); + } + s.execute("document.move", json!({"document":2,"to":0})).unwrap(); + for (offset, expected) in [(-2, "c"), (2, "a"), (5, "a"), (-5, "c"), (i64::MIN, "c"), (i64::MAX, "c"), (0, "b")] { + s.execute("document.activate", json!({"document":2})).unwrap(); + s.execute("document.activate", json!({"offset":offset})).unwrap(); + assert_eq!(s.active().unwrap().doc.name, expected, "{offset}"); + } + for offset in [-2, 2] { + let d = Descriptor::new("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset }])); + let action = recorded(AtnEvent::Code(*b"slct"), d); + assert_eq!(action.steps[0].0, "document.activate"); + s.execute("document.activate", json!({"document":2})).unwrap(); + let (id, p) = &action.steps[0]; + s.execute(id, p.clone()).unwrap(); + assert_eq!(s.active().unwrap().doc.name, if offset < 0 { "c" } else { "a" }); + let written = saved(&action).descriptor.unwrap(); + assert!(matches!(written.get("null"),Some(D::Reference(r)) if matches!(r.as_slice(),[ReferenceItem::Offset{offset:o,..}] if *o==offset))); + } + let zero = Descriptor::new("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset: 0 }])); + let action = recorded(AtnEvent::Code(*b"slct"), zero.clone()); + assert_eq!(action.steps[0].0, atn_cmds::PHOTOSHOP_STEP); + assert_eq!(saved(&action).descriptor, Some(zero)); + assert!(atn_cmds::export("Identifiers", &[&Action::new("Zero", vec![("document.activate".into(), json!({"offset":0}))])], &[], false).is_err()); +}