From 4e69ea3f01be2bbe02937810bcfa6afd525890f9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 03:06:23 +0000 Subject: [PATCH] merge-fwa: FW1: actions library commands (Clear All, Reset, Replace) with one undo, PhotoCraft folder occurrences read into unique names --- crates/automation/src/actions/file.rs | 63 ++++++ crates/automation/src/actions/list.rs | 217 +++++++++++++++++++-- crates/automation/src/actions/mod.rs | 4 +- crates/automation/src/actions/tests.rs | 62 +++++- crates/automation/src/ui/actions/menu.rs | 24 ++- crates/automation/src/ui/actions/mock.rs | 2 +- crates/automation/src/ui/actions/mod.rs | 4 +- crates/automation/src/ui/actions/panel.rs | 9 + crates/automation/src/ui/actions/prompt.rs | 55 ++++++ crates/automation/src/ui/actions/words.rs | 12 ++ crates/automation/tests/it/actions.rs | 26 +++ crates/automation/tests/it/dialogs.rs | 23 +++ 12 files changed, 469 insertions(+), 32 deletions(-) create mode 100644 crates/automation/src/ui/actions/prompt.rs diff --git a/crates/automation/src/actions/file.rs b/crates/automation/src/actions/file.rs index 013661588..1591e6fdb 100644 --- a/crates/automation/src/actions/file.rs +++ b/crates/automation/src/actions/file.rs @@ -6,7 +6,14 @@ use super::model::Action; /// "actions": [...]}`, plus `sets` with the names of empty sets, left out when there are none /// and optional on load, so PhotoCraft's files load and save unchanged. Unknown fields are /// ignored. +/// +/// A file PhotoCraft wrote with its folder occurrences (`set_rows`, and per action `set_slot`, +/// `action_id`, `legacy_shortcut_owner`) loads too: those fields are read into +/// [`FileOccurrences`] and [`ActionList::merge_file`](super::ActionList::merge_file) turns them +/// into unique set and action names. Names are the list's only identity, so they are never +/// written back. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(from = "RawFile")] pub struct ActionsFile { /// The file version, [`ActionsFile::VERSION`]. pub version: u32, @@ -15,6 +22,57 @@ pub struct ActionsFile { /// Sets that hold no action. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sets: Vec, + /// The folder occurrences a PhotoCraft file carried; empty for every other file. + #[serde(skip)] + pub(super) occurrences: FileOccurrences, +} + +/// What a PhotoCraft file says beside the names: its ordered folder occurrences (same-name and +/// empty ones included) and, per action at the same index, its occurrence, stored id and whether +/// it owns the old name-keyed shortcut among actions of its name. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct FileOccurrences { + pub(super) set_rows: Vec, + pub(super) actions: Vec, +} + +/// One action's occurrence fields in a PhotoCraft file. +#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)] +pub(super) struct ActionOccurrence { + #[serde(default)] + pub(super) set_slot: Option, + #[serde(default)] + pub(super) action_id: Option, + #[serde(default)] + pub(super) legacy_shortcut_owner: bool, +} + +/// The file as it is read: each action with its occurrence fields beside it. +#[derive(serde::Deserialize)] +struct RawFile { + version: u32, + actions: Vec, + #[serde(default)] + sets: Vec, + #[serde(default)] + set_rows: Vec, +} + +#[derive(serde::Deserialize)] +struct RawAction { + #[serde(flatten)] + action: Action, + #[serde(flatten)] + occurrence: ActionOccurrence, +} + +impl From for ActionsFile { + fn from(raw: RawFile) -> Self { + let (actions, occurrences): (Vec, Vec) = raw.actions.into_iter().map(|raw| (raw.action, raw.occurrence)).unzip(); + let empty = raw.set_rows.is_empty() && occurrences.iter().all(|occurrence| *occurrence == ActionOccurrence::default()); + let occurrences = if empty { FileOccurrences::default() } else { FileOccurrences { set_rows: raw.set_rows, actions: occurrences } }; + ActionsFile { version: raw.version, actions, sets: raw.sets, occurrences } + } } /// Why an actions file did not load. @@ -57,6 +115,11 @@ impl ActionsFile { // pc: crates/engine/src/preset_store.rs:1112. pub const VERSION: u32 = 1; + /// A file of version [`VERSION`](Self::VERSION) with `actions` and the empty `sets`. + pub fn new(actions: Vec, sets: Vec) -> Self { + ActionsFile { version: Self::VERSION, actions, sets, occurrences: FileOccurrences::default() } + } + /// Reads a file's JSON text. pub fn from_json(text: &str) -> Result { let file: ActionsFile = serde_json::from_str(text)?; diff --git a/crates/automation/src/actions/list.rs b/crates/automation/src/actions/list.rs index d19f1e654..9415f9d85 100644 --- a/crates/automation/src/actions/list.rs +++ b/crates/automation/src/actions/list.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; -use super::file::ActionsFile; +use super::file::{ActionOccurrence, ActionsFile}; use super::model::{Action, ActionColor, ActionInclude, ActionStep}; /// Why an [`ActionList`] edit was refused. The app shows the message; nothing changed. @@ -27,6 +27,8 @@ pub enum ActionListError { NameTaken(String), /// The name is empty or only white space. EmptyName, + /// No Clear All, Reset or Replace to undo: none was made, or an edit since ended its undo. + NothingToUndo, } impl std::fmt::Display for ActionListError { @@ -38,6 +40,7 @@ impl std::fmt::Display for ActionListError { ActionListError::OutOfRange => f.write_str("destination is out of range"), ActionListError::NameTaken(_) => f.write_str("an action with this name already exists"), ActionListError::EmptyName => f.write_str("\"name\" is empty"), + ActionListError::NothingToUndo => f.write_str("no Actions library change is available to undo"), } } } @@ -52,6 +55,31 @@ pub struct MergedFile { pub added: Vec, /// The (name in the file, name given) pair of each action renamed to stay unique. pub renames: Vec<(String, String)>, + /// The (stored id, name given) pair of each action a PhotoCraft file gave an `action_id`, so + /// the app moves what it keyed by the id (`actions.playById:` shortcuts, calls by + /// `actionId`) to the name. An id the file repeats is left out, as PhotoCraft ignores it. + pub ids: Vec<(String, String)>, +} + +/// Which whole-list command an undo reverts: the Actions panel's Clear All Actions, Reset +/// Actions… or Replace Actions…. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum LibraryEdit { + /// [`ActionList::clear_all`]. + ClearAll, + /// [`ActionList::reset`]. + Reset, + /// [`ActionList::replace_all`]. + Replace, +} + +/// The list before the last whole-list command. +#[derive(Clone, Debug, PartialEq)] +struct LibrarySnapshot { + edit: LibraryEdit, + actions: Vec, + sets: Vec, } /// The recorded actions: one flat list (PhotoCraft's engine, journal and file are flat), each @@ -67,12 +95,16 @@ pub struct MergedFile { /// /// Action names are unique across the whole list, whatever their sets: the app finds an action /// by its name (calls, function keys, scripts). An edit that would repeat a name is refused, and -/// a loaded file's repeated names are renamed (`Foo`, `Foo 2`). +/// a loaded file's repeated names are renamed (`Foo`, `Foo 2`). Set names are unique likewise. +/// +/// Clear All, Reset and Replace keep one undo: [`undo_library`](Self::undo_library) restores the +/// list as it was before the last of them, until any other edit ends it. #[derive(Clone, Debug, Default, PartialEq)] pub struct ActionList { pub(super) actions: Vec, pub(super) sets: Vec, pub(super) revision: u64, + undo: Option>, } impl ActionList { @@ -474,19 +506,42 @@ impl ActionList { /// actions of every set the file names are dropped first. The file's empty sets are added when /// absent. `calls(step, &renames)` runs once on every step of every action just added, after /// all renames are known (also when there are none). + /// + /// A PhotoCraft file's folder occurrences become sets: the first occurrence of a set name + /// keeps it (and joins a set of that name already in the list, as a plain file's set does), + /// each later one gets a unique name (`Set 2`), and an empty one becomes an empty set. Of the + /// actions sharing a name, the file's shortcut owner keeps the name. The stored ids come back + /// in [`MergedFile::ids`]. pub fn merge_file(&mut self, file: ActionsFile, replace: bool, mut calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { - let ActionsFile { actions, sets, .. } = file; + let ActionsFile { mut actions, sets, occurrences, .. } = file; if replace { - let named: BTreeSet<&str> = actions.iter().filter_map(|action| action.set.as_deref()).chain(sets.iter().map(String::as_str)).collect(); + let named: BTreeSet<&str> = actions + .iter() + .filter_map(|action| action.set.as_deref()) + .chain(sets.iter().map(String::as_str)) + .chain(occurrences.set_rows.iter().map(String::as_str)) + .collect(); self.actions.retain(|action| !action.set.as_deref().is_some_and(|set| named.contains(set))); } + let fields = |index: usize| occurrences.actions.get(index).cloned().unwrap_or_default(); + let empty_sets = self.fold_occurrences(&mut actions, sets, &occurrences.set_rows, &fields); + // The shortcut owners claim first, so each keeps its name over an earlier namesake. + let owners = (0..actions.len()).filter(|&i| fields(i).legacy_shortcut_owner); + let order: Vec = owners.chain((0..actions.len()).filter(|&i| !fields(i).legacy_shortcut_owner)).collect(); + let claimed = Names::of(&self.actions).claim_all(order.iter().map(|&i| actions[i].name.as_str())); + let mut given = vec![String::new(); actions.len()]; + for (&i, name) in order.iter().zip(claimed) { + given[i] = name; + } let mut merged = MergedFile::default(); - let mut names = Names::of(&self.actions); - let claimed = names.claim_all(actions.iter().map(|action| action.name.as_str())); - for (mut action, name) in actions.into_iter().zip(claimed) { + let ids = file_ids(&occurrences.actions); + for (index, (mut action, name)) in actions.into_iter().zip(given).enumerate() { if name != action.name { merged.renames.push((action.name.clone(), name.clone())); } + if let Some(Some(id)) = ids.get(index) { + merged.ids.push((id.clone(), name.clone())); + } action.name = name; self.actions.push(action); merged.added.push(self.actions.len() - 1); @@ -496,7 +551,7 @@ impl ActionList { calls(step, &merged.renames); } } - for set in sets { + for set in empty_sets { if !self.sets().contains(&set.as_str()) { self.sets.push(set); } @@ -505,16 +560,128 @@ impl ActionList { merged } - /// The list a file holds (its empty sets included). A name the file repeats is renamed as - /// [`merge_file`](Self::merge_file) renames a clash (`Foo`, `Foo 2`); a call by that name - /// keeps reaching the first action that has it. - pub fn from_file(file: ActionsFile) -> Self { - let ActionsFile { mut actions, sets, .. } = file; - let claimed = Names::default().claim_all(actions.iter().map(|action| action.name.as_str())); - for (action, name) in actions.iter_mut().zip(claimed) { - action.name = name; + /// Gives each action of a file the set name of its folder occurrence and returns the file's + /// empty sets: the plain ones, then each occurrence that holds no action. The first + /// occurrence of a name keeps it; a later one, or one whose name a plain set of the file has, + /// claims a name unique among the list's sets and the file's. + fn fold_occurrences( + &self, + actions: &mut [Action], + sets: Vec, + set_rows: &[String], + fields: &dyn Fn(usize) -> ActionOccurrence, + ) -> Vec { + if set_rows.is_empty() { + return sets; } - Self { actions, sets, revision: 0 } + // An action's slot counts only where the file's occurrence still has its set name. + let slot_of = + |index: usize, action: &Action| fields(index).set_slot.filter(|&slot| set_rows.get(slot).map(String::as_str) == action.set.as_deref()); + let plain: HashSet<&str> = actions + .iter() + .enumerate() + .filter(|(index, action)| slot_of(*index, action).is_none()) + .filter_map(|(_, action)| action.set.as_deref()) + .chain(sets.iter().map(String::as_str)) + .collect(); + let mut names = Names::new(self.sets().into_iter().chain(plain.iter().copied()).map(str::to_owned)); + let mut first: HashSet<&str> = HashSet::new(); + let slot_names: Vec = set_rows + .iter() + .map(|caption| { + if !plain.contains(caption.as_str()) && first.insert(caption.as_str()) { + names.taken.insert(caption.clone()); + caption.clone() + } else { + names.claim(caption) + } + }) + .collect(); + let mut filled = vec![false; set_rows.len()]; + let slots: Vec> = actions.iter().enumerate().map(|(index, action)| slot_of(index, action)).collect(); + for (action, slot) in actions.iter_mut().zip(slots) { + if let Some(slot) = slot { + action.set = Some(slot_names[slot].clone()); + filled[slot] = true; + } + } + let mut empty = sets; + empty.extend(slot_names.into_iter().zip(filled).filter(|(_, filled)| !filled).map(|(name, _)| name)); + empty + } + + /// The list a file holds (its empty sets included), named as [`merge_file`](Self::merge_file) + /// names a file's actions and sets in an empty list: a name the file repeats is renamed + /// (`Foo`, `Foo 2`), and a call by that name keeps reaching the first action that has it. The + /// app that keys anything by a PhotoCraft file's stored ids uses [`load`](Self::load). + pub fn from_file(file: ActionsFile) -> Self { + Self::load(file).0 + } + + /// [`from_file`](Self::from_file) with what loading renamed and the stored ids. + pub fn load(file: ActionsFile) -> (Self, MergedFile) { + let mut list = Self::new(); + let merged = list.merge_file(file, false, |_, _| {}); + list.revision = 0; + (list, merged) + } + + /// Clear All Actions: no action and no set. [`undo_library`](Self::undo_library) restores + /// them. + pub fn clear_all(&mut self) { + self.library_edit(LibraryEdit::ClearAll, |list| { + list.actions.clear(); + list.sets.clear(); + }); + } + + /// Reset Actions…: the app's `defaults` (its starting sets), added to the list with `append` + /// (renamed where a name is taken, as [`merge_file`](Self::merge_file) does), else in place + /// of everything. `calls` is as for `merge_file`. + pub fn reset(&mut self, defaults: ActionsFile, append: bool, calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { + self.library_edit(LibraryEdit::Reset, |list| { + if !append { + list.actions.clear(); + list.sets.clear(); + } + list.merge_file(defaults, false, calls) + }) + } + + /// Replace Actions…: the list becomes what `file` holds, named as [`load`](Self::load) names + /// it. `calls` is as for [`merge_file`](Self::merge_file). + pub fn replace_all(&mut self, file: ActionsFile, calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { + self.library_edit(LibraryEdit::Replace, |list| { + list.actions.clear(); + list.sets.clear(); + list.merge_file(file, false, calls) + }) + } + + /// The whole-list command [`undo_library`](Self::undo_library) would revert, for the app's + /// Undo label; `None` when an edit since ended it. + pub fn library_undo(&self) -> Option { + self.undo.as_ref().map(|snapshot| snapshot.edit) + } + + /// Restores the list as it was before the last Clear All, Reset or Replace and returns which + /// one it reverted. + pub fn undo_library(&mut self) -> Result { + let snapshot = self.undo.take().ok_or(ActionListError::NothingToUndo)?; + let LibrarySnapshot { edit, actions, sets } = *snapshot; + self.actions = actions; + self.sets = sets; + self.touch(); + Ok(edit) + } + + /// Runs a whole-list command and keeps the list from before it as the one undo. + fn library_edit(&mut self, edit: LibraryEdit, apply: impl FnOnce(&mut Self) -> R) -> R { + let snapshot = LibrarySnapshot { edit, actions: self.actions.clone(), sets: self.sets.clone() }; + let result = apply(self); + self.touch(); + self.undo = Some(Box::new(snapshot)); + result } /// Replaces the whole list with `with` (a list loaded or restored from elsewhere): its actions @@ -529,7 +696,7 @@ impl ActionList { /// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`). pub fn to_file(&self) -> ActionsFile { let empty = self.sets().into_iter().filter(|set| !self.actions.iter().any(|action| action.set.as_deref() == Some(*set))); - ActionsFile { version: ActionsFile::VERSION, actions: self.actions.clone(), sets: empty.map(str::to_owned).collect() } + ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()) } /// Whether an action has `name`. @@ -551,12 +718,24 @@ impl ActionList { } /// Marks the list changed by an edit made outside these calls (the app replaced an action's - /// steps). + /// steps). Every edit ends the undo of the last Clear All, Reset or Replace. pub fn touch(&mut self) { self.revision = self.revision.wrapping_add(1); + self.undo = None; } } +/// Each action's stored id, where it is PhotoCraft's form (32 lowercase hex digits) and no other +/// action of the file has it. +fn file_ids(occurrences: &[ActionOccurrence]) -> Vec> { + let valid = |id: &&String| id.len() == 32 && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + let mut count: HashMap<&str, usize> = HashMap::new(); + for id in occurrences.iter().filter_map(|occurrence| occurrence.action_id.as_ref()).filter(valid) { + *count.entry(id).or_default() += 1; + } + occurrences.iter().map(|occurrence| occurrence.action_id.clone().filter(|id| valid(&id) && count.get(id.as_str()) == Some(&1))).collect() +} + /// The names taken so far and, per base name, the next suffix to try, so claiming one base many /// times (a file that repeats a name) stays linear. #[derive(Default)] diff --git a/crates/automation/src/actions/mod.rs b/crates/automation/src/actions/mod.rs index c9aed5277..a4dee0272 100644 --- a/crates/automation/src/actions/mod.rs +++ b/crates/automation/src/actions/mod.rs @@ -4,7 +4,7 @@ //! | Part | Names | //! |---|---| //! | The model | [`Action`], [`ActionStep`], [`ActionColor`], [`ActionInclude`] | -//! | The list and its edits | [`ActionList`], [`ActionListError`], [`moved_index`] | +//! | The list and its edits | [`ActionList`], [`ActionListError`], [`LibraryEdit`], [`moved_index`] | //! | The file | [`ActionsFile`] (PhotoCraft's `actions.json`), [`ActionsFileError`] | //! | Playback | [`ActionPlayer`], [`ActionRunner`], [`StepOutcome`], [`PlaybackBudget`], [`PlaybackReport`], [`StepFailure`], [`PlaybackRefusal`], [`MAX_PLAYBACK_STEPS`], [`MAX_PLAYBACK_DEPTH`] | //! | Recording | [`Recording`], [`ActionList::begin_recording`], [`ActionList::append_recorded`] | @@ -23,7 +23,7 @@ mod recording; mod tests; pub use file::{ActionsFile, ActionsFileError}; -pub use list::{ActionList, ActionListError, MergedFile, moved_index}; +pub use list::{ActionList, ActionListError, LibraryEdit, MergedFile, moved_index}; pub use model::{Action, ActionColor, ActionInclude, ActionStep}; pub use player::{ ActionPlayer, ActionRunner, MAX_PLAYBACK_DEPTH, MAX_PLAYBACK_STEPS, PlaybackBudget, PlaybackRefusal, PlaybackReport, StepFailure, StepOutcome, diff --git a/crates/automation/src/actions/tests.rs b/crates/automation/src/actions/tests.rs index 21421be67..9e5bfc1e9 100644 --- a/crates/automation/src/actions/tests.rs +++ b/crates/automation/src/actions/tests.rs @@ -14,7 +14,7 @@ fn action(name: &str, commands: &[&str]) -> Action { } fn list_of(actions: Vec) -> ActionList { - ActionList::from_file(ActionsFile { version: ActionsFile::VERSION, actions, sets: Vec::new() }) + ActionList::from_file(ActionsFile::new(actions, Vec::new())) } /// Runs every step by recording its command. @@ -85,11 +85,7 @@ fn action_list_file_round_trip_keeps_pc_json() { #[trial] fn action_names_in_a_file_keep_their_own_names_and_rename_only_repeats() { let names = |list: &ActionList| list.actions.iter().map(|action| action.name.clone()).collect::>(); - let file = || ActionsFile { - version: ActionsFile::VERSION, - actions: vec![action("Foo", &[]), action("Foo", &[]), action("Foo 2", &[])], - sets: Vec::new(), - }; + let file = || ActionsFile::new(vec![action("Foo", &[]), action("Foo", &[]), action("Foo 2", &[])], Vec::new()); assert_eq!(names(&ActionList::from_file(file())), ["Foo", "Foo 3", "Foo 2"]); let mut list = list_of(vec![action("Foo", &[])]); @@ -98,6 +94,60 @@ fn action_names_in_a_file_keep_their_own_names_and_rename_only_repeats() { assert_eq!(merged.renames, [("Foo".to_owned(), "Foo 3".to_owned()), ("Foo".to_owned(), "Foo 4".to_owned())]); } +// A PhotoCraft file with folder occurrences: two folders named "Basics" and an empty one become +// sets with unique names, the empty one an empty set; of two actions named "Play", the shortcut +// owner keeps the name; each unique stored id maps to its action's final name, a repeated one to +// none; and the occurrence fields are never written back. +#[trial] +fn action_file_folder_occurrences_become_unique_names() { + let text = r#"{"version":1,"set_rows":["Basics","Basics","Empty"],"actions":[ + {"name":"Play","steps":[],"set":"Basics","set_slot":0,"action_id":"0123456789abcdef0123456789abcdef"}, + {"name":"Play","steps":[],"set":"Basics","set_slot":1,"legacy_shortcut_owner":true}, + {"name":"Loose","steps":[],"action_id":"ffffffffffffffffffffffffffffffff"}, + {"name":"Twin","steps":[],"action_id":"ffffffffffffffffffffffffffffffff"}]}"#; + let (list, merged) = ActionList::load(ActionsFile::from_json(text).unwrap()); + let names: Vec<(&str, Option<&str>)> = list.actions().iter().map(|action| (action.name.as_str(), action.set.as_deref())).collect(); + assert_eq!(names, [("Play 2", Some("Basics")), ("Play", Some("Basics 2")), ("Loose", None), ("Twin", None)]); + assert_eq!(list.sets(), ["Basics", "Basics 2", "Empty"]); + assert_eq!(merged.ids, [("0123456789abcdef0123456789abcdef".to_owned(), "Play 2".to_owned())]); + let saved = list.to_file().to_json().unwrap(); + assert!(["set_rows", "set_slot", "action_id", "legacy_shortcut_owner"].iter().all(|field| !saved.contains(field))); +} + +// Clear All, Reset (append and replace) and Replace each keep one undo that restores the list as it +// was, actions and empty sets alike; any other edit after them leaves nothing to undo. +#[trial] +fn action_library_commands_keep_one_undo() { + let mut list = list_of(vec![action("Invert Colors", &["image.invert"])]); + list.new_set("Empty").unwrap(); + let before = (list.actions().to_vec(), list.sets().into_iter().map(str::to_owned).collect::>()); + let state = |list: &ActionList| (list.actions().to_vec(), list.sets().into_iter().map(str::to_owned).collect::>()); + let defaults = || ActionsFile::new(vec![Action { set: Some("Basics".into()), ..action("Invert Colors", &["image.invert"]) }], Vec::new()); + + list.clear_all(); + assert!(list.actions().is_empty() && list.sets().is_empty()); + assert_eq!(list.library_undo(), Some(LibraryEdit::ClearAll)); + assert_eq!(list.undo_library(), Ok(LibraryEdit::ClearAll)); + assert_eq!(state(&list), before); + + list.reset(defaults(), true, |_, _| {}); + let names: Vec<&str> = list.actions().iter().map(|action| action.name.as_str()).collect(); + assert_eq!(names, ["Invert Colors", "Invert Colors 2"]); + assert_eq!(list.undo_library(), Ok(LibraryEdit::Reset)); + assert_eq!(state(&list), before); + + list.reset(defaults(), false, |_, _| {}); + assert_eq!(list.sets(), ["Basics"]); + list.undo_library().unwrap(); + assert_eq!(state(&list), before); + + list.replace_all(ActionsFile::new(vec![action("Other", &[])], Vec::new()), |_, _| {}); + assert_eq!(list.actions().len(), 1); + list.set_color(0, ActionColor::Red).unwrap(); + assert_eq!(list.library_undo(), None); + assert_eq!(list.undo_library(), Err(ActionListError::NothingToUndo)); +} + /// A runner whose steps are named by what they do: `pause`, `wait`, `stop`, `deny` (refused by the /// gate), `noop`; any other is `Done`. Its own `charge` refuses once `charges` are spent. struct Scripted { diff --git a/crates/automation/src/ui/actions/menu.rs b/crates/automation/src/ui/actions/menu.rs index a8ef72a9c..ed1e72837 100644 --- a/crates/automation/src/ui/actions/menu.rs +++ b/crates/automation/src/ui/actions/menu.rs @@ -92,9 +92,18 @@ pub enum ActionsPanelCommands { /// Run an action over many files. #[command(label = "Batch…")] Batch, + /// Remove every action and set. + #[command(label = "Clear All Actions")] + ClearAll, + /// Put back the app's starting sets, in place of the list or added to it. + #[command(label = "Reset Actions…")] + Reset, /// Load actions from a file. #[command(label = "Load Actions…")] Load, + /// Replace every action with the actions of a file. + #[command(label = "Replace Actions…")] + Replace, /// Save every action to a file. #[command(label = "Save Actions…")] Save, @@ -145,7 +154,8 @@ impl ActionsPanelCommands { /// a selected or first action, Delete follows the footer's Delete, Duplicate a deletable /// selection or a set (not while recording), Record Again a selected step (not while /// recording), Insert Menu Item… and Insert Stop… a selected action or step, Insert Path the - /// same with a path selected, Save an action or a selected set, Playback Options… not while + /// same with a path selected, Save an action or a selected set, Clear All an action or a set and + /// Reset and Replace always, all three not while recording or waiting, Playback Options… not while /// waiting, Allow Tool Recording is checked with the fact, Start Recording is off while /// recording and Stop Recording only on while it runs, and Button Mode is checked with the /// state's setting and off while recording. @@ -155,6 +165,8 @@ impl ActionsPanelCommands { let on_row = matches!(panel.selected, Some(ActionSelection::Action(_) | ActionSelection::Step(..))); let set_selected = matches!(&panel.selected, Some(ActionSelection::Set(name)) if list.sets().contains(&name.as_str())); let state = CommandState::new(); + // The whole-list commands wait while a recording or a paused playback holds an action. + let library_idle = !recording && !facts.waiting; match self { ActionsPanelCommands::NewAction | ActionsPanelCommands::NewSet | ActionsPanelCommands::StartRecording => state.enabled(!recording), ActionsPanelCommands::SetOptions => state.enabled(current_set(panel, list).is_some()), @@ -167,6 +179,8 @@ impl ActionsPanelCommands { ActionsPanelCommands::Batch => state.enabled(play_target(panel.selected.as_ref(), list).is_some()), ActionsPanelCommands::Save => state.enabled(any || set_selected), ActionsPanelCommands::Load => state, + ActionsPanelCommands::ClearAll => state.enabled(library_idle && (any || !list.sets().is_empty())), + ActionsPanelCommands::Reset | ActionsPanelCommands::Replace => state.enabled(library_idle), ActionsPanelCommands::ButtonMode => state.enabled(!recording).checked(panel.settings.button_mode), ActionsPanelCommands::Duplicate => { let deletable = panel.selected.as_ref().is_some_and(|selected| delete_event(selected, false).is_some()); @@ -206,6 +220,9 @@ impl ActionsPanelCommands { ActionsPanelCommands::InsertStop => selected_action(selected, list).map(|_| ActionsEvent::InsertStop)?, ActionsPanelCommands::Batch => ActionsEvent::Batch(play_target(selected, list)?.0), ActionsPanelCommands::Load => ActionsEvent::Load, + ActionsPanelCommands::ClearAll => ActionsEvent::ClearAll, + ActionsPanelCommands::Reset => ActionsEvent::Reset, + ActionsPanelCommands::Replace => ActionsEvent::Replace, ActionsPanelCommands::Save => ActionsEvent::Save { set: None }, ActionsPanelCommands::ButtonMode => { panel.settings.button_mode = !panel.settings.button_mode; @@ -229,7 +246,8 @@ impl ActionsPanelCommands { /// The rows of the Actions panel's menu, for the dock's `PanelMenu`, in Photoshop's groups: New /// Action…, New Set…, Set Options…, Duplicate, Delete | Play, Start Recording (Stop Recording /// while `facts.recording`), Record Again | Insert Menu Item…, Insert Stop…, Insert Path, Batch… | -/// Playback Options…, Allow Tool Recording, Button Mode | Load and Save Actions…. A row `offered` +/// Playback Options…, Allow Tool Recording, Button Mode | Clear All Actions, Reset Actions…, Load +/// Actions…, Replace Actions…, Save Actions…. A row `offered` /// refuses is left out, and a group left empty loses its separator. pub fn panel_rows(facts: ActionsMenuFacts, offered: &dyn Fn(ActionsPanelCommands) -> bool) -> Vec { use ActionsPanelCommands as C; @@ -239,7 +257,7 @@ pub fn panel_rows(facts: ActionsMenuFacts, offered: &dyn Fn(ActionsPanelCommands &[C::Play, record, C::RecordAgain], &[C::InsertMenuItem, C::InsertStop, C::InsertPath, C::Batch], &[C::PlaybackOptions, C::ToolRecording, C::ButtonMode], - &[C::Load, C::Save], + &[C::ClearAll, C::Reset, C::Load, C::Replace, C::Save], ]; let mut rows = Vec::new(); for group in groups { diff --git a/crates/automation/src/ui/actions/mock.rs b/crates/automation/src/ui/actions/mock.rs index d6615b654..c708b664e 100644 --- a/crates/automation/src/ui/actions/mock.rs +++ b/crates/automation/src/ui/actions/mock.rs @@ -70,7 +70,7 @@ pub fn action(name: &str, set: Option<&str>, commands: &[&str]) -> Action { /// The list of `actions`. pub fn list_of(actions: Vec) -> ActionList { - ActionList::from_file(ActionsFile { version: ActionsFile::VERSION, actions, sets: Vec::new() }) + ActionList::from_file(ActionsFile::new(actions, Vec::new())) } /// Sharpen (levels, curves, blur) and Vignette (mask, blur) loose; Glow (glow) in the set Effects. diff --git a/crates/automation/src/ui/actions/mod.rs b/crates/automation/src/ui/actions/mod.rs index 9c2e5ac78..db85a5e32 100644 --- a/crates/automation/src/ui/actions/mod.rs +++ b/crates/automation/src/ui/actions/mod.rs @@ -5,7 +5,7 @@ //! | Part | Names | //! |---|---| //! | The panel | [`ActionsPanel`], [`ActionsPanelOutput`], [`ActionsEvent`], [`ActionMove`], [`ActionPlace`], [`ActionSelection`], [`ShortcutChoice`] | -//! | The app's side | [`ActionsHost`], [`ActionsPanelCommands`], [`ActionsMenuFacts`] and [`panel_rows`] (the panel menu), [`ActionsMenuAction`] | +//! | The app's side | [`ActionsHost`], [`ActionsPanelCommands`], [`ActionsMenuFacts`] and [`panel_rows`] (the panel menu), [`ActionsMenuAction`], [`LibraryPrompt`] (Clear All, Reset, Replace) | //! | State | [`ActionsPanelState`], [`ActionsSettings`] (persisted) | //! | Columns and words | [`INCLUDE_COLUMN`], [`DIALOG_COLUMN`], [`ActionsWords`] | @@ -15,6 +15,7 @@ mod menu; #[cfg(feature = "screen-testing")] pub mod mock; mod panel; +mod prompt; mod rows; #[cfg(feature = "screen-testing")] mod stories; @@ -22,6 +23,7 @@ mod words; pub use body::{ActionMove, ActionPlace}; pub use menu::{ActionsMenuAction, ActionsMenuFacts, ActionsPanelCommands, panel_rows}; +pub use prompt::LibraryPrompt; pub use panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanel, ActionsPanelOutput, ActionsPanelState, ActionsSettings, ShortcutChoice}; pub use rows::{DIALOG_COLUMN, INCLUDE_COLUMN}; pub use words::ActionsWords; diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs index d16e0bed4..8429d5025 100644 --- a/crates/automation/src/ui/actions/panel.rs +++ b/crates/automation/src/ui/actions/panel.rs @@ -217,6 +217,15 @@ pub enum ActionsEvent { Batch(usize), /// Load Actions… (the app's file dialog). Load, + /// Clear All Actions: the app asks with [`LibraryPrompt::ClearAll`](super::LibraryPrompt) and + /// answers OK with [`ActionList::clear_all`]. + ClearAll, + /// Reset Actions…: the app asks with [`LibraryPrompt::Reset`](super::LibraryPrompt), whose + /// Append keeps the list ([`ActionList::reset`]). + Reset, + /// Replace Actions…: the app picks a file, then asks with + /// [`LibraryPrompt::Replace`](super::LibraryPrompt) ([`ActionList::replace_all`]). + Replace, /// Save Actions…, or Save Set… for one set. #[non_exhaustive] Save { diff --git a/crates/automation/src/ui/actions/prompt.rs b/crates/automation/src/ui/actions/prompt.rs new file mode 100644 index 000000000..bcb7d98d1 --- /dev/null +++ b/crates/automation/src/ui/actions/prompt.rs @@ -0,0 +1,55 @@ +//! [`LibraryPrompt`]: the question before Clear All Actions, Reset Actions… and Replace Actions…. + +use craft_ui::dialog::{PromptChoice, StandardPrompt}; +use craft_ui::runtime::words::CommonWords; + +use super::words::ActionsWords; + +/// Which whole-list command a [`StandardPrompt`] from [`prompt`](LibraryPrompt::prompt) asks +/// about. The prompt carries it as its tag, so the answer says which command it confirms +/// (`PromptAnswer::tag::()`). +/// +/// | Command | Question | Answers | +/// |---|---|---| +/// | Clear All | "Clear all actions?" | OK (`Proceed`), Cancel | +/// | Reset | "Replace the current actions?" | OK (`Proceed`: in place of the list), Append (`Alternate`: added to it), Cancel | +/// | Replace | "Replace all actions with {count} actions from {file}?" | OK (`Proceed`), Cancel | +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum LibraryPrompt { + /// Clear All Actions. + ClearAll, + /// Reset Actions…. + Reset, + /// Replace Actions… with the file the app read. + #[non_exhaustive] + Replace { + /// How many actions the file holds. + count: usize, + /// The file's display name. + file: String, + }, +} + +impl LibraryPrompt { + /// Replace Actions… with `count` actions from the file named `file`. + pub fn replace(count: usize, file: impl Into) -> Self { + LibraryPrompt::Replace { count, file: file.into() } + } + + /// The question for the app's dialog host, tagged with `self`. + pub fn prompt(&self, words: &ActionsWords, common: &CommonWords) -> StandardPrompt { + let (title, message) = match self { + LibraryPrompt::ClearAll => (words.clear_all_title.clone(), words.clear_all_question.clone()), + LibraryPrompt::Reset => (words.reset_title.clone(), words.reset_question.clone()), + LibraryPrompt::Replace { count, file } => { + (words.replace_title.clone(), words.replace_question.fill(&[("count", count.to_string().as_str()), ("file", file.as_str())]).into()) + } + }; + let mut prompt = StandardPrompt::custom(message).title(title).button(PromptChoice::Proceed, common.ok.clone()); + if *self == LibraryPrompt::Reset { + prompt = prompt.button(PromptChoice::Alternate, words.append.clone()); + } + prompt.button(PromptChoice::Cancel, common.cancel.clone()).tag(self.clone()) + } +} diff --git a/crates/automation/src/ui/actions/words.rs b/crates/automation/src/ui/actions/words.rs index c681dc31d..745edf374 100644 --- a/crates/automation/src/ui/actions/words.rs +++ b/crates/automation/src/ui/actions/words.rs @@ -48,5 +48,17 @@ craft_ui::words! { /// The modifier check row elsewhere. ctrl: "actions.ctrl" = "Ctrl"; color: "actions.color" = "Color"; + /// The title of the Clear All Actions question. + clear_all_title: "actions.clearAllTitle" = "Clear All Actions"; + clear_all_question: "actions.clearAllQuestion" = "Clear all actions?"; + /// The title of the Reset Actions question. + reset_title: "actions.resetTitle" = "Reset Actions"; + reset_question: "actions.resetQuestion" = "Replace the current actions?"; + /// Reset's answer that keeps the current actions and adds the starting sets. + append: "actions.append" = "Append"; + /// The title of the Replace Actions question. + replace_title: "actions.replaceTitle" = "Replace Actions"; + /// `{count}` is the number of actions in the file, `{file}` its name. + replace_question: template "actions.replaceQuestion" = "Replace all actions with {count} actions from {file}?"; } } diff --git a/crates/automation/tests/it/actions.rs b/crates/automation/tests/it/actions.rs index 558c176f1..f017fd4f9 100644 --- a/crates/automation/tests/it/actions.rs +++ b/crates/automation/tests/it/actions.rs @@ -222,3 +222,29 @@ fn actions_panel_disabled_reports_nothing() { assert_eq!(take(&shared), [], "a disabled panel reports no event"); assert_eq!(shared.borrow().state.selected, None, "a click selects no row"); } + +/// The panel menu's last group is Clear All Actions, Reset Actions…, Load Actions…, Replace Actions…, Save Actions…; +/// the three whole-list commands are off while recording, Clear All also with nothing to clear, and each reports +/// its event. +#[trial] +fn actions_panel_menu_offers_the_library_commands() { + use craft_automation::ui::actions::{ActionsMenuAction, ActionsMenuFacts, ActionsPanelCommands as C, panel_rows}; + use craft_ui::menu::PanelRow; + use craft_ui::runtime::commands::CommandRef; + let rows = panel_rows(ActionsMenuFacts::new(), &|_| true); + let last: Vec = rows.iter().rev().take_while(|row| !matches!(row, PanelRow::Separator)).map(|row| format!("{row:?}")).collect(); + let expected: Vec = + [C::Save, C::Replace, C::Load, C::Reset, C::ClearAll].into_iter().map(|c| format!("{:?}", PanelRow::Command(CommandRef::from(c)))).collect(); + assert_eq!(last, expected); + + let mut panel = ActionsPanelState::default(); + let list = list_of(vec![action("A", None, &["image.invert"])]); + let idle = ActionsMenuFacts::new(); + let recording = ActionsMenuFacts::new().recording(true); + for command in [C::ClearAll, C::Reset, C::Replace] { + assert!(command.state(&panel, &list, idle).is_enabled() && !command.state(&panel, &list, recording).is_enabled()); + } + assert!(!C::ClearAll.state(&panel, &ActionList::new(), idle).is_enabled()); + let events: Vec<_> = [C::ClearAll, C::Reset, C::Replace].into_iter().map(|c| c.run(&mut panel, &list, idle)).collect(); + assert_eq!(events, [ActionsEvent::ClearAll, ActionsEvent::Reset, ActionsEvent::Replace].map(|event| Some(ActionsMenuAction::Event(event)))); +} diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index f05f2563e..1763a90f7 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -158,3 +158,26 @@ fn cancel_on_a_standard_prompt_answers_its_cancel_with_the_tag() { assert!(matches!(host.take::(), Some(DialogResult::Cancel)), "a prompt without Cancel closes from outside"); assert!(host.is_empty()); } + +/// The Actions library questions: Reset answers Append (the Alternate) with its tag; Clear All and Replace have no +/// Append, so a confirm choosing it is refused. +#[trial] +fn actions_library_prompts_offer_append_only_on_reset() { + use craft_automation::ui::actions::{ActionsWords, LibraryPrompt}; + use craft_ui::runtime::words::CommonWords; + let ctx = Context::default(); + let mut host = DialogHost::new(); + let (words, common) = (ActionsWords::default(), CommonWords::default()); + let reset = host.open(LibraryPrompt::Reset.prompt(&words, &common)); + assert_eq!(call(&mut host, &ctx, "ui.dialog.confirm", json!({"dialog": reset.value(), "choice": "alternate"})), Ok(Value::Null)); + let Some(DialogResult::Ok(answer)) = host.take::() else { panic!("Reset answers Append") }; + assert_eq!((answer.choice, answer.tag::()), (PromptChoice::Alternate, Some(&LibraryPrompt::Reset))); + + for kind in [LibraryPrompt::ClearAll, LibraryPrompt::replace(3, "set.atn")] { + let prompt = host.open(kind.prompt(&words, &common)); + assert!(call(&mut host, &ctx, "ui.dialog.confirm", json!({"dialog": prompt.value(), "choice": "alternate"})).is_err()); + assert_eq!(call(&mut host, &ctx, "ui.dialog.confirm", json!({"dialog": prompt.value(), "choice": "proceed"})), Ok(Value::Null)); + let Some(DialogResult::Ok(answer)) = host.take::() else { panic!("OK answers Proceed") }; + assert_eq!((answer.choice, answer.tag::()), (PromptChoice::Proceed, Some(&kind))); + } +}