Preserve action header colours through ATN load and save

This commit is contained in:
yoriswind committed 2026-11-03 02:49:08 -08:00
1 parent 503aa60f5a
commit c135363fe6
7 files changed
+276 -8

No files matched your search

+26 -6
View File
@@ -45,13 +45,33 @@ pub struct Action {
/// filled by Load Actions (`actions.load`) and written by Save Actions (`actions.save`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub set: Option<String>,
/// Button Mode colour. Empty is none; otherwise one of [`BUTTON_COLORS`].
/// Action colour: one of [`BUTTON_COLORS`], or an opaque `@atn-color:N` imported header index.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub color: String,
}
/// Button Mode colours, in Photoshop's order. Empty is no colour.
pub const BUTTON_COLORS: [&str; 8] = ["", "red", "orange", "yellow", "green", "blue", "violet", "gray"];
/// Measured action colours in ATN index order. The classic picker offers the first eight.
pub const BUTTON_COLORS: [&str; 12] = ["", "red", "orange", "yellow", "green", "blue", "violet", "gray", "teal", "blue2", "magenta", "purple"];
const OPAQUE_COLOR_PREFIX: &str = "@atn-color:";
/// Keep unknown u16 header indices in the existing String field without naming a new palette colour.
pub(crate) fn color_from_atn(index: u16) -> String {
BUTTON_COLORS.get(usize::from(index)).map_or_else(|| format!("{OPAQUE_COLOR_PREFIX}{index}"), |name| (*name).to_string())
}
/// Only measured names or canonical unknown-index metadata may be written to an ATN header.
pub(crate) fn color_to_atn(color: &str) -> Option<u16> {
if let Some(index) = BUTTON_COLORS.iter().position(|name| *name == color) {
return u16::try_from(index).ok();
}
let number = color.strip_prefix(OPAQUE_COLOR_PREFIX)?;
if number.len() > 5 {
return None; // A decimal u16 has at most five digits.
}
let index = number.parse::<u16>().ok()?;
(usize::from(index) >= BUTTON_COLORS.len() && number == index.to_string()).then_some(index)
}
impl Action {
pub fn new(name: impl Into<String>, steps: Vec<(String, Value)>) -> Self {
@@ -739,7 +759,7 @@ fn set_color(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "needs \"color\""));
};
if !BUTTON_COLORS.contains(&color) {
return Err(bad(cmd, "color must be empty, red, orange, yellow, green, blue, violet, or gray"));
return Err(bad(cmd, "color must be empty, red, orange, yellow, green, blue, violet, gray, teal, blue2, magenta, or purple"));
}
let Some(action) = s.actions.list.get_mut(idx) else {
return Err(bad(cmd, "no such action"));
@@ -777,7 +797,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Get Action",
menu: &[],
shortcut: None,
params: r##"{"action":name|index} → {name, steps:[[id, params]…], disabled:[step…], dialogs:[step…], set:name|null, color:str} (steps is the shape file.automate.batch and droplets take; disabled lists the 0-based steps playback skips; dialogs the steps whose dialog Photoshop would show; set the action set from Load Actions; color is the Button Mode swatch, or empty)"##,
params: r##"{"action":name|index} → {name, steps:[[id, params]…], disabled:[step…], dialogs:[step…], set:name|null, color:str} (steps is the shape file.automate.batch and droplets take; disabled lists the 0-based steps playback skips; dialogs the steps whose dialog Photoshop would show; set the action set from Load Actions; color is a measured action swatch, empty, or reserved @atn-color:N metadata preserving an unknown imported u16 index)"##,
enabled: always,
run: get,
journal: false,
@@ -847,7 +867,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Set Action Color",
menu: &[],
shortcut: None,
params: r##"{"action":name|index, "color":""|"red"|"orange"|"yellow"|"green"|"blue"|"violet"|"gray"} → {action, color}. The Button Mode colour. Empty clears it."##,
params: r##"{"action":name|index, "color":""|"red"|"orange"|"yellow"|"green"|"blue"|"violet"|"gray"|"teal"|"blue2"|"magenta"|"purple"} → {action, color}. Measured ATN indices 0..11 in that order; blue is classic light blue (5), blue2 is modern blue (9). Empty clears it. Reserved @atn-color:N import metadata cannot be selected."##,
enabled: always,
run: set_color,
journal: false,
+4 -1
View File
@@ -2,6 +2,7 @@ use super::descriptors::{desc, get_obj, jstr};
use super::events::{event_and_descriptor, event_for};
use super::fields::Mapped;
use super::{Action, AtnAction, AtnEvent, AtnFile, AtnItem, D, DEFAULT_SET, Descriptor, PHOTOSHOP_STEP, UnicodeString, Value, atn, json};
use crate::actions_cmds::{color_from_atn, color_to_atn};
// ------------------------------------------------------------------ import
@@ -68,6 +69,7 @@ fn convert_action(file: &AtnFile, a: &AtnAction, set: &str, unsupported: &mut Ve
let name = clip_name(&a.name.to_string_lossy());
let mut action = Action::new(name.clone(), Vec::new());
action.set = Some(clip_name(set));
action.color = color_from_atn(a.color);
for (i, item) in a.items.iter().enumerate() {
let mapped = match (event_for(&item.event), &item.descriptor) {
(Some(e), Some(d)) => (e.from)(d),
@@ -226,7 +228,8 @@ pub fn export(
let mut skipped = Vec::new();
let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new(), ..Default::default() };
for a in actions {
let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() };
let color = color_to_atn(&a.color).ok_or_else(|| format!("action `{}` has an invalid colour", a.name))?;
let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, color, ..Default::default() };
if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) {
(out.function_key, out.shift, out.command) = (n, shift, command);
}
+191
View File
@@ -0,0 +1,191 @@
//! Action-header colours survive the public ATN and native action-library paths.
use photocraft_engine::{
Session,
actions_cmds::{Action, ActionsFile},
atn_cmds,
preset_store::{self, ACTIONS_FILE, MAX_ACTIONS_BYTES, MemBackend, PresetBackend},
};
use photocraft_psd::{
atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem},
descriptor::{Descriptor, UnicodeString, Value as D},
};
use serde_json::json;
const SET: &str = "Colour set";
const NAME: &str = "Colour action";
fn recorded(color: u16) -> AtnFile {
AtnFile {
name: UnicodeString::new_nul(SET),
expanded: true,
actions: vec![AtnAction {
name: UnicodeString::new_nul(NAME),
function_key: 6,
shift: true,
command: true,
color,
items: vec![AtnItem {
event: AtnEvent::name("futureColourFixture"),
dictionary: b"Colour fixture".to_vec(),
enabled: false,
with_dialog: true,
dialog_options: 2,
descriptor: Some(Descriptor::new("null").with("data", D::RawData(vec![3, 1, 4])).with("test", D::Integer(7))),
..Default::default()
}],
..Default::default()
}],
..Default::default()
}
}
fn load(s: &mut Session, color: u16) {
let bytes = atn::write(&recorded(color)).unwrap();
let data = photocraft_engine::paint::tile::b64_encode(&bytes);
s.execute("actions.load", json!({"data": data})).unwrap();
}
fn saved(s: &mut Session) -> AtnFile {
let result = s.execute("actions.save", json!({"set": SET})).unwrap();
assert_eq!(result["skipped"], json!([]));
let bytes = photocraft_engine::paint::tile::b64_decode(result["data"].as_str().unwrap()).unwrap();
atn::parse(&bytes).unwrap()
}
fn same_step_wire(actual: &AtnItem, expected: &AtnItem) {
assert_eq!(actual, expected);
assert_eq!(actual.descriptor.as_ref().unwrap().to_bytes(), expected.descriptor.as_ref().unwrap().to_bytes());
}
/// Save through the user-facing commands before checking the imported colour, exposing real wire loss.
#[test]
fn recorded_red_survives_public_load_and_save_without_other_edits() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 2, "height": 2})).unwrap();
let before = s.active().unwrap().doc.clone();
let past = s.active().unwrap().history.past_len();
let original_shortcuts = s.prefs().shortcuts.clone();
load(&mut s, 1);
let actions = s.actions.list.clone();
let revision = s.actions.rev;
let shortcuts = s.prefs().shortcuts.clone();
let output = saved(&mut s);
assert_eq!(output.actions[0].color, 1, "public Load/Save Actions discarded the red header colour");
assert_eq!(s.execute("actions.get", json!({"action": NAME})).unwrap()["color"], "red");
let expected = recorded(1);
assert_eq!(output, expected);
same_step_wire(&output.actions[0].items[0], &expected.actions[0].items[0]);
assert_eq!(atn_cmds::import(&atn::write(&output).unwrap()).unwrap().actions, actions);
assert_eq!(s.actions.list, actions);
assert_eq!(s.actions.rev, revision);
assert_eq!(s.prefs().shortcuts, shortcuts);
assert_eq!(shortcuts[&format!("{}{NAME}", photocraft_engine::actions_cmds::PLAY_SHORTCUT_PREFIX)], "Cmd+Shift+F6");
for (key, value) in original_shortcuts {
assert_eq!(shortcuts.get(&key), Some(&value));
}
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(s.active().unwrap().history.past_len(), past);
}
/// Expectations come from the measured header indices, including the distinct classic and new blues.
#[test]
fn all_twelve_header_colours_and_named_edits_keep_their_indices() {
for (index, name) in [
(0, ""),
(1, "red"),
(2, "orange"),
(3, "yellow"),
(4, "green"),
(5, "blue"),
(6, "violet"),
(7, "gray"),
(8, "teal"),
(9, "blue2"),
(10, "magenta"),
(11, "purple"),
] {
let mut s = Session::new();
load(&mut s, index);
assert_eq!(s.execute("actions.get", json!({"action": NAME})).unwrap()["color"], name, "index {index}");
assert_eq!(saved(&mut s).actions[0].color, index);
s.execute("actions.setColor", json!({"action": NAME, "color": name})).unwrap();
assert_eq!(saved(&mut s).actions[0].color, index);
if index == 5 {
s.execute("actions.setColor", json!({"action": NAME, "color": "blue2"})).unwrap();
assert_eq!(saved(&mut s).actions[0].color, 9);
s.execute("actions.setColor", json!({"action": NAME, "color": "blue"})).unwrap();
assert_eq!(saved(&mut s).actions[0].color, 5);
}
}
}
/// Unknown header values remain opaque through real native-library writes, reloads and a rename.
#[test]
fn unknown_header_colours_survive_native_persistence_and_unrelated_edits() {
for index in [12, u16::MAX] {
let mem = MemBackend::default();
let mut s = Session::new();
assert!(s.attach_preset_store(preset_store::open(Box::new(mem.clone()))).is_empty());
load(&mut s, index);
let opaque = format!("@atn-color:{index}");
assert_eq!(s.actions.list[0].color, opaque);
s.sync_preset_store();
let bytes = mem.read(ACTIONS_FILE, MAX_ACTIONS_BYTES).unwrap();
let native: ActionsFile = serde_json::from_slice(&bytes).unwrap();
assert_eq!(native.actions, s.actions.list);
let mut reopened = Session::new();
assert!(reopened.attach_preset_store(preset_store::open(Box::new(mem.clone()))).is_empty());
assert_eq!(reopened.actions.list, native.actions);
reopened.execute("actions.rename", json!({"action": NAME, "name": "Renamed"})).unwrap();
assert_eq!(reopened.actions.list[0].color, opaque);
reopened.sync_preset_store();
let mut again = Session::new();
assert!(again.attach_preset_store(preset_store::open(Box::new(mem))).is_empty());
assert_eq!(again.actions.list, reopened.actions.list);
let output = saved(&mut again);
assert_eq!(output.actions[0].color, index);
assert_eq!(output.actions[0].name.to_string_lossy(), "Renamed");
same_step_wire(&output.actions[0].items[0], &recorded(index).actions[0].items[0]);
}
}
/// Reserved metadata cannot be chosen as a palette colour; malformed JSON colours never become none.
#[test]
fn invalid_colour_edits_and_exports_leave_the_library_unchanged() {
let mut s = Session::new();
load(&mut s, 1);
for color in ["@atn-color:12", "@atn-color:65535", "unknown", "@atn-color:012", "@atn-color:65536"] {
let before = s.actions.list.clone();
let revision = s.actions.rev;
let shortcuts = s.prefs().shortcuts.clone();
assert!(s.execute("actions.setColor", json!({"action": NAME, "color": color})).is_err(), "{color}");
assert_eq!(s.actions.list, before);
assert_eq!(s.actions.rev, revision);
assert_eq!(s.prefs().shortcuts, shortcuts);
}
for color in [
"unknown",
"@atn-color:",
"@atn-color:0",
"@atn-color:11",
"@atn-color:012",
"@atn-color:+12",
"@atn-color:-12",
"@atn-color:65536",
"@atn-color:12 ",
"@atn-color:12",
"@atn-color:12.0",
] {
let action: Action = serde_json::from_value(json!({"name": NAME, "steps": [], "color": color})).unwrap();
let original = action.clone();
for skip in [false, true] {
assert!(atn_cmds::export(SET, &[&action], &[], skip).is_err(), "{color}, skipUnsupported={skip}");
assert_eq!(action, original);
}
}
let old: Action = serde_json::from_value(json!({"name": "Old", "steps": []})).unwrap();
assert!(old.color.is_empty());
let (bytes, skipped) = atn_cmds::export(SET, &[&old], &[], false).unwrap();
assert!(skipped.is_empty());
assert_eq!(atn::parse(&bytes).unwrap().actions[0].color, 0);
}
+1
View File
@@ -2,6 +2,7 @@
mod affinity;
mod artboard_export_names;
mod atn_action_colors;
mod atn_crystallize_cell_size;
mod atn_reference_forms;
mod atn_ripple_amount;
+3 -1
View File
@@ -416,7 +416,7 @@ fn button_fill(color: &str, t: &Tokens) -> Color32 {
}
fn button_label_color(color: &str, t: &Tokens) -> Color32 {
if color.is_empty() { t.text } else { Color32::from_rgb(20, 20, 20) }
if matches!(color, "red" | "orange" | "yellow" | "green" | "blue" | "violet" | "gray") { Color32::from_rgb(20, 20, 20) } else { t.text }
}
fn paint_check(ui: &egui::Ui, rect: Rect, on: bool, t: &Tokens) {
@@ -1579,5 +1579,7 @@ fn draw_step_controls(ui: &mut egui::Ui, rect: Rect, step: usize, label: &str, c
(check.on_hover_text(tl!("Include in playback")), dialog.on_hover_text(tl!("Show dialog during playback")))
}
#[cfg(test)]
mod metadata_color_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,35 @@
use super::{button_fill, button_label_color};
use crate::theme::{ThemeKind, Tokens};
use egui::Color32;
/// Imported colours without a classic swatch use the theme's complete neutral foreground/background pair.
#[test]
fn metadata_colours_use_readable_neutral_button_tokens() {
for kind in [ThemeKind::Pro, ThemeKind::ProLight] {
let t = Tokens::for_kind(kind);
for color in ["", "teal", "blue2", "magenta", "purple", "@atn-color:12", "@atn-color:65535"] {
assert_eq!(button_fill(color, &t), t.card, "{kind:?}/{color}");
assert_eq!(button_label_color(color, &t), t.text, "{kind:?}/{color}");
}
}
}
/// Metadata preservation does not alter the classic seven named swatches or their existing foreground.
#[test]
fn classic_button_swatches_keep_their_original_colours() {
for kind in [ThemeKind::Pro, ThemeKind::ProLight] {
let t = Tokens::for_kind(kind);
for (color, fill) in [
("red", Color32::from_rgb(196, 64, 64)),
("orange", Color32::from_rgb(204, 120, 40)),
("yellow", Color32::from_rgb(196, 176, 48)),
("green", Color32::from_rgb(56, 140, 72)),
("blue", Color32::from_rgb(48, 104, 176)),
("violet", Color32::from_rgb(120, 72, 168)),
("gray", t.text_dim),
] {
assert_eq!(button_fill(color, &t), fill, "{kind:?}/{color}");
assert_eq!(button_label_color(color, &t), Color32::from_rgb(20, 20, 20), "{kind:?}/{color}");
}
}
}
+16
View File
@@ -18,6 +18,22 @@ 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.
## Action header colours
Load and Save Actions preserve each action's colour index. Indices 0–11 map to
`""`, `red`, `orange`, `yellow`, `green`, `blue`, `violet`, `gray`, `teal`, `blue2`,
`magenta`, and `purple`, respectively. The existing `blue` name remains index 5
(light blue); `blue2` is the newer blue at index 9. `actions.setColor` accepts
these measured names. The classic colour menu keeps its eight choices.
An unknown u16 colour index is retained in native action JSON as the reserved
String `@atn-color:N`, where `N` is its canonical decimal index from 12 to 65535.
It survives library reloads and ATN export, but cannot be selected with
`actions.setColor`. Invalid colour strings fail export, including exports with
`skipUnsupported`, rather than silently becoming index 0. New colours and unknown
indices use a neutral theme card in Classic Button Mode until their swatches are
provided by the newer editor. This header support does not parse an action sidecar.
## Supported events (144)
| Code | String ID | Label | PhotoCraft command(s) |