mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
Preserve legacy shortcuts and unresolved calls on store failure
This commit is contained in:
1 parent
beb42e396b
commit
cc19b9899b
10 files changed
+287
-131
No files matched your search
@@ -29,7 +29,7 @@ pub(crate) use history::ActionHistory;
|
||||
pub use history::{ActionHistoryContinuation, finish_pending_history, suspend_history};
|
||||
pub(crate) use history::{before_edit as before_action_edit, begin_document_history, finish_document_history, history_rows, reconcile_history_removal};
|
||||
pub use identity::{action_shortcut, commit_action_id, is_action_key, occurrence_key, playback_row, prepare_action_id, shortcut_row};
|
||||
pub(crate) use identity::{invalidate_duplicate_ids, pin_shortcut, remove_shortcuts, resolve_action_id, valid_action_id};
|
||||
pub(crate) use identity::{has_legacy_shortcut, invalidate_duplicate_ids, remove_shortcuts, resolve_action_id, valid_action_id};
|
||||
|
||||
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
|
||||
@@ -43,6 +43,9 @@ pub struct Action {
|
||||
/// Stable identity for occurrence shortcuts and stored calls. Legacy rows have no ID.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub action_id: Option<String>,
|
||||
/// Resolves a legacy shortcut to its original row even after a same-name row comes first.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub legacy_shortcut_owner: bool,
|
||||
#[serde(default)]
|
||||
pub steps: Vec<(String, Value)>,
|
||||
/// Indices of steps excluded from playback (unchecked in the Actions panel).
|
||||
@@ -70,7 +73,17 @@ pub const BUTTON_COLORS: [&str; 8] = ["", "red", "orange", "yellow", "green", "b
|
||||
|
||||
impl Action {
|
||||
pub fn new(name: impl Into<String>, steps: Vec<(String, Value)>) -> Self {
|
||||
Self { name: name.into(), action_id: None, steps, disabled: BTreeSet::new(), dialogs: BTreeSet::new(), set: None, set_slot: None, color: String::new() }
|
||||
Self {
|
||||
name: name.into(),
|
||||
action_id: None,
|
||||
legacy_shortcut_owner: false,
|
||||
steps,
|
||||
disabled: BTreeSet::new(),
|
||||
dialogs: BTreeSet::new(),
|
||||
set: None,
|
||||
set_slot: None,
|
||||
color: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply `f` to every per-step index set (`disabled`, `dialogs`) after steps moved.
|
||||
@@ -460,8 +473,12 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec<Act
|
||||
}
|
||||
_ => params["action"] = json!(name),
|
||||
}
|
||||
if let Some(object) = params.as_object_mut() {
|
||||
object.remove("actionId");
|
||||
if let Some(object) = params.as_object_mut()
|
||||
&& object.remove("actionId").is_some()
|
||||
&& id == "file.automate.batch"
|
||||
{
|
||||
// The source ID superseded this legacy qualifier.
|
||||
object.remove("set");
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -926,15 +943,10 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = &s.actions.list[idx].name;
|
||||
let first = s.actions.list.iter().position(|action| &action.name == name).unwrap_or(idx);
|
||||
let changes_owner = if first == idx { to > idx && s.actions.list[idx + 1..=to].iter().any(|action| &action.name == name) } else { to <= first };
|
||||
if changes_owner {
|
||||
let mut shortcuts = s.prefs().shortcuts.clone();
|
||||
let mut alternates = s.prefs().alternate_shortcuts.clone();
|
||||
pin_shortcut(&mut s.actions.list, first, &mut shortcuts, &mut alternates)?;
|
||||
if shortcuts != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts {
|
||||
s.edit_prefs(|prefs| {
|
||||
prefs.shortcuts = shortcuts;
|
||||
prefs.alternate_shortcuts = alternates;
|
||||
});
|
||||
if changes_owner && has_legacy_shortcut(s, name) {
|
||||
let key = format!("{PLAY_SHORTCUT_PREFIX}{name}");
|
||||
if let Some(owner) = shortcut_row(&s.actions.list, &key) {
|
||||
s.actions.list[owner].legacy_shortcut_owner = true;
|
||||
}
|
||||
}
|
||||
let moved = s.actions.list.remove(idx);
|
||||
@@ -1064,18 +1076,23 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A loaded library can hold two actions of one name (in different sets): a call follows the
|
||||
// rename only if it resolved to this action before it, so one reaching the other stays put.
|
||||
let before = s.actions.list.clone();
|
||||
let by_name = resolve(&before, &json!({"action": old}), "actions.rename").ok() == Some(idx);
|
||||
let owned_shortcut = shortcut_row(&before, &format!("{PLAY_SHORTCUT_PREFIX}{old}")) == Some(idx);
|
||||
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 {
|
||||
let keys: &[&str] = match id.as_str() {
|
||||
"actions.play" if by_name => &["action"],
|
||||
"actions.conditional" if by_name => &["then", "else"],
|
||||
"actions.play" if resolve_play_target(&before, params, id).ok() == Some(idx) => &["action"],
|
||||
"actions.conditional" => &["then", "else"],
|
||||
// A named Batch selects from the caller's list, by name alone or within its set;
|
||||
// explicit `steps` run instead of any named action, so those are left alone.
|
||||
"file.automate.batch" if params.get("steps").is_none() && crate::file_cmds::batch_action(&before, params).ok() == Some(idx) => &["action"],
|
||||
_ => &[],
|
||||
};
|
||||
for key in keys {
|
||||
if id == "actions.conditional"
|
||||
&& conditional_branch(params, key).ok().flatten().and_then(|target| resolve_play_target(&before, &target, id).ok()) != Some(idx)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if params.get(*key).and_then(Value::as_str) == Some(old.as_str()) {
|
||||
params[*key] = json!(name);
|
||||
}
|
||||
@@ -1086,7 +1103,7 @@ 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 by_name && (s.prefs().shortcuts.contains_key(&from) || s.prefs().alternate_shortcuts.contains_key(&from)) {
|
||||
if owned_shortcut && (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.clone(), key);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Persisted action occurrences are independent of name, list order, and folder position.
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::{Action, PLAY_SHORTCUT_PREFIX, bad};
|
||||
use crate::{Result, Session};
|
||||
@@ -57,6 +57,10 @@ pub fn shortcut_row(list: &[Action], key: &str) -> Option<usize> {
|
||||
return resolve_action_id(list, id);
|
||||
}
|
||||
let name = key.strip_prefix(PLAY_SHORTCUT_PREFIX)?;
|
||||
let mut pinned = list.iter().enumerate().filter(|(_, action)| action.name == name && action.legacy_shortcut_owner);
|
||||
if let Some((index, _)) = pinned.next() {
|
||||
return pinned.next().is_none().then_some(index);
|
||||
}
|
||||
list.iter().position(|action| action.name == name)
|
||||
}
|
||||
|
||||
@@ -75,13 +79,21 @@ pub fn prepare_action_id(list: &[Action], index: usize) -> Result<String> {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Complete a successful shortcut edit. The shortcut command only edits preferences.
|
||||
pub fn commit_action_id(s: &mut Session, index: usize, id: String) {
|
||||
if s.actions.list[index].action_id.is_none() {
|
||||
s.actions.list[index].action_id = Some(id);
|
||||
s.actions.touch();
|
||||
s.sync_preset_store();
|
||||
/// Save a new identity before the shortcut edit can reach the separate preferences file.
|
||||
pub fn commit_action_id(s: &mut Session, index: usize, id: String) -> Result<()> {
|
||||
if s.actions.list[index].action_id.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
s.actions.list[index].action_id = Some(id);
|
||||
let rev = s.actions.rev.saturating_add(1);
|
||||
if let Some(store) = s.preset_store.as_mut()
|
||||
&& let Err(error) = store.commit_action_definitions(&s.actions, rev)
|
||||
{
|
||||
s.actions.list[index].action_id = None;
|
||||
return Err(bad(COMMAND, error));
|
||||
}
|
||||
s.actions.touch();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A valid explicit key takes precedence over a legacy key for the same row.
|
||||
@@ -98,27 +110,9 @@ pub fn action_shortcut(s: &Session, index: usize) -> Option<&str> {
|
||||
(shortcut_row(list, &legacy) == Some(index)).then(|| keys.get(&legacy)).flatten().map(String::as_str)
|
||||
}
|
||||
|
||||
/// Move a legacy binding to its already resolved row before an edit changes name lookup.
|
||||
pub(crate) fn pin_shortcut(
|
||||
list: &mut [Action],
|
||||
index: usize,
|
||||
shortcuts: &mut BTreeMap<String, String>,
|
||||
alternates: &mut BTreeMap<String, Vec<String>>,
|
||||
) -> Result<()> {
|
||||
let legacy = format!("{PLAY_SHORTCUT_PREFIX}{}", list[index].name);
|
||||
if shortcut_row(list, &legacy) != Some(index) || !(shortcuts.contains_key(&legacy) || alternates.contains_key(&legacy)) {
|
||||
return Ok(());
|
||||
}
|
||||
let id = prepare_action_id(list, index)?;
|
||||
let key = occurrence_key(&id);
|
||||
list[index].action_id = Some(id);
|
||||
if let Some(binding) = shortcuts.remove(&legacy) {
|
||||
shortcuts.entry(key.clone()).or_insert(binding);
|
||||
}
|
||||
if let Some(bindings) = alternates.remove(&legacy) {
|
||||
alternates.entry(key).or_insert(bindings);
|
||||
}
|
||||
Ok(())
|
||||
pub(crate) fn has_legacy_shortcut(s: &Session, name: &str) -> bool {
|
||||
let key = format!("{PLAY_SHORTCUT_PREFIX}{name}");
|
||||
s.prefs().shortcuts.contains_key(&key) || s.prefs().alternate_shortcuts.contains_key(&key)
|
||||
}
|
||||
|
||||
/// Remove only the bindings owned by the deleted rows, before the indices or first match change.
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::io::{self, Write};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::actions_cmds::{Action, is_action_key, not_playing, pin_shortcut};
|
||||
use crate::actions_cmds::{Action, PLAY_SHORTCUT_PREFIX, has_legacy_shortcut, is_action_key, not_playing, shortcut_row};
|
||||
use crate::{Result, Session};
|
||||
|
||||
use super::bad;
|
||||
@@ -104,13 +104,16 @@ pub(crate) fn publish_library(
|
||||
let (after_shortcuts, after_alternates) = match new_shortcuts {
|
||||
Some(keys) => (keys, Alternates::new()),
|
||||
None => {
|
||||
let (mut keys, mut alternate_keys) = (shortcuts.clone(), alternates.clone());
|
||||
let count = s.actions.list.len();
|
||||
let owners: Vec<_> = list[count..].iter().filter_map(|action| list[..count].iter().position(|prior| prior.name == action.name)).collect();
|
||||
let owners: Vec<_> = list[count..]
|
||||
.iter()
|
||||
.filter(|action| has_legacy_shortcut(s, &action.name))
|
||||
.filter_map(|action| shortcut_row(&list[..count], &format!("{PLAY_SHORTCUT_PREFIX}{}", action.name)))
|
||||
.collect();
|
||||
for owner in owners {
|
||||
pin_shortcut(&mut list, owner, &mut keys, &mut alternate_keys)?;
|
||||
list[owner].legacy_shortcut_owner = true;
|
||||
}
|
||||
(keys, alternate_keys)
|
||||
(shortcuts.clone(), alternates.clone())
|
||||
}
|
||||
};
|
||||
check_library_size(&list, &sets, &rows, cmd)?;
|
||||
|
||||
@@ -141,19 +141,16 @@ fn repeated_reset_pins_existing_shortcuts_and_undo_restores_legacy_keys() {
|
||||
assert_eq!(s.prefs().alternate_shortcuts, prefs.alternate_shortcuts);
|
||||
|
||||
s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap();
|
||||
let key = crate::actions_cmds::occurrence_key(s.actions.list[0].action_id.as_deref().unwrap());
|
||||
assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &key), Some(0));
|
||||
assert_eq!(s.prefs().shortcuts[&key], "F2");
|
||||
assert_eq!(s.prefs().alternate_shortcuts[&key], ["F3"]);
|
||||
assert!(!s.prefs().shortcuts.contains_key(&shortcut));
|
||||
assert!(!s.prefs().alternate_shortcuts.contains_key(&shortcut));
|
||||
assert!(s.actions.list[0].legacy_shortcut_owner);
|
||||
assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &shortcut), Some(0));
|
||||
assert_eq!(s.prefs().shortcuts[&shortcut], "F2");
|
||||
assert_eq!(s.prefs().alternate_shortcuts[&shortcut], ["F3"]);
|
||||
assert_eq!(s.actions.list.iter().filter(|action| action.name == "Invert Colors").count(), 2);
|
||||
|
||||
s.execute("actions.undoLibrary", json!({})).unwrap();
|
||||
assert_eq!(s.actions.list, before);
|
||||
assert_eq!(s.prefs().shortcuts[&shortcut], "F2");
|
||||
assert_eq!(s.prefs().alternate_shortcuts[&shortcut], ["F3"]);
|
||||
assert!(!s.prefs().shortcuts.contains_key(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -184,7 +181,7 @@ fn atn_export_and_load_keep_function_keys_of_duplicate_rows_separate() {
|
||||
for (row, key) in [(0, "F2"), (2, "F3")] {
|
||||
let id = crate::actions_cmds::prepare_action_id(&s.actions.list, row).unwrap();
|
||||
s.edit_prefs(|prefs| prefs.shortcuts.insert(crate::actions_cmds::occurrence_key(&id), key.into()));
|
||||
crate::actions_cmds::commit_action_id(&mut s, row, id);
|
||||
crate::actions_cmds::commit_action_id(&mut s, row, id).unwrap();
|
||||
}
|
||||
let archive = s.execute("actions.save", json!({"set":"PhotoCraft Basics","skipUnsupported":true})).unwrap();
|
||||
let mut loaded = Session::new();
|
||||
@@ -220,6 +217,36 @@ fn attachment_keeps_disk_batch_targets_and_does_not_resolve_foreign_ids() {
|
||||
assert_eq!(crate::actions_cmds::resolve(list, &json!({"action":"Target"}), "actions.play").unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attachment_keeps_unresolved_disk_calls_from_binding_to_early_actions() {
|
||||
use crate::actions_cmds::{conditional_branch, resolve_play_target};
|
||||
use crate::preset_store::{ACTIONS_FILE, PresetBackend};
|
||||
|
||||
let store = MemBackend::default();
|
||||
let file = json!({"version":1,"actions":[{"name":"Disk caller","steps":[
|
||||
["actions.play",{"action":"Early"}],
|
||||
["actions.conditional",{"if":"always","then":"Early"}],
|
||||
["file.automate.batch",{"action":"Early","set":"Session"}],
|
||||
["actions.play",{"action":1}]
|
||||
]}]});
|
||||
store.write(ACTIONS_FILE, file.to_string().as_bytes()).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.actions.list.push(Action { set: Some("Session".into()), ..Action::new("Early", Vec::new()) });
|
||||
assert!(s.attach_preset_store(open(Box::new(store.clone()))).is_empty());
|
||||
s.sync_preset_store();
|
||||
|
||||
let mut s = Session::new();
|
||||
assert!(s.attach_preset_store(open(Box::new(store))).is_empty());
|
||||
let list = &s.actions.list;
|
||||
let steps = &list[1].steps;
|
||||
assert!(resolve_play_target(list, &steps[0].1, "actions.play").is_err());
|
||||
let branch = conditional_branch(&steps[1].1, "then").unwrap().unwrap();
|
||||
assert!(resolve_play_target(list, &branch, "actions.conditional").is_err());
|
||||
assert!(crate::file_cmds::batch_action(list, &steps[2].1).is_err());
|
||||
assert!(resolve_play_target(list, &steps[3].1, "actions.play").is_err());
|
||||
assert_eq!(s.execute("actions.play", json!({"action":"Early"})).unwrap()["action"], "Early");
|
||||
}
|
||||
|
||||
/// Imported calls follow a local physical folder before falling back to the first archive name.
|
||||
#[test]
|
||||
fn whole_replace_resolves_unqualified_calls_in_their_own_occurrence() {
|
||||
|
||||
@@ -1108,30 +1108,38 @@ impl PresetStore {
|
||||
if self.actions_rev == rev {
|
||||
return;
|
||||
}
|
||||
if self.actions_skipped {
|
||||
self.warnings.push(format!("Couldn't save actions: {ACTIONS_FILE} could not be read, so it was left unchanged"));
|
||||
self.actions_rev = rev;
|
||||
return;
|
||||
}
|
||||
let file = crate::actions_cmds::ActionsFile { version: 1, actions: state.list.clone(), sets: state.sets.clone(), set_rows: state.set_rows.clone() };
|
||||
let bytes = match serde_json::to_vec_pretty(&file) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
self.warnings.push(format!("Couldn't save actions: {e}"));
|
||||
let bytes = match self.action_bytes(state) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
self.warnings.push(error);
|
||||
self.actions_rev = rev;
|
||||
return;
|
||||
}
|
||||
};
|
||||
if bytes.len() as u64 > MAX_ACTIONS_BYTES {
|
||||
self.warnings.push(format!("actions: the action list is too large to save ({} MB limit)", MAX_ACTIONS_BYTES >> 20));
|
||||
self.actions_rev = rev;
|
||||
return;
|
||||
}
|
||||
match self.backend.write(ACTIONS_FILE, &bytes) {
|
||||
Ok(()) => self.actions_rev = rev,
|
||||
Err(e) => self.warnings.push(format!("Couldn't save actions: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn commit_action_definitions(&mut self, state: &crate::actions_cmds::ActionState, rev: u64) -> Result<(), String> {
|
||||
let bytes = self.action_bytes(state)?;
|
||||
self.backend.write(ACTIONS_FILE, &bytes).map_err(|error| format!("Couldn't save actions: {error}"))?;
|
||||
self.actions_rev = rev;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn action_bytes(&self, state: &crate::actions_cmds::ActionState) -> Result<Vec<u8>, String> {
|
||||
if self.actions_skipped {
|
||||
return Err(format!("Couldn't save actions: {ACTIONS_FILE} could not be read, so it was left unchanged"));
|
||||
}
|
||||
let file = crate::actions_cmds::ActionsFile { version: 1, actions: state.list.clone(), sets: state.sets.clone(), set_rows: state.set_rows.clone() };
|
||||
let bytes = serde_json::to_vec_pretty(&file).map_err(|error| format!("Couldn't save actions: {error}"))?;
|
||||
if bytes.len() as u64 > MAX_ACTIONS_BYTES {
|
||||
return Err(format!("actions: the action list is too large to save ({} MB limit)", MAX_ACTIONS_BYTES >> 20));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
fn builtin_names() -> &'static [String] {
|
||||
@@ -1210,7 +1218,11 @@ impl Session {
|
||||
}
|
||||
}
|
||||
for mut action in disk {
|
||||
if action.set_slot.is_some() || action.action_id.is_some() || !self.actions.list.iter().any(|have| have.name == action.name) {
|
||||
if action.set_slot.is_some()
|
||||
|| action.action_id.is_some()
|
||||
|| action.legacy_shortcut_owner
|
||||
|| !self.actions.list.iter().any(|have| have.name == action.name)
|
||||
{
|
||||
action.set_slot = action.set_slot.and_then(|slot| slot.checked_add(offset));
|
||||
self.actions.list.push(action);
|
||||
}
|
||||
|
||||
@@ -5,8 +5,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::actions_cmds::{
|
||||
Action, PLAY_SHORTCUT_PREFIX, branch_id_field, conditional_branch, pin_shortcut, prepare_action_id, resolve_play_target, shortcut_row, valid_action_id,
|
||||
visit_calls,
|
||||
Action, PLAY_SHORTCUT_PREFIX, branch_id_field, conditional_branch, prepare_action_id, resolve_play_target, shortcut_row, valid_action_id, visit_calls,
|
||||
};
|
||||
|
||||
/// Explicit IDs that failed in their source list must also fail after the lists are joined.
|
||||
@@ -38,23 +37,16 @@ pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: &
|
||||
block_unknown_ids(disk);
|
||||
let memory = &s.actions.list;
|
||||
|
||||
// A legacy shortcut read with the saved preferences belongs to the first disk match.
|
||||
// The current Action Options path already gives a newly assigned in-memory binding an ID.
|
||||
let (mut keys, mut alternates) = (s.prefs().shortcuts.clone(), s.prefs().alternate_shortcuts.clone());
|
||||
let owners: Vec<_> = keys
|
||||
.keys()
|
||||
.chain(alternates.keys())
|
||||
.filter_map(|key| {
|
||||
let name = key.strip_prefix(PLAY_SHORTCUT_PREFIX)?;
|
||||
memory.iter().any(|action| action.name == name).then(|| shortcut_row(disk, key)).flatten().map(|row| (key.clone(), row))
|
||||
})
|
||||
.collect();
|
||||
for (key, row) in owners {
|
||||
if let Err(error) = pin_shortcut(disk, row, &mut keys, &mut alternates) {
|
||||
// The original target cannot be identified. The legacy key must not play a memory row.
|
||||
keys.remove(&key);
|
||||
alternates.remove(&key);
|
||||
warnings.push(format!("actions: {error}"));
|
||||
// Saved preferences predate the asynchronous attachment. Keep their legacy key, and
|
||||
// persist the disk owner with the library so a failed store write cannot orphan the key.
|
||||
let keys = s.prefs().shortcuts.keys().chain(s.prefs().alternate_shortcuts.keys());
|
||||
for key in keys {
|
||||
let Some(name) = key.strip_prefix(PLAY_SHORTCUT_PREFIX) else { continue };
|
||||
if memory.iter().any(|action| action.name == name)
|
||||
&& !memory.iter().any(|action| action.name == name && action.legacy_shortcut_owner)
|
||||
&& let Some(row) = shortcut_row(disk, key)
|
||||
{
|
||||
disk[row].legacy_shortcut_owner = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,10 +57,10 @@ pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: &
|
||||
let resolve = |list: &[Action]| {
|
||||
if command == "actions.play" { resolve_play_target(list, params, command) } else { crate::file_cmds::batch_action(list, params) }
|
||||
};
|
||||
if (params.get("action").is_some_and(Value::is_number) || resolve(memory).is_ok())
|
||||
&& let Ok(target) = resolve(disk)
|
||||
{
|
||||
params["actionId"] = pin_target(disk, target, warnings);
|
||||
if params.get("action").is_some_and(Value::is_number) || resolve(memory).is_ok() {
|
||||
let original = resolve(disk);
|
||||
// A name or index that failed on disk must not acquire a target from the merge.
|
||||
params["actionId"] = original.map_or(Value::Null, |row| pin_target(disk, row, warnings));
|
||||
}
|
||||
}
|
||||
"actions.conditional" => {
|
||||
@@ -79,9 +71,9 @@ pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: &
|
||||
}
|
||||
if let Ok(Some(target)) = conditional_branch(params, branch)
|
||||
&& resolve_play_target(memory, &target, command).is_ok()
|
||||
&& let Ok(target) = resolve_play_target(disk, &target, command)
|
||||
{
|
||||
params[field] = pin_target(disk, target, warnings);
|
||||
let original = resolve_play_target(disk, &target, command);
|
||||
params[field] = original.map_or(Value::Null, |row| pin_target(disk, row, warnings));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,12 +81,6 @@ pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: &
|
||||
});
|
||||
disk[row].steps = steps;
|
||||
}
|
||||
if keys != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts {
|
||||
s.edit_prefs(|prefs| {
|
||||
prefs.shortcuts = keys;
|
||||
prefs.alternate_shortcuts = alternates;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn pin_target(list: &mut [Action], index: usize, warnings: &mut Vec<String>) -> Value {
|
||||
|
||||
@@ -49,8 +49,19 @@ pub fn take_log(ctx: &egui::Context) -> Vec<(String, Outcome)> {
|
||||
/// their overrides apply. Held temporary tools (Space…) are not here: see [`crate::hold_keys`].
|
||||
pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> {
|
||||
let prefs = app.session.prefs();
|
||||
let action_row = |key: &str| actions_cmds::shortcut_row(&app.session.actions.list, key);
|
||||
let actions = prefs.shortcuts.keys().filter(|id| action_row(id.as_str()).is_some()).map(|id| (id.as_str(), prefs.shortcut(id, None).map(str::to_string)));
|
||||
let action_key = |key: &str, alternate| {
|
||||
let Some(row) = action_shortcut_row(app, key) else { return false };
|
||||
if !key.starts_with(actions_cmds::PLAY_SHORTCUT_PREFIX) {
|
||||
return true;
|
||||
}
|
||||
let list = &app.session.actions.list;
|
||||
let explicit = list[row].action_id.as_deref().map(actions_cmds::occurrence_key);
|
||||
!explicit.is_some_and(|id| {
|
||||
actions_cmds::shortcut_row(list, &id) == Some(row)
|
||||
&& if alternate { prefs.alternate_shortcuts.contains_key(&id) } else { prefs.shortcuts.contains_key(&id) }
|
||||
})
|
||||
};
|
||||
let actions = prefs.shortcuts.keys().filter(|id| action_key(id.as_str(), false)).map(|id| (id.as_str(), prefs.shortcut(id, None).map(str::to_string)));
|
||||
// The Keyboard Shortcuts dialog lists Photoshop's Window › <panel> item (`window.panel.*`)
|
||||
// in place of the shell command it runs (`window.toggle.*`, see `menus::panel_alias`), so an
|
||||
// edit to that row reassigns or removes the shell command's default too (#1272).
|
||||
@@ -99,7 +110,7 @@ pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> {
|
||||
let alternate_ids: std::collections::BTreeSet<&str> =
|
||||
photocraft_engine::prefs::ALTERNATE_SHORTCUTS.iter().map(|(id, _)| *id).chain(prefs.alternate_shortcuts.keys().map(String::as_str)).collect();
|
||||
for id in alternate_ids {
|
||||
if actions_cmds::is_action_key(id) && action_row(id).is_none() {
|
||||
if actions_cmds::is_action_key(id) && !action_key(id, true) {
|
||||
continue;
|
||||
}
|
||||
let main = prefs.shortcut(id, crate::shortcuts::default_shortcut(id).as_deref()).map(str::to_string);
|
||||
@@ -375,10 +386,17 @@ pub fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) {
|
||||
dispatch_as(app, ctx, id, false);
|
||||
}
|
||||
|
||||
fn action_shortcut_row(app: &PhotocraftApp, key: &str) -> Option<usize> {
|
||||
if key.starts_with(actions_cmds::PLAY_SHORTCUT_PREFIX) && app.services.preset_store.is_some() && app.session.preset_store.is_none() {
|
||||
return None;
|
||||
}
|
||||
actions_cmds::shortcut_row(&app.session.actions.list, key)
|
||||
}
|
||||
|
||||
/// [`dispatch`]; with `last`, an adjustment dialog opens at its last confirmed settings.
|
||||
fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: bool) {
|
||||
let is_action = actions_cmds::is_action_key(id);
|
||||
let action = actions_cmds::shortcut_row(&app.session.actions.list, id).map(|row| &app.session.actions.list[row]);
|
||||
let action = action_shortcut_row(app, id);
|
||||
let command_id = if is_action { "actions.play" } else { id };
|
||||
let missing = is_action && action.is_none();
|
||||
let outcome = if missing || !crate::menus::is_enabled(app, command_id) {
|
||||
@@ -390,10 +408,12 @@ fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: boo
|
||||
} else if ctx.data(|d| d.get_temp::<bool>(dry_run_id())).unwrap_or(false) {
|
||||
Outcome::Ran
|
||||
} else {
|
||||
let r = if let Some(action) = action {
|
||||
let r = if let Some(row) = action {
|
||||
let list = &app.session.actions.list;
|
||||
let target = match id.strip_prefix(actions_cmds::PLAY_SHORTCUT_PREFIX) {
|
||||
Some(name) => json!({"action": name}),
|
||||
None => json!({"actionId": action.action_id}),
|
||||
Some(name) if list.iter().position(|action| action.name == name) == Some(row) => json!({"action": name}),
|
||||
Some(_) => json!({"action": row}),
|
||||
None => json!({"actionId": list[row].action_id}),
|
||||
};
|
||||
// Synthetic input and every nested action still pass the automation authorizer.
|
||||
crate::menus::invoke(app, ctx, "actions.play", target).and_then(|v| {
|
||||
|
||||
@@ -814,10 +814,15 @@ fn f3_dispatches_only_the_second_same_named_action_after_reorder_and_reopen() {
|
||||
let mut h = harness();
|
||||
let store = MemBackend::default();
|
||||
h.state_mut().session.attach_preset_store(open(Box::new(store.clone())));
|
||||
h.state_mut().session.actions.set_rows.push("Before".into());
|
||||
repeated_reset_shortcuts(&mut h);
|
||||
let first_key = action_key(&h, 0);
|
||||
let second_key = action_key(&h, 2);
|
||||
h.state_mut().run("actions.move", json!({"action":2,"to":0})).unwrap();
|
||||
let (empty, _) = photocraft_engine::atn_cmds::export("Before", &[], &[], false).unwrap();
|
||||
let data = photocraft_paint::tile::b64_encode(&empty);
|
||||
h.state_mut().run("actions.load", json!({"data":data})).unwrap();
|
||||
assert_eq!(h.state().session.actions.list[0].set_slot, Some(1));
|
||||
h.state_mut().session.sync_preset_store();
|
||||
let prefs = h.state().session.prefs_to_json();
|
||||
|
||||
@@ -852,9 +857,10 @@ fn attachment_preserves_disk_keys_and_calls_without_changing_name_lookup() {
|
||||
h.state_mut().session.load_prefs_json(r#"{"shortcuts":{"actions.play:Target":"F2"},"alternateShortcuts":{"actions.play:Target":["F3"]}}"#).unwrap();
|
||||
h.state_mut().session.actions.list.push(actions_cmds::Action::new("Target", vec![("layer.new.layer".into(), json!({"name":"memory target"}))]));
|
||||
assert!(h.state_mut().session.attach_preset_store(open(Box::new(store.clone()))).is_empty());
|
||||
let disk_key = action_key(&h, 1);
|
||||
assert_eq!(h.state().session.prefs().shortcuts[&disk_key], "F2");
|
||||
assert_eq!(h.state().session.prefs().alternate_shortcuts[&disk_key], ["F3"]);
|
||||
let disk_key = "actions.play:Target";
|
||||
assert!(h.state().session.actions.list[1].legacy_shortcut_owner);
|
||||
assert_eq!(h.state().session.prefs().shortcuts[disk_key], "F2");
|
||||
assert_eq!(h.state().session.prefs().alternate_shortcuts[disk_key], ["F3"]);
|
||||
|
||||
h.state_mut().run("actions.play", json!({"action":"Target"})).unwrap();
|
||||
assert_eq!(active_name(&h), "memory target");
|
||||
@@ -876,6 +882,70 @@ fn attachment_preserves_disk_keys_and_calls_without_changing_name_lookup() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_occurrence_key_shadows_legacy_primary_until_the_identity_is_missing() {
|
||||
let mut h = harness();
|
||||
h.state_mut().session.actions.list.push(actions_cmds::Action::new("Target", Vec::new()));
|
||||
h.state_mut().session.edit_prefs(|p| {
|
||||
p.shortcuts.insert("actions.play:Target".into(), "F2".into());
|
||||
});
|
||||
crate::actions::assign_shortcut(h.state_mut(), 0, "F4").unwrap();
|
||||
let key = action_key(&h, 0);
|
||||
assert!(bindings(h.state()).iter().any(|(id, _)| id == &key));
|
||||
assert!(!bindings(h.state()).iter().any(|(id, _)| id == "actions.play:Target"));
|
||||
// An async backend may have saved the preferences but still have the old Actions file.
|
||||
h.state_mut().session.actions.list[0].action_id = None;
|
||||
assert!(!bindings(h.state()).iter().any(|(id, _)| id == &key));
|
||||
assert!(bindings(h.state()).iter().any(|(id, _)| id == "actions.play:Target"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_action_id_write_keeps_the_legacy_shortcut_after_reopen() {
|
||||
use photocraft_engine::preset_store::{ACTIONS_FILE, MemBackend, PresetBackend, open};
|
||||
|
||||
struct RejectActionsWrite(MemBackend);
|
||||
impl PresetBackend for RejectActionsWrite {
|
||||
fn list(&self) -> Result<Vec<(String, u64)>, String> {
|
||||
self.0.list()
|
||||
}
|
||||
fn read(&self, name: &str, max: u64) -> Result<Vec<u8>, String> {
|
||||
self.0.read(name, max)
|
||||
}
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
if name == ACTIONS_FILE {
|
||||
return Err("injected Actions write failure".into());
|
||||
}
|
||||
self.0.write(name, bytes)
|
||||
}
|
||||
fn remove(&self, name: &str) -> Result<(), String> {
|
||||
self.0.remove(name)
|
||||
}
|
||||
}
|
||||
|
||||
let store = MemBackend::default();
|
||||
let file = json!({"version":1,"actions":[{"name":"Target","steps":[["layer.new.layer",{"name":"legacy target"}]]}]});
|
||||
let original = file.to_string().into_bytes();
|
||||
store.write(ACTIONS_FILE, &original).unwrap();
|
||||
|
||||
let mut h = harness();
|
||||
h.state_mut().session.load_prefs_json(r#"{"shortcuts":{"actions.play:Target":"F2"},"alternateShortcuts":{"actions.play:Target":["F3"]}}"#).unwrap();
|
||||
h.state_mut().session.attach_preset_store(open(Box::new(RejectActionsWrite(store.clone()))));
|
||||
let failure = crate::actions::assign_shortcut(h.state_mut(), 0, "F4").unwrap_err();
|
||||
assert!(failure.contains("injected Actions write failure"));
|
||||
assert!(h.state().session.actions.list[0].action_id.is_none());
|
||||
assert_eq!(store.read(ACTIONS_FILE, 4096).unwrap(), original);
|
||||
let saved_prefs = h.state().session.prefs_to_json();
|
||||
|
||||
let mut h = harness();
|
||||
h.state_mut().session.load_prefs_json(&saved_prefs).unwrap();
|
||||
h.state_mut().session.attach_preset_store(open(Box::new(store)));
|
||||
assert_eq!(h.state().session.prefs().shortcuts["actions.play:Target"], "F2");
|
||||
assert_eq!(h.state().session.prefs().alternate_shortcuts["actions.play:Target"], ["F3"]);
|
||||
assert!(!h.state().session.prefs().shortcuts.values().any(|key| key == "F4"));
|
||||
press(&mut h, "F2");
|
||||
assert_eq!(active_name(&h), "legacy target");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_shortcut_assignment_leaves_identity_and_bindings_unmodified() {
|
||||
let mut h = harness();
|
||||
|
||||
@@ -231,28 +231,36 @@ pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, index: usize, shortcut: &
|
||||
let id = actions_cmds::occurrence_key(&action_id);
|
||||
let legacy = format!("{}{}", actions_cmds::PLAY_SHORTCUT_PREFIX, list[index].name);
|
||||
let prefs = app.session.prefs();
|
||||
let previous = list[index].action_id.is_none().then(|| (prefs.shortcuts.clone(), prefs.alternate_shortcuts.clone()));
|
||||
let pending = app.services.preset_store.is_some() && app.session.preset_store.is_none();
|
||||
let legacy_owner = !pending && actions_cmds::shortcut_row(list, &legacy) == Some(index);
|
||||
let mut set = serde_json::Map::new();
|
||||
let mut alternates = serde_json::Map::new();
|
||||
// A function key belongs to only one action. Ordinary menu bindings remain intact.
|
||||
// Retain the old key as a fallback if an asynchronous store never commits the ID.
|
||||
// A live ID-based override shadows it, including an explicit "None" assignment.
|
||||
for (other, assigned) in &prefs.shortcuts {
|
||||
if actions_cmds::is_action_key(other) && other != &id && assigned == shortcut && !shortcut.is_empty() {
|
||||
if actions_cmds::is_action_key(other)
|
||||
&& other != &id
|
||||
&& assigned == shortcut
|
||||
&& !shortcut.is_empty()
|
||||
&& !(other.starts_with(actions_cmds::PLAY_SHORTCUT_PREFIX) && (pending || (legacy_owner && other == &legacy)))
|
||||
{
|
||||
set.insert(other.clone(), json!(""));
|
||||
}
|
||||
}
|
||||
if actions_cmds::shortcut_row(list, &legacy) == Some(index) {
|
||||
if prefs.shortcuts.contains_key(&legacy) {
|
||||
set.insert(legacy.clone(), Value::Null);
|
||||
}
|
||||
if let Some(keys) = prefs.alternate_shortcuts.get(&legacy) {
|
||||
if !prefs.alternate_shortcuts.contains_key(&id) {
|
||||
alternates.insert(id.clone(), json!(keys));
|
||||
}
|
||||
alternates.insert(legacy, Value::Null);
|
||||
}
|
||||
}
|
||||
set.insert(id, json!(shortcut));
|
||||
let result = app.run("edit.keyboardShortcuts", json!({"set": set, "alternates": alternates, "allowUnknown": true, "removeConflicts": false}))?;
|
||||
actions_cmds::commit_action_id(&mut app.session, index, action_id);
|
||||
let result = app.run("edit.keyboardShortcuts", json!({"set": set, "allowUnknown": true, "removeConflicts": false}))?;
|
||||
if let Err(error) = actions_cmds::commit_action_id(&mut app.session, index, action_id) {
|
||||
if let Some((shortcuts, alternate_shortcuts)) = previous {
|
||||
app.session.edit_prefs(|prefs| {
|
||||
prefs.shortcuts = shortcuts;
|
||||
prefs.alternate_shortcuts = alternate_shortcuts;
|
||||
});
|
||||
}
|
||||
let error = error.to_string();
|
||||
app.ui.status = error.clone();
|
||||
app.ui.status_error = true;
|
||||
return Err(error);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
|
||||
@@ -2146,6 +2146,25 @@ fn pause_child(app: &mut PhotocraftApp) -> u64 {
|
||||
v["paused"]["dialog"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bound_same_name_call_resumes_the_selected_occurrence() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 8, "height": 6, "background": "#203040"})).unwrap();
|
||||
let id = "a".repeat(32);
|
||||
let mut second =
|
||||
Action::new("Same", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1.5})), ("layer.new.layer".into(), json!({"name":"Suffix"}))]);
|
||||
second.action_id = Some(id.clone());
|
||||
second.dialogs.insert(0);
|
||||
let first =
|
||||
Action::new("Same", vec![("actions.play".into(), json!({"action":"Same","actionId":id})), ("layer.new.layer".into(), json!({"name":"caller tail"}))]);
|
||||
app.session.actions.list.extend([first, second]);
|
||||
|
||||
let playback = play(&mut app, &json!({"action":"Same"})).unwrap();
|
||||
let dialog = playback["paused"]["dialog"].as_u64().expect("the selected occurrence's blur dialog");
|
||||
crate::dialogs::confirm(&mut app, dialog).unwrap();
|
||||
assert_eq!(layer_names(&app), ["Suffix", "caller tail"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() {
|
||||
let mut app = recording_with_dialog_child();
|
||||
|
||||
Reference in new issue
Block a user