Preserve Actions targets and reject incomplete definition publication

This commit is contained in:
yoriswind committed 2026-11-03 20:41:06 -08:00
1 parent 8038f78059
commit d72aa36d1d
9 files changed
+474 -70

No files matched your search

+27 -10
View File
@@ -916,10 +916,16 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
fn remove_actions(s: &mut Session, removed: &[usize]) -> Vec<String> {
let old_len = s.actions.list.len();
let names: Vec<_> = removed.iter().filter_map(|&index| s.actions.list.get(index).map(|action| action.name.clone())).collect();
let mut vanished: BTreeSet<&str> = names.iter().map(String::as_str).collect();
for (index, action) in s.actions.list.iter().enumerate() {
if removed.binary_search(&index).is_err() {
vanished.remove(action.name.as_str());
}
}
for (id, params) in s.actions.list.iter_mut().flat_map(|action| &mut action.steps) {
for &key in call_keys(id) {
let Some(value) = params.get(key) else { continue };
if value.as_str().is_some_and(|name| names.iter().any(|deleted| deleted == name)) {
if value.as_str().is_some_and(|name| vanished.contains(name)) {
params[key] = Value::Null;
} else if let Some(index) = num(value).and_then(|index| usize::try_from(index).ok()).filter(|&index| index < old_len) {
match removed.binary_search(&index) {
@@ -936,7 +942,7 @@ fn remove_actions(s: &mut Session, removed: &[usize]) -> Vec<String> {
index += 1;
keep
});
let keys: Vec<_> = names.iter().map(|name| format!("{PLAY_SHORTCUT_PREFIX}{name}")).collect();
let keys: Vec<_> = vanished.iter().map(|name| format!("{PLAY_SHORTCUT_PREFIX}{name}")).collect();
if keys.iter().any(|key| s.prefs().shortcuts.contains_key(key) || s.prefs().alternate_shortcuts.contains_key(key)) {
s.edit_prefs(|prefs| {
for key in &keys {
@@ -999,6 +1005,11 @@ fn call_keys(id: &str) -> &'static [&'static str] {
}
}
/// Named calls and shortcuts resolve to the first matching occurrence.
fn owns_name(list: &[Action], index: usize) -> bool {
list.get(index).is_some_and(|action| list.iter().position(|candidate| candidate.name == action.name) == Some(index))
}
/// Rename an action in place. Nested `actions.play` steps and `actions.conditional` branches
/// that call it by name, and its function-key binding, follow the new name so nothing silently
/// stops working.
@@ -1018,12 +1029,15 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
if s.actions.list.iter().any(|a| a.name == name) {
return Err(bad("actions.rename", "an action with this name already exists"));
}
let pending = s.actions.recording_cursor().unwrap_or(s.journal.len());
let calls = s.actions.list.iter_mut().flat_map(|a| a.steps.iter_mut()).chain(s.journal.iter_mut().skip(pending));
for (id, params) in calls {
for key in call_keys(id) {
if params.get(*key).and_then(Value::as_str) == Some(old.as_str()) {
params[*key] = json!(name);
let follows = owns_name(&s.actions.list, idx);
if follows {
let pending = s.actions.recording_cursor().unwrap_or(s.journal.len());
let calls = s.actions.list.iter_mut().flat_map(|a| a.steps.iter_mut()).chain(s.journal.iter_mut().skip(pending));
for (id, params) in calls {
for key in call_keys(id) {
if params.get(*key).and_then(Value::as_str) == Some(old.as_str()) {
params[*key] = json!(name);
}
}
}
}
@@ -1032,10 +1046,13 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
}
s.actions.touch();
let (from, to) = (format!("{PLAY_SHORTCUT_PREFIX}{old}"), format!("{PLAY_SHORTCUT_PREFIX}{name}"));
if s.prefs().shortcuts.contains_key(&from) {
if follows && (s.prefs().shortcuts.contains_key(&from) || s.prefs().alternate_shortcuts.contains_key(&from)) {
s.edit_prefs(|prefs| {
if let Some(key) = prefs.shortcuts.remove(&from) {
prefs.shortcuts.insert(to, key);
prefs.shortcuts.insert(to.clone(), key);
}
if let Some(key) = prefs.alternate_shortcuts.remove(&from) {
prefs.alternate_shortcuts.insert(to, key);
}
});
}
+35 -10
View File
@@ -189,6 +189,15 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
let mut next = draft.clone();
if let Some(value) = p.get("name") {
next.value.name = name(value, Some(&next.value.name), UPDATE)?;
if next.value.name != draft.value.name
&& next
.value
.steps
.iter()
.any(|(id, params)| super::call_keys(id).iter().any(|key| params.get(key).and_then(Value::as_str) == Some(next.value.name.as_str())))
{
return Err(bad(UPDATE, "an action cannot play itself"));
}
}
if let Some(value) = p.get("description") {
next.value.description = value.as_str().ok_or_else(|| bad(UPDATE, "`description` must be a string"))?.to_string();
@@ -223,7 +232,7 @@ fn index(p: &Value, key: &str, len: usize, insert: bool) -> Result<usize> {
}
/// Validate newly authored content, without interpreting or normalizing an untouched opaque step.
fn new_step(p: &Value, old: Option<&(String, Value)>, draft: &Draft) -> Result<(String, Value)> {
fn new_step(s: &Session, p: &Value, old: Option<&(String, Value)>, draft: &Draft) -> Result<(String, Value)> {
let id = match p.get("id") {
Some(Value::String(id)) => id.as_str(),
Some(_) => return Err(bad(STEP, "`id` must be a command string")),
@@ -236,10 +245,13 @@ fn new_step(p: &Value, old: Option<&(String, Value)>, draft: &Draft) -> Result<(
if !crate::actions_edit_cmds::is_step_command(id) || !params.is_object() {
return Err(bad(STEP, "a new step needs a known command and object params"));
}
if id == "actions.play"
&& (params.get("action").and_then(Value::as_str) == Some(draft.value.name.as_str())
|| draft.source.is_some_and(|source| params.get("action").and_then(Value::as_u64) == Some(source as u64)))
{
let owns_current_name = draft.value.name != draft.opening.name || draft.source.is_none_or(|index| super::owns_name(&s.actions.list, index));
if super::call_keys(id).iter().any(|key| {
owns_current_name && params.get(key).and_then(Value::as_str) == Some(draft.value.name.as_str())
|| draft.source.is_some_and(|index| super::owns_name(&s.actions.list, index))
&& params.get(key).and_then(Value::as_str) == Some(draft.opening.name.as_str())
|| draft.source.is_some_and(|source| params.get(key).and_then(Value::as_u64) == Some(source as u64))
}) {
return Err(bad(STEP, "an action cannot play itself"));
}
Ok((id.to_string(), params))
@@ -251,10 +263,10 @@ fn remap(value: &mut Action, old_len: usize, f: impl Fn(usize) -> Option<usize>)
}
/// Insert or replace after complete validation, retaining all unrelated Action fields.
fn insert_or_replace(value: &mut Action, draft: &Draft, p: &Value, op: &str) -> Result<()> {
fn insert_or_replace(s: &Session, value: &mut Action, draft: &Draft, p: &Value, op: &str) -> Result<()> {
let len = value.steps.len();
let at = index(p, "step", len, op == "insert")?;
let step = new_step(p, if op == "replace" { value.steps.get(at) } else { None }, draft)?;
let step = new_step(s, p, if op == "replace" { value.steps.get(at) } else { None }, draft)?;
if op == "insert" {
if len >= MAX_STEPS {
return Err(bad(STEP, "the draft exceeds the 100000-step limit"));
@@ -319,7 +331,7 @@ fn step(s: &mut Session, p: &Value) -> Result<Value> {
STEP,
)?;
match op {
"insert" | "replace" => insert_or_replace(&mut value, draft, p, op)?,
"insert" | "replace" => insert_or_replace(s, &mut value, draft, p, op)?,
"delete" | "move" | "duplicate" => rearrange(&mut value, p, op)?,
"enabled" | "dialog" => {
let at = index(p, "step", value.steps.len(), false)?;
@@ -411,7 +423,7 @@ fn rename_calls(params: &mut Value, id: &str, old: &str, new: &str) {
/// Only changed references need prepared copies; no library or Session snapshot is taken.
fn references(s: &Session, draft: &Draft, value: &mut Action) -> Vec<(usize, usize, Value)> {
let mut changes = Vec::new();
if draft.source.is_none() || draft.opening.name == value.name {
if !draft.source.is_some_and(|index| super::owns_name(&s.actions.list, index)) || draft.opening.name == value.name {
return changes;
}
for (id, params) in &mut value.steps {
@@ -435,7 +447,7 @@ fn bindings(s: &Session, draft: &Draft, value: &Action) -> Bindings {
let mut alternates = s.prefs().alternate_shortcuts.clone();
let old = format!("{}{}", super::PLAY_SHORTCUT_PREFIX, draft.opening.name);
let new = format!("{}{}", super::PLAY_SHORTCUT_PREFIX, value.name);
if draft.source.is_some() && old != new {
if draft.source.is_some_and(|index| super::owns_name(&s.actions.list, index)) && old != new {
if let Some(key) = keys.remove(&old) {
keys.insert(new.clone(), key);
}
@@ -460,6 +472,9 @@ fn bindings(s: &Session, draft: &Draft, value: &Action) -> Bindings {
fn save(s: &mut Session, p: &Value) -> Result<Value> {
fields(p, &["draft"], SAVE)?;
not_playing(s, SAVE)?;
if s.has_recording_job() {
return Err(bad(SAVE, "finish the recorded step before saving the action"));
}
let draft = owned(s, p, SAVE)?;
if s.actions.recording.is_some() {
return Err(bad(SAVE, "stop Classic recording first"));
@@ -481,6 +496,16 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(SAVE, "an action with this name already exists"));
}
let changes = references(s, draft, &mut value);
super::library::check_action_count(
&s.actions,
s.actions
.list
.iter()
.enumerate()
.map(|(index, action)| if Some(index) == draft.source { &value } else { action })
.chain(draft.source.is_none().then_some(&value)),
)
.map_err(|error| bad(SAVE, error))?;
let (keys, alternates) = bindings(s, draft, &value);
let target = draft.source.unwrap_or(s.actions.list.len());
let changed = draft.source.is_none() || value != draft.opening || !changes.is_empty();
+39 -8
View File
@@ -12,6 +12,21 @@ use crate::atn_cmds::{self, sidecar};
type Result<T> = std::result::Result<T, String>;
const MAX_BYTES: usize = crate::preset_store::MAX_ACTIONS_BYTES as usize;
/// Check the encoded action-count ceiling before a definition edit is published.
/// The metadata carrier consumes one real ATN action even though it is hidden in the panel.
pub(crate) fn check_action_count<'a>(state: &ActionState, actions: impl IntoIterator<Item = &'a Action>) -> Result<()> {
let mut count = 0usize;
let mut carrier = state.library.sidecar.is_some() || state.library.legacy.is_some() || !state.atn_set_rows.is_empty();
for action in actions {
count = count.checked_add(1).ok_or("Actions count overflow")?;
carrier |= sidecar::action_needs_metadata(action);
}
if count.checked_add(usize::from(carrier)).is_none_or(|total| total > atn::MAX_TOTAL_ACTIONS) {
return Err("actions archive leaves no space for the action and its metadata sidecar".into());
}
Ok(())
}
#[derive(Debug)]
struct Archive {
bytes: Arc<[u8]>,
@@ -45,6 +60,7 @@ pub struct StepOrigin {
pub(crate) struct RowOrigin {
archive: Arc<Archive>,
set: usize,
logical_name: String,
}
impl RowOrigin {
@@ -164,17 +180,35 @@ pub(crate) fn decode(bytes: &[u8]) -> Result<ActionState> {
state.library.sidecar = metadata.source;
state.library.legacy = legacy;
let mut total = 0usize;
let mut set_names = atn_cmds::UniqueNames::new(
std::iter::once(atn_cmds::UNGROUPED_SET.to_string()).chain(
archive
.parsed
.sets
.iter()
.enumerate()
.filter(|(index, _)| Some(*index) != archive.hidden)
.map(|(_, file)| file.name.to_string_lossy())
.filter(|name| !name.is_empty()),
),
);
let literal_ungrouped = set_names.claim(atn_cmds::UNGROUPED_SET);
for (set, file) in archive.parsed.sets.iter().enumerate().filter(|(index, _)| Some(*index) != archive.hidden) {
let wire_name = file.name.to_string_lossy();
let row = RowOrigin { archive: archive.clone(), set };
let logical_name = if wire_name == atn_cmds::UNGROUPED_SET {
literal_ungrouped.as_str()
} else {
atn_cmds::logical_set_name((!wire_name.is_empty()).then_some(wire_name.as_str()))
};
let row = RowOrigin { archive: archive.clone(), set, logical_name: logical_name.to_string() };
let slot = state.sets.len();
state.sets.push(atn_cmds::logical_set_name((!wire_name.is_empty()).then_some(wire_name.as_str())).to_string());
state.sets.push(logical_name.to_string());
state.library.rows.push(Some(row.clone()));
if let Some(source) = metadata.sets.get_mut(set).and_then(Option::take) {
state.atn_set_rows.push(sidecar::SetRowMetadata { slot, row: state.sets.last().cloned().ok_or("missing loaded row")?, source });
}
for (index, original) in file.actions.iter().enumerate() {
let (mut action, cohorts) = atn_cmds::library_action(file, original, &wire_name)?;
let (mut action, cohorts) = atn_cmds::library_action(file, original, if wire_name.is_empty() { "" } else { logical_name })?;
total = total.checked_add(action.steps.len()).filter(|count| *count <= atn::MAX_TOTAL_ITEMS).ok_or("too many native steps in Actions library")?;
if let Some(metadata) = metadata.actions.get_mut(set).and_then(|actions| actions.get_mut(index)).and_then(Option::take) {
sidecar::apply(&mut action, metadata);
@@ -366,7 +400,7 @@ pub(crate) fn encode(state: &ActionState, keys: &[(String, String)]) -> Result<V
.filter(|bytes| *bytes <= MAX_BYTES)
.ok_or("Actions text exceeds library byte limit")?;
}
let groups = sidecar::groups(state, None)?;
let groups = sidecar::library_groups(state)?;
let mut names = std::collections::HashMap::new();
for action in &state.list {
*names.entry(action.name.as_str()).or_insert(0usize) += 1;
@@ -377,10 +411,7 @@ pub(crate) fn encode(state: &ActionState, keys: &[(String, String)]) -> Result<V
let original = selection.raw.as_ref().map(RowOrigin::file).transpose()?;
let mut file = original.cloned().unwrap_or_default();
let wire = atn_cmds::wire_set_name(name);
if original.is_none_or(|old| {
let source_name = old.name.to_string_lossy();
atn_cmds::logical_set_name((!source_name.is_empty()).then_some(source_name.as_str())) != *name
}) {
if selection.raw.as_ref().is_none_or(|row| row.logical_name != *name) {
file.name = UnicodeString::new_nul(wire);
}
file.actions.clear();
@@ -58,6 +58,58 @@ fn untouched_duplicate_physical_records_and_noncanonical_bytes_survive() {
assert_ne!(atn::write_sets(&atn::parse_sets(&bytes).unwrap()).unwrap(), bytes);
}
/// Strict loading preserves repeated physical rows; external import intentionally renames them.
fn ordered_archive(rows: &[(&str, &[Action])]) -> Vec<u8> {
let files: Vec<_> = rows
.iter()
.map(|(name, actions)| {
let refs: Vec<_> = actions.iter().collect();
let (bytes, skipped) = atn_cmds::export(name, &refs, &[], false).unwrap();
assert!(skipped.is_empty());
atn::parse_sets(&bytes).unwrap().remove(0)
})
.collect();
atn::write_sets(&files).unwrap()
}
#[test]
fn durable_regrouping_keeps_flat_call_targets_and_empty_rows() {
let first = Action::new("First", vec![]);
let second = Action::new("Second", vec![]);
let other = Action::new("Other", vec![]);
let caller = Action::new("Caller", vec![("actions.play".into(), json!({"action":1}))]);
let bytes = ordered_archive(&[("Before", &[]), ("A", &[first, second]), ("Between", &[]), ("B", &[other]), ("C", &[caller])]);
let state = library::decode(&bytes).unwrap();
assert_eq!(encode(&state), bytes, "untouched empty rows retain exact physical placement");
let mut session = crate::Session::new();
session.actions = state;
session.execute("actions.assignSet", json!({"action":0,"set":"B"})).unwrap();
let restored = library::decode(&encode(&session.actions)).unwrap();
assert_eq!(restored.list.iter().map(|action| action.name.as_str()).collect::<Vec<_>>(), ["First", "Second", "Other", "Caller"]);
assert_eq!(restored.list[3].steps[0].1["action"], 1);
assert_eq!(restored.list[1].name, "Second");
for name in ["Before", "Between"] {
assert_eq!(restored.sets.iter().filter(|row| row.as_str() == name).count(), 1);
}
}
#[test]
fn duplicate_physical_rows_stay_after_all_original_targets() {
let first = Action::new("First", vec![]);
let second = Action::new("Second", vec![]);
let caller = Action::new("Caller", vec![("actions.play".into(), json!({"action":1}))]);
let bytes = ordered_archive(&[("Group", &[first]), ("Empty", &[]), ("Group", &[second]), ("Other", &[caller])]);
let mut session = crate::Session::new();
session.actions = library::decode(&bytes).unwrap();
session.execute("actions.duplicate", json!({"set":"Group"})).unwrap();
let restored = library::decode(&encode(&session.actions)).unwrap();
assert_eq!(restored.list.iter().map(|action| action.name.as_str()).collect::<Vec<_>>(), ["First", "Second", "First copy", "Second copy", "Caller"]);
assert_eq!(restored.list[4].steps[0].1["action"], 1);
assert_eq!(restored.list[1].name, "Second");
assert_eq!(restored.sets.iter().filter(|name| name.as_str() == "Group").count(), 2);
assert_eq!(restored.sets.iter().filter(|name| name.as_str() == "Empty").count(), 1);
}
#[test]
fn changing_one_name_preserves_every_other_original_field_and_occurrence() {
let bytes = wire();
@@ -151,9 +203,47 @@ fn empty_library_has_a_known_carrier_and_no_invented_user_folder() {
assert!(loaded.sets.is_empty());
assert_eq!(atn::parse_sets(&bytes).unwrap().len(), 1);
assert_eq!(encode(&loaded), bytes);
let imported = atn_cmds::import(&bytes).unwrap();
assert!(imported.actions.is_empty());
assert!(imported.sets.is_empty());
// A foreign sidecar with no real set is still rejected; only the explicit native
// empty-library marker permits this otherwise ambiguous input through public import.
let mut files = atn::parse_sets(&bytes).unwrap();
let outer = files[0].actions[0].items[0].descriptor.as_mut().unwrap();
let (_, D::RawData(payload)) = outer.items.iter_mut().find(|(id, _)| id.is("modernizedActionData")).unwrap() else { panic!("native payload") };
let mut root = Descriptor::from_bytes(&payload[4..]).unwrap();
root.items.retain(|(id, _)| !id.is("photocraftEmptyLibraryV1"));
payload.truncate(4);
payload.extend(root.to_bytes());
assert!(atn_cmds::import(&atn::write_sets(&files).unwrap()).is_err());
assert!(library::decode(&16u32.to_be_bytes()).is_err());
}
#[test]
fn literal_ungrouped_rows_remain_distinct_from_the_unnamed_category() {
let rows = [("", "Loose"), (atn_cmds::UNGROUPED_SET, "Named"), ("Ungrouped Actions 2", "Collision")];
let files: Vec<_> = rows
.iter()
.map(|(set, action)| AtnFile {
name: UnicodeString::new_nul(set),
actions: vec![AtnAction { name: UnicodeString::new_nul(action), ..Default::default() }],
..Default::default()
})
.collect();
let bytes = atn::write_sets(&files).unwrap();
let state = library::decode(&bytes).unwrap();
assert_eq!(state.sets, ["Ungrouped Actions", "Ungrouped Actions 3", "Ungrouped Actions 2"]);
assert_eq!(state.list[0].set, None);
assert_eq!(state.list[1].set.as_deref(), Some("Ungrouped Actions 3"));
assert_eq!(encode(&state), bytes, "logical disambiguation keeps untouched original wire names");
let mut session = crate::Session::new();
session.actions = state;
session.execute("actions.delete", json!({"set":"Ungrouped Actions"})).unwrap();
assert_eq!(session.actions.list.iter().map(|action| action.name.as_str()).collect::<Vec<_>>(), ["Named", "Collision"]);
let loaded = library::decode(&encode(&session.actions)).unwrap();
assert_eq!(loaded.list.iter().map(|action| action.name.as_str()).collect::<Vec<_>>(), ["Named", "Collision"]);
}
fn legacy() -> Vec<u8> {
br#" {"version":1,"actions":[{"name":"Legacy","description":"kept","steps":[["future.command",{"x":1}]],"disabled":[0]}]} "#.to_vec()
}
@@ -177,6 +267,24 @@ fn migration_publishes_one_atn_and_renames_exact_json_bytes_once() {
}
}
#[test]
fn portable_exports_do_not_inherit_full_library_migration_receipts() {
let bytes = legacy();
let mem = MemBackend::default();
mem.files.lock().unwrap().insert(LEGACY_ACTIONS_FILE.into(), bytes.clone());
assert!(preset_store::open(Box::new(mem.clone())).warnings.is_empty());
let state = library::decode(&mem.read(ACTIONS_FILE, MAX_ACTIONS_BYTES).unwrap()).unwrap();
assert!(state.library.legacy.as_ref().unwrap().matches(&bytes));
let (portable, skipped) = atn_cmds::export("Portable", &[&state.list[0]], &[], false).unwrap();
assert!(skipped.is_empty());
assert!(library::decode(&portable).unwrap().library.legacy.is_none());
let unrelated_store = MemBackend::default();
unrelated_store.files.lock().unwrap().extend([(ACTIONS_FILE.into(), portable), (LEGACY_ACTIONS_FILE.into(), bytes.clone())]);
let _ = preset_store::open(Box::new(unrelated_store.clone()));
assert_eq!(unrelated_store.read(LEGACY_ACTIONS_FILE, MAX_ACTIONS_BYTES).unwrap(), bytes);
assert!(unrelated_store.read(MIGRATED_ACTIONS_FILE, MAX_ACTIONS_BYTES).is_err());
}
#[test]
fn corrupt_atn_has_precedence_and_corrupt_legacy_is_never_overwritten() {
for (name, bytes) in [(ACTIONS_FILE, b"broken ATN".to_vec()), (LEGACY_ACTIONS_FILE, b"broken JSON".to_vec())] {
+3 -1
View File
@@ -137,6 +137,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let mut copied = s.actions.list[idx].clone();
let mut names = crate::atn_cmds::UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone()));
copied.name = names.claim(&format!("{} copy", copied.name));
crate::actions_cmds::library::check_action_count(&s.actions, s.actions.list.iter().chain(std::iter::once(&copied))).map_err(|error| bad(cmd, error))?;
let at = idx + 1;
let result = json!({"action": copied.name, "index": at, "steps": copied.steps.len()});
s.actions.list.insert(at, copied);
@@ -162,7 +163,7 @@ fn duplicate_set(s: &mut Session, p: &Value) -> Result<Value> {
let mut set_names = crate::atn_cmds::UniqueNames::new(sets);
let name = set_names.claim(&format!("{source} copy"));
let mut names = crate::atn_cmds::UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone()));
let at = s.actions.list.iter().position(|a| crate::atn_cmds::logical_set_name(a.set.as_deref()) == source).map_or(s.actions.list.len(), |i| i + 1);
let at = s.actions.list.iter().rposition(|a| crate::atn_cmds::logical_set_name(a.set.as_deref()) == source).map_or(s.actions.list.len(), |i| i + 1);
let added: Vec<_> = s
.actions
.list
@@ -177,6 +178,7 @@ fn duplicate_set(s: &mut Session, p: &Value) -> Result<Value> {
.collect();
let copied: Vec<_> = added.iter().map(|a| a.name.clone()).collect();
let count = added.len();
crate::actions_cmds::library::check_action_count(&s.actions, s.actions.list.iter().chain(added.iter())).map_err(|error| bad(cmd, error))?;
s.actions.list.splice(at..at, added);
if count != 0 {
shift_action_calls(&mut s.actions.list, at, count);
+67 -39
View File
@@ -10,6 +10,7 @@ use super::{Action, AtnAction, AtnEvent, AtnFile, AtnItem};
use crate::actions_cmds::ActionState;
const MODERN: &str = "modernizedActionData";
const EMPTY_LIBRARY: &str = "photocraftEmptyLibraryV1";
const MAX_BYTES: usize = crate::preset_import_cmds::MAX_FILE_BYTES as usize;
type Result<T> = std::result::Result<T, String>;
@@ -250,7 +251,7 @@ pub(crate) fn install_row(state: &mut ActionState, name: &str, source: Option<Ar
/// surviving row carriers with the insertion. Action clones already retain their raw entries.
pub(crate) fn duplicate_set_rows(state: &mut ActionState, source: &str, name: &str) {
let rows: Vec<_> = state.sets.iter().enumerate().filter_map(|(slot, row)| (row == source).then_some(slot)).collect();
let at = rows.first().map_or(state.sets.len(), |slot| slot + 1);
let at = rows.last().map_or(state.sets.len(), |slot| slot + 1);
let mut copied: Vec<_> = rows.iter().map(|&slot| empty_source(state, slot)).collect();
if copied.is_empty() {
copied.push(group_source(state, source));
@@ -334,43 +335,61 @@ pub(crate) fn selection<'a>(state: &ActionState, action: &'a Action) -> Selectio
}
pub(crate) fn groups<'a>(state: &'a ActionState, only: Option<&str>) -> Result<Vec<(&'a str, Selection<'a>)>> {
groups_ordered(state, only, false)
}
/// Durable libraries preserve flat resolution order, including interleaved logical sets.
pub(crate) fn library_groups(state: &ActionState) -> Result<Vec<(&str, Selection<'_>)>> {
groups_ordered(state, None, true)
}
fn groups_ordered<'a>(state: &'a ActionState, only: Option<&str>, durable: bool) -> Result<Vec<(&'a str, Selection<'a>)>> {
if state.list.len() > atn::MAX_TOTAL_ACTIONS || state.sets.len() > atn::MAX_SETS {
return Err("action library exceeds archive limits".into());
}
let raw_rows = state.library.row_index(&state.sets);
let mut names = std::collections::HashSet::new();
let mut seen = std::collections::HashSet::new();
let names: Vec<_> = state
.list
.iter()
.map(|action| super::logical_set_name(action.set.as_deref()))
.chain(state.sets.iter().map(String::as_str))
.filter(|name| only.is_none_or(|only| only == *name) && seen.insert(*name))
.collect();
let sources: std::collections::HashMap<_, _> = names.iter().map(|&name| (name, group_source(state, name))).collect();
let mut out: Vec<(&str, Selection<'a>)> = Vec::new();
for name in state.list.iter().map(|action| super::logical_set_name(action.set.as_deref())).chain(state.sets.iter().map(String::as_str)) {
if only.is_some_and(|only| only != name) || !names.insert(name) {
continue;
}
let fallback = group_source(state, name);
let before = out.len();
for action in state.list.iter().filter(|action| super::logical_set_name(action.set.as_deref()) == name) {
let source = action.atn_metadata.as_ref().and_then(|metadata| metadata.set.clone()).or_else(|| fallback.clone());
let raw = raw_rows.source(action);
let existing = out.last_mut().filter(|(previous, selection)| {
*previous == name
&& selection.raw == raw
&& match (&selection.source, &source) {
(None, None) => true,
(Some(left), Some(right)) => same_set(left, right),
_ => false,
}
});
if let Some((_, selection)) = existing {
selection.actions.push(action);
} else {
if out.len() >= atn::MAX_SETS {
return Err("too many sets in actions archive".into());
let ordered: Vec<_> = if durable {
state.list.iter().collect()
} else {
names.iter().flat_map(|name| state.list.iter().filter(move |action| super::logical_set_name(action.set.as_deref()) == *name)).collect()
};
for action in ordered {
let name = super::logical_set_name(action.set.as_deref());
let source = action.atn_metadata.as_ref().and_then(|metadata| metadata.set.clone()).or_else(|| sources.get(name).cloned().flatten());
let raw = raw_rows.source(action);
let existing = out.last_mut().filter(|(previous, selection)| {
*previous == name
&& selection.raw == raw
&& match (&selection.source, &source) {
(None, None) => true,
(Some(left), Some(right)) => same_set(left, right),
_ => false,
}
out.push((name, Selection { actions: vec![action], source, raw }));
});
if let Some((_, selection)) = existing {
selection.actions.push(action);
} else {
if out.len() >= atn::MAX_SETS {
return Err("too many sets in actions archive".into());
}
out.push((name, Selection { actions: vec![action], source, raw }));
}
}
for name in names {
for (slot, _) in state.sets.iter().enumerate().filter(|(_, row)| row.as_str() == name) {
let raw = state.library.rows.get(slot).cloned().flatten();
if let Some(raw) = raw.as_ref()
&& !out.iter().skip(before).any(|(_, selection)| selection.raw.as_ref() == Some(raw))
&& !out.iter().any(|(current, selection)| *current == name && selection.raw.as_ref() == Some(raw))
{
if out.len() >= atn::MAX_SETS {
return Err("too many sets in actions archive".into());
@@ -378,7 +397,7 @@ pub(crate) fn groups<'a>(state: &'a ActionState, only: Option<&str>) -> Result<V
out.push((name, Selection { actions: Vec::new(), source: empty_source(state, slot), raw: Some(raw.clone()) }));
}
if let Some(source) = empty_source(state, slot)
&& !out.iter().skip(before).any(|(_, selection)| selection.source.as_ref().is_some_and(|existing| same_set(existing, &source)))
&& !out.iter().any(|(current, selection)| *current == name && selection.source.as_ref().is_some_and(|existing| same_set(existing, &source)))
{
if out.len() >= atn::MAX_SETS {
return Err("too many sets in actions archive".into());
@@ -386,15 +405,15 @@ pub(crate) fn groups<'a>(state: &'a ActionState, only: Option<&str>) -> Result<V
out.push((name, Selection { actions: Vec::new(), source: Some(source), raw: state.library.rows.get(slot).cloned().flatten() }));
}
}
if out.len() == before {
if !out.iter().any(|(current, _)| *current == name) {
if out.len() >= atn::MAX_SETS {
return Err("too many sets in actions archive".into());
}
out.push((name, Selection { actions: Vec::new(), source: fallback, raw: None }));
out.push((name, Selection { actions: Vec::new(), source: sources.get(name).cloned().flatten(), raw: None }));
}
}
// Preserve physical rows only when doing so preserves the panel's group/action order.
// An explicit move can change that projection, including S1/S2/S1 runs within one group.
// Restore physical rows only if the relevant order remains unchanged. Durable storage
// must preserve the entire flat list because numeric and first-name calls resolve there.
let mut slots = std::collections::HashMap::new();
for row in &state.atn_set_rows {
if state.sets.get(row.slot) == Some(&row.row) {
@@ -414,7 +433,13 @@ pub(crate) fn groups<'a>(state: &'a ActionState, only: Option<&str>) -> Result<V
.or_else(|| selection.source.as_ref().and_then(|source| slots.get(&(*name, Arc::as_ptr(&source.source), source.ordinal)).copied()))
.unwrap_or(usize::MAX)
});
if panel_projection(&out, 0..out.len()) != panel_projection(&out, physical.iter().copied()) {
let preserves_order = if durable {
let projected: Vec<_> = physical.iter().flat_map(|&index| out[index].1.actions.iter().map(|action| std::ptr::from_ref(*action))).collect();
projected == state.list.iter().map(std::ptr::from_ref).collect::<Vec<_>>()
} else {
panel_projection(&out, 0..out.len()) == panel_projection(&out, physical.iter().copied())
};
if !preserves_order {
return Ok(out);
}
Ok(physical
@@ -535,7 +560,7 @@ fn decode_inner(files: &[AtnFile], library: bool, raw_outer: Option<&[u8]>) -> R
return Err("unsupported Actions sidecar root".into());
}
let sets = root.list("sets")?;
if sets.is_empty() && !library {
if sets.is_empty() && !library && unique(&parsed, EMPTY_LIBRARY)? != &D::Boolean(true) {
return Err("Actions sidecar requires at least one real set".into());
}
if sets.len().checked_add(1) != Some(files.len()) {
@@ -689,6 +714,10 @@ pub(crate) fn append_library(
append_inner(files, selected, force, source, receipt)
}
pub(crate) fn action_needs_metadata(action: &Action) -> bool {
action.atn_metadata.is_some() || !action.description.is_empty() || !action.icon.is_empty()
}
fn append_inner(
files: &mut Vec<AtnFile>,
selected: &[Selection<'_>],
@@ -699,10 +728,7 @@ fn append_inner(
if files.len() != selected.len() {
return Err("sidecar export selection mismatch".into());
}
let needed = selected.iter().any(|selection| {
selection.source.is_some()
|| selection.actions.iter().any(|action| action.atn_metadata.is_some() || !action.description.is_empty() || !action.icon.is_empty())
});
let needed = selected.iter().any(|selection| selection.source.is_some() || selection.actions.iter().any(|action| action_needs_metadata(action)));
if !needed && !force {
return Ok(None);
}
@@ -763,10 +789,12 @@ fn append_inner(
Some(source) => source.root.patch(&[("sets", Some(objects(&sets)?))])?,
None => RawDescriptor::new(&Descriptor::new("null").with("sets", D::List(Vec::new())).to_bytes())?.patch(&[("sets", Some(objects(&sets)?))])?,
};
let root = RawDescriptor::new(&root)?.patch(&[(EMPTY_LIBRARY, if files.is_empty() { Some(value_bytes(D::Boolean(true))?) } else { None })])?;
let root = if let Some(receipt) = receipt {
RawDescriptor::new(&root)?.patch(&[("photocraftLegacyJsonV1", Some(value_bytes(D::Descriptor(receipt.descriptor()?))?))])?
} else {
root
// A portable subset is not proof that the complete legacy library was published.
RawDescriptor::new(&root)?.patch(&[("photocraftLegacyJsonV1", None)])?
};
let mut payload = 16u32.to_be_bytes().to_vec();
extend(&mut payload, &root)?;
@@ -2,6 +2,32 @@
use photocraft_engine::{Session, actions_cmds::Action};
use serde_json::{Value, json};
#[test]
fn a_copied_group_keeps_numeric_call_identity_through_native_store_reload() {
use photocraft_engine::preset_store::{self, MemBackend};
let store = MemBackend::default();
let mut s = session();
assert!(s.attach_preset_store(preset_store::open(Box::new(store.clone()))).is_empty());
let mut first = Action::new("First", vec![("layer.new.layer".into(), json!({"name":"First marker"}))]);
first.set = Some("Group".into());
let mut second = Action::new("Second", vec![("layer.new.layer".into(), json!({"name":"Second marker"}))]);
second.set = Some("Group".into());
let mut caller = Action::new("Caller", vec![("actions.play".into(), json!({"action":1}))]);
caller.set = Some("Other".into());
s.actions.list = vec![first, second, caller];
s.execute("actions.duplicate", json!({"set":"Group"})).unwrap();
assert_eq!(s.actions.list.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["First", "Second", "First copy", "Second copy", "Caller"]);
assert_eq!(s.actions.list[4].steps[0].1["action"], 1);
let mut restored = Session::new();
assert!(restored.attach_preset_store(preset_store::open(Box::new(store))).is_empty());
assert_eq!(restored.actions.list.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["First", "Second", "First copy", "Second copy", "Caller"]);
assert_eq!(restored.actions.list[4].steps[0].1["action"], 1);
restored.execute("file.new", json!({"width":8,"height":6})).unwrap();
let result = restored.execute("actions.play", json!({"action":"Caller"})).unwrap();
assert!(result.get("failed").is_none(), "{result}");
assert_eq!(restored.active().unwrap().doc.layers.last().unwrap().name, "Second marker");
}
/// A tiny document to distinguish definition edits from document mutations and playback.
fn session() -> Session {
let mut s = Session::new();
@@ -9,6 +35,43 @@ fn session() -> Session {
s
}
#[test]
fn action_count_admission_reserves_the_metadata_carrier_before_publication() {
for metadata in [false, true] {
for operation in ["action", "set", "editor"] {
let mut s = Session::new();
let capacity = photocraft_psd::atn::MAX_TOTAL_ACTIONS - usize::from(metadata);
s.actions.list = (0..capacity - 1).map(|index| Action::new(&format!("Action {index}"), vec![])).collect();
s.actions.list[0].set = Some("Source".into());
if metadata {
s.actions.list[0].description = "Requires the hidden metadata action".into();
}
for admitted in [true, false] {
let (command, params) = match operation {
"action" => ("actions.duplicate", json!({"action":0})),
"set" => ("actions.duplicate", json!({"set":"Source"})),
_ => {
let draft = s.execute("actions.editor.open", json!({"name":format!("New {admitted}")})).unwrap()["draft"].as_u64().unwrap();
s.execute("actions.editor.step", json!({"draft":draft,"op":"insert","step":0,"id":"select.all","params":{}})).unwrap();
("actions.editor.save", json!({"draft":draft}))
}
};
let before = s.actions.clone();
let result = s.execute(command, params.clone());
assert_eq!(result.is_ok(), admitted, "{operation}, metadata={metadata}: {result:?}");
if admitted {
assert_eq!(s.actions.list.len(), capacity);
if operation == "editor" {
s.execute("actions.editor.discard", json!({"draft":params["draft"]})).unwrap();
}
} else {
assert_eq!(s.actions, before, "a full archive retains its list, rows and unpublished draft");
}
}
}
}
}
/// Copies retain metadata and call targets without taking the original function key.
#[test]
fn action_copies_follow_the_source_without_retargeting_calls_or_function_keys() {
+95 -2
View File
@@ -39,6 +39,42 @@ fn open(s: &mut Session, params: Value) -> u64 {
s.execute("actions.editor.open", params).unwrap()["draft"].as_u64().unwrap()
}
#[test]
fn namesake_rename_follows_only_the_first_resolved_occurrence_in_both_editors() {
for modern in [false, true] {
for index in [0, 1] {
let (mut s, _) = session();
s.actions.list.insert(1, s.actions.list[0].clone());
s.actions.list[2].steps.push(("actions.conditional".into(), json!({"if":"always","then":"Original","else":"Other"})));
s.prefs.edit(|prefs| {
prefs.alternate_shortcuts.insert("actions.play:Original".into(), "Shift+F8".into());
});
if modern {
let draft = open(&mut s, json!({"action":index}));
editor(&mut s, "update", draft, json!({"name":"Renamed"})).unwrap();
// A later occurrence may legitimately call the first, including after rename.
if index == 1 {
editor(&mut s, "step", draft, json!({"op":"insert","step":1,"id":"actions.play","params":{"action":"Original"}})).unwrap();
}
editor(&mut s, "save", draft, json!({})).unwrap();
} else {
s.execute("actions.rename", json!({"action":index,"name":"Renamed"})).unwrap();
}
let owner = if index == 0 { "Renamed" } else { "Original" };
let caller = s.actions.list.iter().find(|action| action.name == "Caller").unwrap();
assert_eq!(caller.steps[0].1["action"], owner, "modern={modern}, index={index}");
assert_eq!(caller.steps[1].1["then"], owner);
assert_eq!(caller.steps[1].1["else"], "Other");
let key = format!("actions.play:{owner}");
assert_eq!(s.prefs().shortcuts.get(&key).map(String::as_str), Some("F6"));
assert_eq!(s.prefs().alternate_shortcuts.get(&key).map(String::as_str), Some("Shift+F8"));
let other = if index == 0 { "Original" } else { "Renamed" };
assert!(!s.prefs().shortcuts.contains_key(&format!("actions.play:{other}")));
assert!(!s.prefs().alternate_shortcuts.contains_key(&format!("actions.play:{other}")));
}
}
}
/// Metadata, portable recorded targets and named calls stay out of the stored library.
#[test]
fn edits_and_recording_stay_draft_until_save_or_discard() {
@@ -223,8 +259,9 @@ fn classic_recording_remains_immediate_without_editor_save() {
let len = s.actions.list.len();
s.execute("actions.record", json!({"name":"Classic"})).unwrap();
assert_eq!(s.actions.list.len(), len + 1);
let native: Value = serde_json::from_slice(&store.read(ACTIONS_FILE, MAX_ACTIONS_BYTES).unwrap()).unwrap();
assert_eq!(native["actions"].as_array().unwrap().len(), len + 1);
let mut restored = Session::new();
assert!(restored.attach_preset_store(preset_store::open(Box::new(store.clone()))).is_empty());
assert_eq!(restored.actions.list.len(), len + 1);
assert!(s.execute("actions.editor.open", json!({})).is_err());
s.execute("edit.fill", json!({"color":"#00ff00"})).unwrap();
assert_eq!(photocraft_engine::actions_cmds::pending_steps(&s, len).count(), 1);
@@ -234,6 +271,36 @@ fn classic_recording_remains_immediate_without_editor_save() {
assert_eq!(s.actions.list[len].steps[0].1["color"], "#00ff00");
}
#[test]
fn rename_and_new_steps_cannot_introduce_play_or_conditional_self_calls() {
for (command, params) in [
("actions.play", json!({"action":"Future"})),
("actions.conditional", json!({"if":"always","then":"Future"})),
("actions.conditional", json!({"if":"always","then":"Other","else":"Future"})),
] {
let (mut s, _) = session();
let draft = open(&mut s, json!({"name":"Before"}));
editor(&mut s, "step", draft, json!({"op":"insert","step":0,"id":command,"params":params})).unwrap();
let before = editor(&mut s, "get", draft, json!({})).unwrap();
assert!(editor(&mut s, "update", draft, json!({"name":"Future"})).is_err());
assert_eq!(editor(&mut s, "get", draft, json!({})).unwrap(), before);
editor(&mut s, "update", draft, json!({"name":"Allowed"})).unwrap();
editor(&mut s, "discard", draft, json!({})).unwrap();
let draft = open(&mut s, json!({"action":"Original"}));
editor(&mut s, "update", draft, json!({"name":"Renamed"})).unwrap();
let mut params = params.clone();
for key in ["action", "then", "else"] {
if params.get(key).is_some_and(|v| v == "Future") {
params[key] = json!("Original");
}
}
assert!(
editor(&mut s, "step", draft, json!({"op":"insert","step":0,"id":command,"params":params})).is_err(),
"the opening source name will become Renamed at Save"
);
}
}
/// Failed Save keeps an active take; successful Save consumes its pending steps only once.
#[test]
fn save_finishes_its_own_capture_only_after_complete_validation() {
@@ -259,6 +326,32 @@ fn save_finishes_its_own_capture_only_after_complete_validation() {
assert_eq!(s.journal, journal);
}
/// A late job from a discarded take is journaled, but never enters the next draft capture.
#[test]
fn save_waits_for_a_real_recorded_job_before_publishing() {
let (mut s, store) = session();
let draft = open(&mut s, json!({"name":"Worker capture"}));
editor(&mut s, "record", draft, json!({})).unwrap();
let job = match s.start("filter.blur.gaussianBlur", json!({"radius":1})).unwrap() {
Started::Job(id) => id,
_ => panic!("blur must use its real job path"),
};
assert!(s.has_recording_job());
let state = s.actions.clone();
let bytes = store.read(ACTIONS_FILE, MAX_ACTIONS_BYTES).unwrap();
assert!(editor(&mut s, "save", draft, json!({})).is_err());
assert_eq!(s.actions, state, "refusal retains the capture and unpublished draft");
assert_eq!(store.read(ACTIONS_FILE, MAX_ACTIONS_BYTES).unwrap(), bytes);
s.wait_job(job).unwrap();
assert!(!s.has_recording_job());
let saved = editor(&mut s, "save", draft, json!({})).unwrap();
assert_eq!(saved["recording"], false);
assert_eq!(s.actions.list.last().unwrap().steps[0].0, "filter.blur.gaussianBlur");
let mut restored = Session::new();
assert!(restored.attach_preset_store(preset_store::open(Box::new(store))).is_empty());
assert_eq!(restored.actions.list.last().unwrap().steps, s.actions.list.last().unwrap().steps);
}
/// A late job from a discarded take is journaled, but never enters the next draft capture.
#[test]
fn late_job_cannot_enter_a_discarded_or_later_draft() {
@@ -5,6 +5,43 @@ use photocraft_engine::{
};
use serde_json::{Value, json};
#[test]
fn deleting_a_namesake_keeps_named_calls_and_keys_until_the_last_target_is_gone() {
for group in [false, true] {
let mut s = Session::new();
s.actions.list = vec![
grouped("Duplicate", "First"), grouped("Duplicate", "Second"),
Action::new("Caller", vec![
("actions.play".into(), json!({"action":"Duplicate"})),
("actions.play".into(), json!({"action":0})),
("actions.play".into(), json!({"action":1})),
("actions.conditional".into(), json!({"if":"always","then":"Duplicate","else":0})),
]),
];
s.prefs.edit(|prefs| {
prefs.shortcuts.insert("actions.play:Duplicate".into(), "F5".into());
prefs.alternate_shortcuts.insert("actions.play:Duplicate".into(), vec!["F6".into()]);
});
s.execute("actions.delete", if group {json!({"set":"First"})} else {json!({"action":0})}).unwrap();
assert_eq!(s.actions.list[0].name, "Duplicate");
let calls = &s.actions.list[1].steps;
assert_eq!(calls[0].1["action"], "Duplicate");
assert!(calls[1].1["action"].is_null());
assert_eq!(calls[2].1["action"], 0);
assert_eq!(calls[3].1["then"], "Duplicate");
assert!(calls[3].1["else"].is_null());
assert_eq!(s.prefs().shortcuts["actions.play:Duplicate"], "F5");
assert_eq!(s.prefs().alternate_shortcuts["actions.play:Duplicate"], ["F6"]);
s.execute("actions.delete", json!({"action":0})).unwrap();
for (id, params) in &s.actions.list[0].steps {
if id == "actions.play" { assert!(params["action"].is_null()); }
else { assert!(params["then"].is_null()); }
}
assert!(!s.prefs().shortcuts.contains_key("actions.play:Duplicate"));
assert!(!s.prefs().alternate_shortcuts.contains_key("actions.play:Duplicate"));
}
}
fn grouped(name: &str, set: &str) -> Action {
Action { set: Some(set.into()), ..Action::new(name, Vec::new()) }
}