mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
feat: start persisted single-action history grouping
Add the default-on Actions history setting and a grouping scope shared by ordinary engine and shell playback entry points. Define public regressions for whole-play Undo/Redo, the off setting, failure prefixes, nesting, no-op and repeated-play boundaries, and persistence. This is an unvalidated draft increment: dialog continuation, direct compound edits, Batch/droplet boundaries and the complete edge-case qualification remain unfinished.
This commit is contained in:
1 parent
327c4cc82e
commit
182da545ee
8 files changed
+200
-5
No files matched your search
@@ -7,8 +7,9 @@
|
||||
//! `edit.transform.againCopy`) into an action. A replayable command's journal entry replaces the
|
||||
//! entries of the commands it ran on its own behalf, so they are recorded once (#3067). Playback
|
||||
//! runs those steps with [`Session::execute`] and stops at the first error, leaving one history
|
||||
//! step per step that ran. Steps switched off with `actions.toggle` (the Actions panel check
|
||||
//! marks) are skipped by playback, Batch and droplets.
|
||||
//! entry for the whole play by default (`actions.setHistory` opts into per-step history).
|
||||
//! Steps switched off with `actions.toggle` (the Actions panel check marks) are skipped by
|
||||
//! playback, Batch and droplets.
|
||||
//!
|
||||
//! An untrusted session installs [`Session::authorize`]. `actions.play` calls it for every nested
|
||||
//! step, because the outer `actions.play` id would otherwise hide a recorded `file.*` command from
|
||||
@@ -22,6 +23,9 @@ use serde_json::{Value, json};
|
||||
use crate::commands::CommandSpec;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
mod history;
|
||||
pub(crate) use history::ActionHistory;
|
||||
|
||||
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
|
||||
}
|
||||
@@ -488,6 +492,7 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option<V
|
||||
pub fn begin_playback(s: &mut Session, action: &Action) -> Result<Option<(usize, usize)>> {
|
||||
flush_recording(s)?;
|
||||
if s.actions.playing == 0 {
|
||||
history::begin(s, &action.name)?;
|
||||
s.actions.playback_steps = 0;
|
||||
}
|
||||
let recording = s.actions.recording.take();
|
||||
@@ -499,6 +504,9 @@ pub fn begin_playback(s: &mut Session, action: &Action) -> Result<Option<(usize,
|
||||
pub fn finish_playback(s: &mut Session, recording: Option<(usize, usize)>, action: &Action, from: usize) {
|
||||
s.actions.playback_stack.pop();
|
||||
s.actions.playing = s.actions.playing.saturating_sub(1);
|
||||
if s.actions.playing == 0 {
|
||||
history::finish(s);
|
||||
}
|
||||
if let Some((_, idx)) = recording {
|
||||
restore_recording(s, idx, &action.name, from);
|
||||
}
|
||||
@@ -750,8 +758,26 @@ fn set_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"action": name, "color": color}))
|
||||
}
|
||||
|
||||
/// Kept separate from Playback Options' performance modes until #5212 provides that dialog.
|
||||
fn set_history(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
not_playing(s, "actions.setHistory")?;
|
||||
let enabled = p.get("singleState").and_then(Value::as_bool).ok_or_else(|| bad("actions.setHistory", "singleState must be a boolean"))?;
|
||||
s.edit_prefs(|prefs| prefs.actions.create_single_history_state = enabled);
|
||||
Ok(json!({"singleState":enabled}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec {
|
||||
id: "actions.setHistory",
|
||||
label: "Set Actions History",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"singleState":bool} → {singleState}. Persist Create a single history state (default true). Playback Options can use this setting without changing its performance mode."##,
|
||||
enabled: always,
|
||||
run: set_history,
|
||||
journal: false,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "actions.move",
|
||||
label: "Move Action or Step",
|
||||
@@ -807,7 +833,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
label: "Play Action",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"action":name|index, "from":step?} → {action, ran, failed?:{step, id, error}}. step and from are 0-based; steps switched off with actions.toggle are skipped. Stops at the first error (the command still returns ok, with failed set) and leaves one history step per step that ran. Nested calls are supported up to 16 levels; cycles are rejected. Recording stores a named call rather than its expanded commands. Each step is checked with Session::authorize when one is installed."##,
|
||||
params: r##"{"action":name|index, "from":step?} → {action, ran, failed?:{step, id, error}}. step and from are 0-based; steps switched off with actions.toggle are skipped. Stops at the first error (the command still returns ok, with failed set) and groups document edits in one Action: <name> history entry by default; actions.setHistory can retain per-step history. Nested calls are supported up to 16 levels; cycles are rejected. Recording stores a named call rather than its expanded commands. Each step is checked with Session::authorize when one is installed."##,
|
||||
enabled: always,
|
||||
run: play,
|
||||
journal: false,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//! An outer action shares one history key across its document edits and nested calls.
|
||||
use super::{EngineError, Result, Session};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ActionHistory {
|
||||
pub key: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
pub(super) fn begin(s: &mut Session, name: &str) -> Result<()> {
|
||||
if !s.prefs().actions.create_single_history_state {
|
||||
return Ok(());
|
||||
}
|
||||
let next = s.next_action_history.checked_add(1).ok_or_else(|| EngineError::Other("action history identifier exhausted".into()))?;
|
||||
s.next_action_history = next;
|
||||
// A caller-supplied coalesce key must never join the first edit to a previous gesture.
|
||||
for st in &mut s.docs {
|
||||
st.coalesce = None;
|
||||
}
|
||||
s.action_history = Some(ActionHistory { key: format!("action-history:{next}"), label: format!("Action: {name}") });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn finish(s: &mut Session) {
|
||||
let Some(group) = s.action_history.take() else { return };
|
||||
for st in &mut s.docs {
|
||||
if st.coalesce.as_deref() == Some(group.key.as_str()) {
|
||||
st.coalesce = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,6 +201,9 @@ pub struct Session {
|
||||
pub journal: Vec<(String, Value)>,
|
||||
/// Coalescing key of the command being executed.
|
||||
coalesce_request: Option<String>,
|
||||
/// The outer action's document-edit grouping, independent of nested command dispatch.
|
||||
action_history: Option<actions_cmds::ActionHistory>,
|
||||
next_action_history: u64,
|
||||
/// Pixels copied with Edit › Copy / Cut (shared by all documents, like Photoshop).
|
||||
pub clipboard: Option<edit_cmds::Clip>,
|
||||
/// Layer › Layer Style › Copy Layer Style: the effects and the Blending Options
|
||||
|
||||
@@ -1020,6 +1020,19 @@ impl Default for Integrations {
|
||||
}
|
||||
}
|
||||
|
||||
/// Actions panel Playback Options. These are saved independently of an action library.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Actions {
|
||||
pub create_single_history_state: bool,
|
||||
}
|
||||
|
||||
impl Default for Actions {
|
||||
fn default() -> Self {
|
||||
Self { create_single_history_state: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The History panel's History Options… (not part of Edit › Preferences in Photoshop either).
|
||||
/// Photoshop's snapshot options come with #3634.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -1104,6 +1117,7 @@ impl LayerMaskOverlay {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Preferences {
|
||||
pub actions: Actions,
|
||||
pub general: General,
|
||||
pub interface: Interface,
|
||||
pub workspace: Workspace,
|
||||
|
||||
@@ -282,12 +282,16 @@ impl Session {
|
||||
let keep_clean = st.keeps_clean(&before);
|
||||
#[cfg(any(test, debug_assertions))]
|
||||
let hint_before = before.clone();
|
||||
let key = self.coalesce_request.clone();
|
||||
let group = self.action_history.clone();
|
||||
let key = group.as_ref().map(|g| g.key.clone()).or_else(|| self.coalesce_request.clone());
|
||||
let label = group.as_ref().map_or(label, |g| g.label.as_str());
|
||||
let st = self.active_mut().ok_or(EngineError::NoDocument)?;
|
||||
let layers = st.layer_target();
|
||||
if !record {
|
||||
// Nothing to coalesce with: the next recorded step starts a state of its own.
|
||||
st.coalesce = None;
|
||||
if group.is_none() {
|
||||
st.coalesce = None;
|
||||
}
|
||||
} else if key.is_none() || st.coalesce != key || !st.history.can_undo() {
|
||||
st.history.set_current_layers(prior);
|
||||
st.history.record(label, before.clone(), layers);
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Public playback history semantics, independent of the Actions panel implementation.
|
||||
use photocraft_engine::{Session, actions_cmds::Action};
|
||||
use serde_json::json;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
|
||||
s.actions.list.push(Action::new(
|
||||
"Two layers",
|
||||
["First", "Second"].into_iter().map(|name| ("layer.new.layer".into(), json!({"name":name}))).collect(),
|
||||
));
|
||||
s
|
||||
}
|
||||
|
||||
/// Default playback is one named edit, including the complete Undo and Redo states.
|
||||
#[test]
|
||||
fn default_playback_is_one_named_history_state() {
|
||||
let mut s = session();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let count = s.active().unwrap().history.past_len();
|
||||
let result = s.execute("actions.play", json!({"action":"Two layers"})).unwrap();
|
||||
assert!(result.get("failed").is_none(), "{result}");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), count + 1);
|
||||
assert_eq!(s.active().unwrap().history.undo_label(), Some("Action: Two layers"));
|
||||
let after = s.active().unwrap().doc.clone();
|
||||
assert_eq!(after.layers.len(), before.layers.len() + 2);
|
||||
assert!(s.undo());
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len());
|
||||
assert_eq!(s.active().unwrap().history.redo_label(), Some("Action: Two layers"));
|
||||
assert!(s.redo());
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), after.layers.len());
|
||||
assert_eq!(s.active().unwrap().doc.layers.iter().map(|l| &l.name).collect::<Vec<_>>(), after.layers.iter().map(|l| &l.name).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// Disabling the persisted option retains the existing one-entry-per-step behavior.
|
||||
#[test]
|
||||
fn disabled_single_history_keeps_each_step() {
|
||||
let mut s = session();
|
||||
s.execute("actions.setHistory", json!({"singleState":false})).unwrap();
|
||||
let count = s.active().unwrap().history.past_len();
|
||||
let layers = s.active().unwrap().doc.layers.len();
|
||||
s.execute("actions.play", json!({"action":0})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), count + 2);
|
||||
assert!(s.undo());
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1);
|
||||
assert!(s.undo());
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), layers);
|
||||
}
|
||||
|
||||
/// Failure commits the completed prefix; an inner play uses its outer action's name and key.
|
||||
#[test]
|
||||
fn failures_and_nested_calls_keep_the_outer_history_entry() {
|
||||
let mut s = session();
|
||||
let layers = s.active().unwrap().doc.layers.len();
|
||||
s.actions.list.push(Action::new("Outer", vec![
|
||||
("layer.new.layer".into(), json!({"name":"Outer layer"})),
|
||||
("actions.play".into(), json!({"action":0})),
|
||||
("not.a.command".into(), json!({})),
|
||||
("layer.new.layer".into(), json!({"name":"Must not run"})),
|
||||
]));
|
||||
let before = s.active().unwrap().history.past_len();
|
||||
let result = s.execute("actions.play", json!({"action":"Outer"})).unwrap();
|
||||
assert_eq!(result["failed"]["step"], 2);
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), layers + 3);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), before + 1);
|
||||
assert_eq!(s.active().unwrap().history.undo_label(), Some("Action: Outer"));
|
||||
assert!(s.undo());
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), layers);
|
||||
assert!(s.redo());
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), layers + 3);
|
||||
}
|
||||
|
||||
/// No-op playback preserves redo, and separate plays never coalesce into one another.
|
||||
#[test]
|
||||
fn no_op_and_repeated_plays_preserve_history_boundaries() {
|
||||
let mut s = session();
|
||||
s.execute("actions.play", json!({"action":0})).unwrap();
|
||||
assert!(s.undo());
|
||||
let entries = s.active().unwrap().history.entries();
|
||||
let redo = s.active().unwrap().history.redo_label().map(str::to_owned);
|
||||
s.actions.list.push(Action::new("Empty", vec![]));
|
||||
s.execute("actions.play", json!({"action":"Empty"})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.entries(), entries);
|
||||
assert_eq!(s.active().unwrap().history.redo_label(), redo.as_deref());
|
||||
assert!(s.redo());
|
||||
let count = s.active().unwrap().history.past_len();
|
||||
let layers = s.active().unwrap().doc.layers.len();
|
||||
s.execute("actions.play", json!({"action":0})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), count + 1);
|
||||
assert!(s.undo());
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), layers);
|
||||
}
|
||||
|
||||
/// Older preference files default on; an explicit off survives the public save/load path.
|
||||
#[test]
|
||||
fn action_history_setting_is_persisted_and_rejects_wrong_types() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.prefs().actions.create_single_history_state);
|
||||
assert!(s.execute("actions.setHistory", json!({"singleState":"false"})).is_err());
|
||||
assert!(s.prefs().actions.create_single_history_state);
|
||||
s.execute("actions.setHistory", json!({"singleState":false})).unwrap();
|
||||
let mut restored = Session::new();
|
||||
assert!(restored.load_prefs_json(&s.prefs_to_json()).unwrap().is_empty());
|
||||
assert!(!restored.prefs().actions.create_single_history_state);
|
||||
restored.load_prefs_json("{}").unwrap();
|
||||
assert!(restored.prefs().actions.create_single_history_state);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod affinity;
|
||||
mod actions_single_history;
|
||||
mod artboard_export_names;
|
||||
mod atn_crystallize_cell_size;
|
||||
mod atn_reference_forms;
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
# Actions files (`.atn`)
|
||||
|
||||
## Action playback history
|
||||
|
||||
Actions create one history entry named `Action: <name>` by default. Nested plays
|
||||
share the outer action's entry, and a failing step keeps the completed prefix.
|
||||
`actions.setHistory {"singleState":false}` restores per-step history. The option
|
||||
is saved as `actions.createSingleHistoryState` in preferences and defaults to true
|
||||
when loading older preferences. It is separate from Playback Options' performance
|
||||
modes; the Playback Options dialog can use the same setting when #5212 lands.
|
||||
|
||||
PhotoCraft loads and saves action sets in the reference application's `.atn` format: Load Actions and
|
||||
Save Actions in the Actions panel menu, `actions.load` / `actions.save` for agents, and
|
||||
`photocraft batch --actions set.atn` on the command line. Reading and writing the file lives in
|
||||
|
||||
Reference in new issue
Block a user