From d84fa7955d260505378a1a596ec80d602036319d Mon Sep 17 00:00:00 2001 From: kotulsky <7805437+kotulsky@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:23:40 +0200 Subject: [PATCH] fix(actions): undo and redo action definition edits Keep action-definition history separate from document History and route Undo and Redo to the focused Actions panel. Preserve named calls and function-key bindings when restoring edits, checkpoint recorded steps, and return Undo to document edits after playback. Add regression coverage for reordering, deletion, renaming, recording, append, redo invalidation and keyboard routing without changing document pixels. --- crates/engine/src/actions_cmds.rs | 196 +++++++++++++++++++++++++++++- crates/ui-egui/src/actions.rs | 42 +++++++ crates/ui-egui/src/menus.rs | 6 + docs/control-protocol.md | 5 + 4 files changed, 243 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs index 348011f75d..e8a3be6368 100644 --- a/crates/engine/src/actions_cmds.rs +++ b/crates/engine/src/actions_cmds.rs @@ -75,6 +75,84 @@ pub struct ActionState { /// Bumped whenever `list` changes, so the preset store can skip unchanged writes. #[serde(skip)] pub rev: u64, + #[serde(skip)] + pub(crate) undo: Vec, + #[serde(skip)] + pub(crate) redo: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct ActionEdit { + list: Vec, + recording: Option<(usize, usize)>, + shortcuts: std::collections::BTreeMap, +} + +fn snapshot(s: &Session) -> ActionEdit { + let mut list = s.actions.list.clone(); + if let Some((_, idx)) = s.actions.recording { + let pending: Vec<_> = pending_steps(s, idx).cloned().collect(); + if let Some(action) = list.get_mut(idx) { + action.steps.extend(pending); + } + } + ActionEdit { + list, + recording: s.actions.recording.map(|(_, idx)| (s.journal.len(), idx)), + shortcuts: s.prefs().shortcuts.iter().filter(|(key, _)| key.starts_with(PLAY_SHORTCUT_PREFIX)).map(|(k, v)| (k.clone(), v.clone())).collect(), + } +} + +fn edit_action(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> Result, include_pending: bool) -> Result { + let mut before = snapshot(s); + if !include_pending { + before.list = s.actions.list.clone(); + } + let result = run(s, p)?; + if before.list != snapshot(s).list { + s.actions.undo.push(before); + if s.actions.undo.len() > 100 { + s.actions.undo.remove(0); + } + s.actions.redo.clear(); + } + Ok(result) +} + +pub fn can_undo(s: &Session) -> bool { + s.actions.playing == 0 && !s.actions.undo.is_empty() +} +pub fn can_redo(s: &Session) -> bool { + s.actions.playing == 0 && !s.actions.redo.is_empty() +} + +fn undo_edit(s: &mut Session, redo: bool) -> Result { + not_playing(s, if redo { "actions.redo" } else { "actions.undo" })?; + let current = snapshot(s); + let prior = if redo { s.actions.redo.pop() } else { s.actions.undo.pop() }; + let Some(prior) = prior else { return Ok(json!(false)) }; + if redo { + s.actions.undo.push(current); + } else { + s.actions.redo.push(current); + } + let old_names: std::collections::BTreeSet<_> = s.actions.list.iter().map(|a| a.name.as_str()).collect(); + let new_names: std::collections::BTreeSet<_> = prior.list.iter().map(|a| a.name.as_str()).collect(); + let changed_bindings: Vec<_> = old_names.symmetric_difference(&new_names).map(|name| format!("{PLAY_SHORTCUT_PREFIX}{name}")).collect(); + s.actions.list = prior.list; + s.actions.recording = s.actions.recording.and(prior.recording).map(|(_, idx)| (s.journal.len(), idx)); + if !changed_bindings.is_empty() { + s.edit_prefs(|prefs| { + for key in changed_bindings { + prefs.shortcuts.remove(&key); + if let Some(value) = prior.shortcuts.get(&key) { + prefs.shortcuts.insert(key, value.clone()); + } + } + }); + } + s.actions.touch(); + Ok(json!(true)) } impl ActionState { @@ -528,6 +606,26 @@ fn rename(s: &mut Session, p: &Value) -> Result { pub fn specs() -> Vec { vec![ + CommandSpec { + id: "actions.undo", + label: "Undo Action Edit", + menu: &[], + shortcut: None, + params: "{} → bool. Undo an action definition edit without changing the document.", + enabled: |s| if can_undo(s) { Ok(()) } else { Err("nothing to undo".into()) }, + run: |s, _| undo_edit(s, false), + journal: false, + }, + CommandSpec { + id: "actions.redo", + label: "Redo Action Edit", + menu: &[], + shortcut: None, + params: "{} → bool. Redo an action definition edit without changing the document.", + enabled: |s| if can_redo(s) { Ok(()) } else { Err("nothing to redo".into()) }, + run: |s, _| undo_edit(s, true), + journal: false, + }, CommandSpec { id: "actions.move", label: "Move Action or Step", @@ -535,7 +633,7 @@ pub fn specs() -> Vec { shortcut: None, params: r##"{"action":name|index, "step":index?, "to":index}. Move a step within its action, or the action itself. to is the final zero-based index. Pending recorded steps can be moved."##, enabled: always, - run: move_item, + run: |s, p| edit_action(s, p, move_item, true), journal: false, }, CommandSpec { @@ -565,7 +663,7 @@ pub fn specs() -> Vec { shortcut: None, params: r##"{"name":str? (new action, default "Action N")} or {"action":name|index} (append) → {action, index}"##, enabled: always, - run: record, + run: |s, p| edit_action(s, p, record, true), journal: false, }, CommandSpec { @@ -575,7 +673,7 @@ pub fn specs() -> Vec { shortcut: None, params: "{} → {action, steps:count} (steps recorded since actions.record, queries and action-editing commands omitted)", enabled: always, - run: stop, + run: |s, p| edit_action(s, p, stop, false), journal: false, }, CommandSpec { @@ -595,7 +693,7 @@ pub fn specs() -> Vec { shortcut: None, params: r##"{"action":name|index, "step":index?} → {deleted:name} or {action, deletedStep, steps:count}. step is 0-based, including pending recorded steps. Whole-action deletion is refused while recording."##, enabled: always, - run: delete, + run: |s, p| edit_action(s, p, delete, true), journal: false, }, CommandSpec { @@ -605,7 +703,7 @@ pub fn specs() -> Vec { shortcut: None, params: r##"{"action":name|index, "step":index?, "enabled":bool?} → {action, disabled:[step…]}. Switch one 0-based step (including pending recorded steps) on or off for playback, Batch and droplets; omitted enabled flips it. Without step, switch every step: on unless all already are, or as enabled says."##, enabled: always, - run: toggle, + run: |s, p| edit_action(s, p, toggle, true), journal: false, }, CommandSpec { @@ -615,7 +713,7 @@ pub fn specs() -> Vec { shortcut: None, params: r##"{"action":name|index, "name":str} → {action, index}. The name must not be empty or whitespace-only and must be unique. Nested Play Action steps and the action's function key follow the rename."##, enabled: always, - run: rename, + run: |s, p| edit_action(s, p, rename, true), journal: false, }, ] @@ -673,6 +771,92 @@ mod tests { assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1], "rejected toggles change nothing"); } + #[test] + fn recording_and_appending_steps_can_be_undone_without_restarting_recording() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("actions.record", json!({"name": "A"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + s.execute("actions.record", json!({"action": "A"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert_eq!(s.actions.list[0].steps.len(), 2); + s.execute("actions.undo", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps.len(), 1); + assert!(s.actions.recording.is_none()); + s.execute("actions.redo", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps.len(), 2); + assert!(s.actions.recording.is_none()); + assert_eq!(s.active().unwrap().doc, doc); + } + + #[test] + fn definition_edits_undo_redo_without_touching_document_or_journal() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.actions.list.push(Action { + name: "A".into(), + steps: vec![("layer.new.layer".into(), json!({})), ("select.all".into(), json!({}))], + disabled: Default::default(), + }); + s.actions.list.push(Action { name: "Caller".into(), steps: vec![("actions.play".into(), json!({"action": "A"}))], disabled: Default::default() }); + s.edit_prefs(|p| { + p.shortcuts.insert("actions.play:A".into(), "F6".into()); + }); + let before = s.actions.list.clone(); + let doc = s.active().unwrap().doc.clone(); + let journal = s.journal.clone(); + s.execute("actions.move", json!({"action": "A", "step": 0, "to": 1})).unwrap(); + s.execute("actions.delete", json!({"action": "A", "step": 0})).unwrap(); + s.execute("actions.rename", json!({"action": "A", "name": "B"})).unwrap(); + let after = s.actions.list.clone(); + for _ in 0..3 { + s.execute("actions.undo", json!({})).unwrap(); + } + assert_eq!(s.actions.list, before); + assert_eq!(s.prefs().shortcuts.get("actions.play:A").map(String::as_str), Some("F6")); + assert!(!s.prefs().shortcuts.contains_key("actions.play:B")); + for _ in 0..3 { + s.execute("actions.redo", json!({})).unwrap(); + } + assert_eq!(s.actions.list, after); + assert_eq!(s.active().unwrap().doc, doc); + assert_eq!(s.journal, journal); + s.execute("actions.undo", json!({})).unwrap(); + s.execute("actions.delete", json!({"action": "Caller"})).unwrap(); + assert!(!can_redo(&s)); + } + + #[test] + fn enabled_step_edits_undo_and_invalidate_redo() { + let mut s = Session::new(); + s.actions.list.push(Action::new("A", vec![("select.all".into(), json!({}))])); + s.execute("actions.toggle", json!({"action": "A", "step": 0})).unwrap(); + assert!(s.actions.list[0].disabled.contains(&0)); + s.execute("actions.undo", json!({})).unwrap(); + assert!(s.actions.list[0].disabled.is_empty()); + s.execute("actions.redo", json!({})).unwrap(); + assert!(s.actions.list[0].disabled.contains(&0)); + s.execute("actions.undo", json!({})).unwrap(); + s.execute("actions.toggle", json!({"action": "A"})).unwrap(); + assert!(!can_redo(&s)); + } + + #[test] + fn undo_pending_step_deletion_does_not_duplicate_recording() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("actions.record", json!({"name": "A"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("actions.delete", json!({"action": "A", "step": 0})).unwrap(); + s.execute("actions.undo", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps.len(), 1); + assert_eq!(s.active().unwrap().doc.layers.len(), 2); + } + #[test] fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rs index cf06940224..c0381a15ae 100644 --- a/crates/ui-egui/src/actions.rs +++ b/crates/ui-egui/src/actions.rs @@ -22,6 +22,8 @@ pub struct ActionsUi { pub selected_step: Option, pub expanded: Vec, #[serde(skip)] + pub(crate) focused: bool, + #[serde(skip)] reveal_recording: Option<(usize, usize)>, /// The action whose name is being edited in place (double-click on its name). #[serde(skip)] @@ -88,6 +90,7 @@ pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, name: &str, shortcut: &st /// Replay edits synchronously, with view steps handled by the shell in the same order. /// Engine steps keep the headless action semantics (no dialogs or background jobs). pub(crate) fn play(app: &mut PhotocraftApp, params: &Value) -> Result { + app.ui.actions.focused = false; let (action, from) = actions_cmds::playback_plan(&app.session, params).map_err(|e| e.to_string())?; let recording = actions_cmds::begin_playback(&mut app.session, &action).map_err(|e| e.to_string())?; let mut ran = 0u64; @@ -317,8 +320,22 @@ fn rename_action(app: &mut PhotocraftApp, index: usize, name: String) { } } +pub(crate) fn undo_command(app: &PhotocraftApp, id: &str) -> Option<&'static str> { + if !app.ui.actions.focused { + return None; + } + match id { + "edit.undo" => Some("actions.undo"), + "edit.redo" => Some("actions.redo"), + _ => None, + } +} + pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); + if ui.input(|i| i.pointer.any_pressed()) { + app.ui.actions.focused = ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| ui.max_rect().contains(p)); + } let recording = app.session.actions.recording; let rows: Vec<_> = app.session.actions.list.iter().enumerate().map(|(i, a)| (a.name.clone(), visible_steps(app, i), a.disabled.clone())).collect(); if app @@ -541,6 +558,31 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { mod tests { use super::*; + #[test] + fn actions_shortcut_undo_and_redo_edit_script_without_undoing_pixels() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.session.actions.list.push(Action { name: "A".into(), steps: vec![("select.all".into(), json!({}))], disabled: Default::default() }); + let doc = app.session.active().unwrap().doc.clone(); + let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(3); + h.get_by_label("A").click(); + h.run_steps(3); + assert!(h.state().ui.actions.focused); + h.state_mut().run("actions.delete", json!({"action": "A", "step": 0})).unwrap(); + let ctx = egui::Context::default(); + crate::shortcut_dispatch::dispatch(h.state_mut(), &ctx, "edit.undo"); + assert_eq!(h.state().session.actions.list[0].steps.len(), 1); + assert_eq!(h.state().session.active().unwrap().doc, doc); + crate::shortcut_dispatch::dispatch(h.state_mut(), &ctx, "edit.redo"); + assert!(h.state().session.actions.list[0].steps.is_empty()); + h.state_mut().ui.actions.focused = false; + crate::shortcut_dispatch::dispatch(h.state_mut(), &ctx, "edit.undo"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 1); + } + #[test] fn double_clicking_an_action_name_renames_it_in_place() { use egui_kittest::{Harness, kittest::Queryable}; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2bc1829e9f..d265c27fc0 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -157,6 +157,9 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va /// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it. pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { + if let Some(command) = crate::actions::undo_command(app, id) { + return app.run(command, params); + } if id == "ui.symmetryTransform" { return crate::symmetry_ui::begin(app).map(|_| Value::Null); } @@ -604,6 +607,9 @@ fn open_path(app: &mut PhotocraftApp, path: &str) -> Result { } pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { + if let Some(command) = crate::actions::undo_command(app, id) { + return photocraft_engine::commands::find(command).is_some_and(|spec| (spec.enabled)(&app.session).is_ok()); + } if id == "ui.symmetryTransform" { return crate::symmetry_ui::can_transform(app); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 62dfe71451..dfc6d2c53b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -117,6 +117,11 @@ store expose and persist the same setting; scripts keep using canonical command | `actions.toggle` | `{"action": name or index, "step": index?, "enabled": bool?}` → `{action, disabled}`. Switches one 0-based step (pending recorded steps included) on or off; omitting `enabled` flips it. Without `step`, switches every step: on unless all already are. Playback, Batch and droplets skip steps that are off. In the desktop panel, click a step's check box | | `actions.rename` | `{"action": name or index, "name": str}` → `{action, index}`. Empty, whitespace-only or duplicate names are rejected and keep the old name. Nested `actions.play` steps that call the action by name and its function key follow the new name. In the desktop panel, double-click an action's name to rename it in place (Enter commits, Esc cancels) | +`actions.undo` and `actions.redo` undo/redo edits to action definitions (reordering, +deleting, renaming, creating and recording), independently of document History. Ctrl/Cmd+Z and +Ctrl/Cmd+Shift+Z target this history while the Actions panel has focus. Playing an +action returns Undo to document edits. + The Actions panel shows replayable steps immediately while recording. Click an individual step to select it, then use the trash button to remove that step; selecting the action heading instead targets the whole action. Step deletion also works during recording