PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Actions: edit steps, nested action calls, F-key shortcuts and recorded Fit on Screen (#1093)
Wil3091a2843c45
diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rsindex a97cf85b1..30fe5c7d6 100644--- a/crates/engine/src/actions_cmds.rs+++ b/crates/engine/src/actions_cmds.rs@@ -3,8 +3,8 @@//!//! The list lives on [`Session`] so the panel, the CLI, the control channel and MCP share one//! copy. Recording copies replayable journal entries (commands whose [`CommandSpec::journal`] is-//! set, except `actions.*` and the already-expanded `edit.transform.again`) into an action.-//! Playback runs those steps with [`Session::execute`]+//! set, except action-editing commands and the already-expanded `edit.transform.again`) into an+//! action. Playback runs those steps with [`Session::execute`]//! and stops at the first error, leaving one history step per step that ran.//!//! An untrusted session installs [`Session::authorize`]. `actions.play` calls it for every nested@@ -45,9 +45,12 @@ pub struct ActionState {/// Journal length when recording started, and the action index being recorded into.#[serde(skip)]pub recording: Option<(usize, usize)>,- /// Nesting depth of `actions.play`. Greater than zero refuses another play.+ /// Nesting depth of `actions.play`, bounded by the playback stack limit.#[serde(skip)]pub playing: u8,+ /// Active action names, for cycle detection in engine and desktop playback.+ #[serde(skip)]+ pub playback_stack: Vec<String>,/// Bumped whenever `list` changes, so the preset store can skip unchanged writes.#[serde(skip)]pub rev: u64,@@ -59,10 +62,35 @@ impl ActionState {}}-/// A journal entry worth replaying: omit Actions commands and the already-expanded Again wrapper.+/// Replay commands and named action calls, excluding edits to the action definitions and the+/// already-expanded Again wrapper.pub fn replayable(id: &str) -> bool {// Again journals its concrete transform too; recording the wrapper would replay it twice.- !id.starts_with("actions.") && id != "edit.transform.again" && crate::commands::find(id).is_some_and(|c| c.journal)+ id == "actions.play"+ || (!id.starts_with("actions.") && id != "edit.transform.again" && (shell_view_command(id) || crate::commands::find(id).is_some_and(|c| c.journal)))+}++/// View-only menu commands recorded by the desktop shell. Headless playback reports+/// them as unsupported instead of silently dropping them.+pub fn shell_view_command(id: &str) -> bool {+ matches!(id, "view.fitOnScreen" | "view.actualPixels" | "view.zoomIn" | "view.zoomOut")+}++/// Shared validation for headless and shell playback. Does not start playback.+pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> {+ if s.actions.playing > 0 && s.actions.playback_stack.is_empty() {+ return Err(bad("actions.play", "an action is already playing"));+ }+ let idx = resolve(&s.actions.list, p, "actions.play")?;+ let action = s.actions.list.get(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?;+ if s.actions.playback_stack.iter().any(|name| name == &action.name) || s.actions.recording.is_some_and(|(_, i)| i == idx) {+ return Err(bad("actions.play", format!("recursive action call to `{}`", action.name)));+ }+ if s.actions.playback_stack.len() >= 16 {+ return Err(bad("actions.play", "action nesting exceeds 16 levels"));+ }+ let from = from_step(p, action.steps.len())?;+ Ok((action, from))}fn always(_: &Session) -> std::result::Result<(), String> {@@ -130,6 +158,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {}fn record(s: &mut Session, p: &Value) -> Result<Value> {+ not_playing(s, "actions.record")?;if s.actions.recording.is_some() {return Err(bad("actions.record", "already recording; stop first"));}@@ -137,11 +166,20 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {resolve(&s.actions.list, p, "actions.record")?} else {let name = match p.get("name") {- None | Some(Value::Null) => format!("Action {}", s.actions.list.len() + 1),+ None | Some(Value::Null) => {+ let mut n = s.actions.list.len().saturating_add(1);+ while s.actions.list.iter().any(|a| a.name == format!("Action {n}")) {+ n = n.checked_add(1).ok_or_else(|| bad("actions.record", "cannot allocate a unique action name"))?;+ }+ format!("Action {n}")+ }Some(Value::String(n)) if !n.is_empty() => n.clone(),Some(Value::String(_)) => return Err(bad("actions.record", "\"name\" is empty")),Some(_) => return Err(bad("actions.record", "\"name\" must be a string")),};+ if s.actions.list.iter().any(|action| action.name == name) {+ return Err(bad("actions.record", "an action with this name already exists"));+ }s.actions.list.push(Action { name, steps: Vec::new() });s.actions.touch();s.actions.list.len() - 1@@ -151,21 +189,35 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"action": name, "index": idx}))}-fn stop(s: &mut Session, _p: &Value) -> Result<Value> {- let Some((from, idx)) = s.actions.recording else {- return Err(bad("actions.stop", "not recording"));- };+/// Replayable journal entries not yet committed to this action while recording.+pub fn pending_steps(s: &Session, action: usize) -> impl Iterator<Item = &(String, Value)> {+ let from = s.actions.recording.filter(|(_, i)| *i == action).map_or(s.journal.len(), |(from, _)| from);+ s.journal.iter().skip(from).filter(|(id, _)| replayable(id))+}++fn flush_recording(s: &mut Session) -> Result<()> {+ let Some((_, idx)) = s.actions.recording else { return Ok(()) };if idx >= s.actions.list.len() {return Err(bad("actions.stop", "the action being recorded no longer exists"));}- let steps: Vec<(String, Value)> = s.journal.iter().skip(from).filter(|(id, _)| replayable(id)).cloned().collect();+ let steps: Vec<_> = pending_steps(s, idx).cloned().collect();+ s.actions.recording = Some((s.journal.len(), idx));+ if !steps.is_empty() {+ s.actions.list[idx].steps.extend(steps);+ s.actions.touch();+ }+ Ok(())+}++fn stop(s: &mut Session, _p: &Value) -> Result<Value> {+ not_playing(s, "actions.stop")?;+ let Some((_, idx)) = s.actions.recording else {+ return Err(bad("actions.stop", "not recording"));+ };+ flush_recording(s)?;s.actions.recording = None;- let action = &mut s.actions.list[idx];- action.steps.extend(steps);- let name = action.name.clone();- let n = action.steps.len();- s.actions.touch();- Ok(json!({"action": name, "steps": n}))+ let action = &s.actions.list[idx];+ Ok(json!({"action": action.name, "steps": action.steps.len()}))}fn run_recorded(s: &mut Session, steps: &[(String, Value)], from: usize) -> (u64, Option<Value>) {@@ -179,7 +231,13 @@ fn run_recorded(s: &mut Session, steps: &[(String, Value)], from: usize) -> (u64break;}match s.execute(id, params.clone()) {- Ok(_) => ran += 1,+ Ok(value) => {+ if let Some(error) = nested_failure(id, &value) {+ failed = Some(json!({"step": i, "id": id, "error": error}));+ break;+ }+ ran += 1;+ }Err(e) => {failed = Some(json!({"step": i, "id": id, "error": e.to_string()}));break;@@ -189,27 +247,134 @@ fn run_recorded(s: &mut Session, steps: &[(String, Value)], from: usize) -> (u64(ran, failed)}-fn play(s: &mut Session, p: &Value) -> Result<Value> {- if s.actions.playing > 0 {- return Err(bad("actions.play", "an action is already playing"));- }- let idx = resolve(&s.actions.list, p, "actions.play")?;- let action = s.actions.list[idx].clone();- let from = from_step(p, action.steps.len())?;+/// Suspend recording while a called action executes. Keep its commands in the journal+/// for diagnostics, but record just the named call in the parent action.+pub fn begin_playback(s: &mut Session, action: &Action) -> Result<Option<(usize, usize)>> {+ flush_recording(s)?;+ let recording = s.actions.recording.take();s.actions.playing = s.actions.playing.saturating_add(1);- let (ran, failed) = run_recorded(s, &action.steps, from);+ s.actions.playback_stack.push(action.name.clone());+ Ok(recording)+}++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 let Some((_, idx)) = recording {+ s.actions.recording = Some((s.journal.len(), idx));+ let mut params = json!({"action": action.name});+ if from > 0 {+ params["from"] = json!(from);+ }+ s.journal.push(("actions.play".into(), params));+ }+}++/// Nested playback returns a structured failure even though the command itself succeeded.+/// Promote it to the caller's failed step so no later parent steps run after a child fails.+pub fn nested_failure(id: &str, value: &Value) -> Option<String> {+ (id == "actions.play").then(|| value.get("failed")).flatten().map(|failure| {+ format!(+ "action `{}` step {} failed: {}",+ value.get("action").and_then(Value::as_str).unwrap_or(""),+ failure.get("step").and_then(Value::as_u64).unwrap_or(0).saturating_add(1),+ failure.get("error").and_then(Value::as_str).unwrap_or("unknown error")+ )+ })+}++fn play(s: &mut Session, p: &Value) -> Result<Value> {+ let (action, from) = playback_plan(s, p)?;+ let recording = begin_playback(s, &action)?;+ let (ran, failed) = run_recorded(s, &action.steps, from);+ finish_playback(s, recording, &action, from);Ok(match failed {Some(f) => json!({"action": action.name, "ran": ran, "failed": f}),None => json!({"action": action.name, "ran": ran}),})}+fn not_playing(s: &Session, cmd: &str) -> Result<()> {+ if s.actions.playing > 0 { Err(bad(cmd, "cannot edit actions during playback")) } else { Ok(()) }+}++/// Move to a final zero-based index, either in an action's steps or in the action list.+fn move_item(s: &mut Session, p: &Value) -> Result<Value> {+ not_playing(s, "actions.move")?;+ let idx = resolve(&s.actions.list, p, "actions.move")?;+ let index = |key: &str| -> Result<usize> {+ p.get(key)+ .and_then(Value::as_u64)+ .and_then(|n| usize::try_from(n).ok())+ .ok_or_else(|| bad("actions.move", format!("{key} must be a non-negative integer")))+ };+ let to = index("to")?;+ if p.get("step").is_some() {+ let step = index("step")?;+ let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count());+ if step >= len || to >= len {+ return Err(bad("actions.move", "step or destination is out of range"));+ }+ if s.actions.recording.is_some_and(|(_, i)| i == idx) {+ flush_recording(s)?;+ }+ let action = &mut s.actions.list[idx];+ let moved = action.steps.remove(step);+ action.steps.insert(to, moved);+ let result = json!({"action": action.name, "step": to});+ s.actions.touch();+ Ok(result)+ } else {+ if to >= s.actions.list.len() {+ return Err(bad("actions.move", "destination is out of range"));+ }+ let moved = s.actions.list.remove(idx);+ let result = json!({"action": moved.name, "index": to});+ s.actions.list.insert(to, moved);+ if let Some((_, recording)) = s.actions.recording.as_mut() {+ *recording = moved_index(*recording, idx, to);+ }+ s.actions.touch();+ Ok(result)+ }+}++/// Follow a selected/recording row when a list item is moved.+pub fn moved_index(index: usize, from: usize, to: usize) -> usize {+ if index == from {+ to+ } else if from < index && index <= to {+ index - 1+ } else if to <= index && index < from {+ index + 1+ } else {+ index+ }+}+fn delete(s: &mut Session, p: &Value) -> Result<Value> {+ not_playing(s, "actions.delete")?;+ let idx = resolve(&s.actions.list, p, "actions.delete")?;+ if let Some(step) = p.get("step") {+ let step = step.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("actions.delete", "step must be a non-negative integer"))?;+ let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count());+ if step >= len {+ return Err(bad("actions.delete", "step is out of range"));+ }+ // Commit pending entries before editing the action; never erase the command+ // journal or undo the edit that produced the deleted recording step.+ if s.actions.recording.is_some_and(|(_, i)| i == idx) {+ flush_recording(s)?;+ }+ let action = &mut s.actions.list[idx];+ action.steps.remove(step);+ let result = json!({"action": action.name, "deletedStep": step, "steps": action.steps.len()});+ s.actions.touch();+ return Ok(result);+ }if s.actions.recording.is_some() {- return Err(bad("actions.delete", "stop recording first"));+ return Err(bad("actions.delete", "stop recording before deleting an action"));}- let idx = resolve(&s.actions.list, p, "actions.delete")?;let name = s.actions.list.remove(idx).name;s.actions.touch();Ok(json!({"deleted": name}))@@ -217,6 +382,16 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {pub fn specs() -> Vec<CommandSpec> {vec![+ CommandSpec {+ id: "actions.move",+ label: "Move Action or Step",+ menu: &[],+ 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,+ journal: false,+ },CommandSpec {id: "actions.list",label: "List Actions",@@ -252,7 +427,7 @@ pub fn specs() -> Vec<CommandSpec> {label: "Stop Recording",menu: &[],shortcut: None,- params: "{} → {action, steps:count} (steps recorded since actions.record, queries and actions.* omitted)",+ params: "{} → {action, steps:count} (steps recorded since actions.record, queries and action-editing commands omitted)",enabled: always,run: stop,journal: false,@@ -262,7 +437,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. Stops at the first error (the command still returns ok, with failed set) and leaves one history step per step that ran. Refuses to play while a play is already running. 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. 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."##,enabled: always,run: play,journal: false,@@ -272,7 +447,7 @@ pub fn specs() -> Vec<CommandSpec> {label: "Delete Action",menu: &[],shortcut: None,- params: r##"{"action":name|index} → {deleted:name}. Refused while recording."##,+ 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,journal: false,@@ -426,7 +601,7 @@ mod tests {let r = s.execute("actions.play", json!({"action": "Loop"})).unwrap();assert_eq!(r["ran"], 0);assert_eq!(r["failed"]["id"], "actions.play");- assert!(r["failed"]["error"].as_str().unwrap().contains("already playing"), "{r}");+ assert!(r["failed"]["error"].as_str().unwrap().contains("recursive action"), "{r}");assert_eq!(s.actions.playing, 0);}@@ -472,6 +647,158 @@ mod tests {assert!(s.execute("actions.get", json!({"action": "Grow"})).is_err());}+ #[test]+ fn delete_one_step_while_recording_keeps_journal_and_remaining_steps() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ s.execute("actions.record", json!({"name": "Edit"})).unwrap();+ s.execute("layer.new.layer", json!({"name": "Kept"})).unwrap();+ s.execute("layer.new.layer", json!({"name": "Removed"})).unwrap();+ let journal = s.journal.clone();+ let rev = s.actions.rev;+ let before = s.actions.clone();+ for step in [json!(-1), json!(2), json!(0.5), json!(null), json!("0"), json!(u64::MAX)] {+ assert!(s.execute("actions.delete", json!({"action": 0, "step": step})).is_err());+ assert_eq!(s.actions, before, "invalid deletion is atomic");+ }+ assert_eq!(pending_steps(&s, 0).count(), 2);+ let result = s.execute("actions.delete", json!({"action": 0, "step": 1})).unwrap();+ assert_eq!(result["steps"], 1);+ assert_eq!(s.journal, journal, "deleting a recording does not erase executed commands");+ assert_eq!(s.active().unwrap().doc.layers.len(), 3, "it does not undo document edits");+ assert!(s.actions.recording.is_some());+ assert!(s.actions.rev > rev);+ s.execute("layer.new.layer", json!({"name": "After"})).unwrap();+ s.execute("actions.stop", json!({})).unwrap();+ assert_eq!(s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect::<Vec<_>>(), ["Kept", "After"]);+ s.execute("actions.delete", json!({"action": "Edit", "step": 0})).unwrap();+ assert_eq!(s.actions.list[0].steps[0].1["name"], "After");+ let saved = serde_json::to_string(&s.actions.list).unwrap();+ s.actions.list = serde_json::from_str(&saved).unwrap();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ assert_eq!(s.execute("actions.play", json!({"action": 0})).unwrap()["ran"], 1);+ assert_eq!(s.active().unwrap().doc.layers[1].name, "After");+ s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap();+ assert_eq!(s.actions.list.len(), 1, "an empty action still exists");+ assert!(s.actions.list[0].steps.is_empty());+ }++ #[test]+ fn nested_call_records_one_named_step_and_tracks_child_edits() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();+ s.actions.list.push(Action { name: "Child".into(), steps: vec![("layer.new.layer".into(), json!({"name": "Child layer"}))] });+ s.execute("actions.record", json!({"name": "Parent"})).unwrap();+ s.execute("layer.new.layer", json!({"name": "Before"})).unwrap();+ s.execute("actions.play", json!({"action": 0})).unwrap();+ assert_eq!(pending_steps(&s, 1).cloned().collect::<Vec<_>>(), [("actions.play".into(), json!({"action": "Child"}))]);+ s.execute("layer.new.layer", json!({"name": "After"})).unwrap();+ s.execute("actions.stop", json!({})).unwrap();+ assert_eq!(s.actions.list[1].steps.iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["layer.new.layer", "actions.play", "layer.new.layer"]);+ s.actions.list[0].steps.push(("layer.new.layer".into(), json!({"name": "Added later"})));+ s.execute("actions.move", json!({"action": "Child", "to": 1})).unwrap();+ let saved = serde_json::to_string(&s.actions.list).unwrap();+ s.actions.list = serde_json::from_str(&saved).unwrap();+ s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();+ let result = s.execute("actions.play", json!({"action": "Parent"})).unwrap();+ assert!(result.get("failed").is_none(), "{result}");+ assert_eq!(+ s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::<Vec<_>>(),+ ["Before", "Child layer", "Added later", "After"]+ );+ assert!(s.actions.playback_stack.is_empty());+ }++ #[test]+ fn nested_failure_cycles_depth_and_authorization_stop_parent() {+ let mut s = Session::new();+ s.actions.list.push(Action {+ name: "A".into(),+ steps: vec![("actions.play".into(), json!({"action": "B"})), ("file.new".into(), json!({"width": 2,"height": 2}))],+ });+ s.actions.list.push(Action { name: "B".into(), steps: vec![("actions.play".into(), json!({"action": "A"}))] });+ let r = s.execute("actions.play", json!({"action": "A"})).unwrap();+ assert!(r["failed"]["error"].as_str().unwrap().contains("recursive"));+ assert!(s.documents().is_empty());+ s.actions.list[1].steps = vec![("file.new".into(), json!({"width": 2,"height": 2}))];+ s.authorize = Some(|id, _| if id == "file.new" { Err(EngineError::Other("denied nested file".into())) } else { Ok(()) });+ let r = s.execute("actions.play", json!({"action": "A"})).unwrap();+ assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested file"));+ assert!(s.documents().is_empty());+ s.authorize = None;+ s.actions.list.clear();+ for i in 0..17 {+ s.actions.list.push(Action {+ name: format!("N{i}"),+ steps: if i < 16 { vec![("actions.play".into(), json!({"action":format!("N{}", i + 1)}))] } else { vec![] },+ });+ }+ let r = s.execute("actions.play", json!({"action": "N0"})).unwrap();+ assert!(r["failed"]["error"].as_str().unwrap().contains("16 levels"));+ assert_eq!(s.actions.playing, 0);+ assert!(s.actions.playback_stack.is_empty());+ s.actions.list[15].steps.clear();+ assert!(s.execute("actions.play", json!({"action": "N0"})).unwrap().get("failed").is_none());+ }++ #[test]+ fn move_pending_steps_is_atomic_persists_and_changes_playback_order() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();+ s.execute("actions.record", json!({"name": "Order"})).unwrap();+ for name in ["One", "Two", "Three"] {+ s.execute("layer.new.layer", json!({"name": name})).unwrap();+ }+ let before = s.actions.clone();+ for params in [+ json!({"action":0,"step":0,"to":3}),+ json!({"action":0,"step":99,"to":0}),+ json!({"action":0,"step":0.5,"to":0}),+ json!({"action":0,"to":-1}),+ json!({"action":0,"to":null}),+ ] {+ assert!(s.execute("actions.move", params).is_err());+ assert_eq!(s.actions, before);+ }+ let journal = s.journal.clone();+ s.execute("actions.move", json!({"action":0,"step":0,"to":2})).unwrap();+ s.execute("actions.move", json!({"action":0,"step":1,"to":0})).unwrap();+ assert_eq!(s.journal, journal);+ s.execute("layer.new.layer", json!({"name":"Four"})).unwrap();+ s.execute("actions.stop", json!({})).unwrap();+ assert_eq!(s.actions.list[0].steps.iter().map(|st| st.1["name"].as_str().unwrap()).collect::<Vec<_>>(), ["Three", "Two", "One", "Four"]);+ s.execute("file.new", json!({"width":4,"height":4})).unwrap();+ s.execute("actions.play", json!({"action":0})).unwrap();+ assert_eq!(s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::<Vec<_>>(), ["Three", "Two", "One", "Four"]);+ }++ #[test]+ fn new_names_do_not_collide_with_named_calls() {+ let mut s = Session::new();+ s.actions.list.push(Action { name: "Action 2".into(), steps: vec![] });+ assert_eq!(s.execute("actions.record", json!({})).unwrap()["action"], "Action 3");+ s.execute("actions.stop", json!({})).unwrap();+ assert!(s.execute("actions.record", json!({"name":"Action 2"})).is_err());+ assert!(s.actions.recording.is_none());+ }++ #[test]+ fn moving_action_keeps_recording_attached_to_it() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width":4,"height":4})).unwrap();+ for name in ["A", "B", "C"] {+ s.actions.list.push(Action { name: name.into(), steps: vec![] });+ }+ s.execute("actions.record", json!({"action":"B"})).unwrap();+ s.execute("layer.new.layer", json!({"name":"before"})).unwrap();+ s.execute("actions.move", json!({"action":"B","to":2})).unwrap();+ s.execute("actions.move", json!({"action":"A","to":2})).unwrap();+ s.execute("layer.new.layer", json!({"name":"after"})).unwrap();+ s.execute("actions.stop", json!({})).unwrap();+ assert_eq!(s.actions.list[1].name, "B");+ assert_eq!(s.actions.list[1].steps.len(), 2);+ }+#[test]fn bad_params_do_not_panic() {let mut s = Session::new();@@ -490,7 +817,7 @@ mod tests {json!({"from": -3}),json!({"action": "missing", "from": 4}),];- for id in ["actions.list", "actions.get", "actions.record", "actions.stop", "actions.play", "actions.delete"] {+ for id in ["actions.list", "actions.get", "actions.record", "actions.stop", "actions.play", "actions.delete", "actions.move"] {for p in &junk {let _ = s.execute(id, p.clone());}diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rsindex 63073f4a5..f43aece16 100644--- a/crates/ui-egui/src/actions.rs+++ b/crates/ui-egui/src/actions.rs@@ -1,7 +1,7 @@//! Actions panel: record and replay command sequences.//!//! The list and the recording flag live on the engine session (`actions.record` / `stop` /-//! `play` / `list` / `get` / `delete`), so the panel, the CLI and MCP share them. This module+//! `play` / `list` / `get` / `delete` / `move`), so the panel, the CLI and MCP share them. This module//! keeps only which row is selected and which rows are expanded.use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};@@ -19,11 +19,18 @@ use crate::theme::Tokens;#[serde(default)]pub struct ActionsUi {pub selected: Option<usize>,+ pub selected_step: Option<usize>,pub expanded: Vec<bool>,+ #[serde(skip)]+ reveal_recording: Option<(usize, usize)>,}fn label_of(id: &str) -> String {- photocraft_engine::commands::find(id).map(|c| c.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string())+ photocraft_engine::commands::find(id)+ .map(|c| c.label)+ .or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.1))+ .map(|label| label.trim_end_matches('…').to_string())+ .unwrap_or_else(|| id.to_string())}/// The selected action, or the first one when nothing is selected.@@ -38,23 +45,117 @@ pub fn action_steps(action: &Action) -> Vec<Value> {action.steps.iter().map(|(id, p)| json!([id, p])).collect()}-fn begin_recording(app: &mut PhotocraftApp) {+/// Named action bindings use the existing persisted shortcut overrides. Keeping the+/// name in the key means selecting or deleting another row cannot retarget F6.+pub(crate) const SHORTCUT_PREFIX: &str = "actions.play:";++pub(crate) fn shortcut_id(name: &str) -> String {+ format!("{SHORTCUT_PREFIX}{name}")+}++pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, name: &str, shortcut: &str) -> Result<Value, String> {+ let id = shortcut_id(name);+ let mut set = serde_json::Map::new();+ // A function key belongs to only one action. Ordinary menu bindings remain+ // intact and become available again when the action binding is removed.+ for (other, assigned) in &app.session.prefs().shortcuts {+ if other.starts_with(SHORTCUT_PREFIX) && other != &id && assigned == shortcut && !shortcut.is_empty() {+ set.insert(other.clone(), json!(""));+ }+ }+ set.insert(id, json!(shortcut));+ app.run("edit.keyboardShortcuts", json!({"set": set, "allowUnknown": true, "removeConflicts": false}))+}++/// 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<Value, String> {+ 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;+ let mut failed = None;+ for (i, (id, p)) in action.steps.iter().enumerate().skip(from) {+ let result = (|| {+ if let Some(auth) = app.session.authorize {+ auth(id, p).map_err(|e| e.to_string())?;+ }+ if id == "actions.play" {+ play(app, p)+ } else if actions_cmds::shell_view_command(id) {+ app.sync_views();+ app.run(id, p.clone())+ } else {+ app.session.execute(id, p.clone()).map_err(|e| e.to_string())+ }+ })();+ match result {+ Ok(value) => {+ if let Some(error) = actions_cmds::nested_failure(id, &value) {+ failed = Some(json!({"step": i, "id": id, "error": error}));+ break;+ }+ ran += 1;+ }+ Err(error) => {+ failed = Some(json!({"step": i, "id": id, "error": error}));+ break;+ }+ }+ }+ actions_cmds::finish_playback(&mut app.session, recording, &action, from);+ Ok(match failed {+ Some(f) => json!({"action": action.name, "ran": ran, "failed": f}),+ None => json!({"action": action.name, "ran": ran}),+ })+}++/// Execute the actual menu command, not a synthetic keystroke. Fit is deferred+/// until canvas layout, so it uses the dimensions after all preceding action steps.+pub(crate) fn run_view(app: &mut PhotocraftApp, id: &str, params: Value) -> Result<Value, String> {+ app.sync_views();+ let i = app.session.active_index().ok_or("no document")?;+ let v = app.ui.views.get_mut(i).ok_or("no document view")?;+ v.fill_pending = false;+ match id {+ "view.fitOnScreen" => v.fit_pending = true,+ "view.zoomIn" => {+ v.fit_pending = false;+ v.zoom = crate::canvas::zoom_step(v.zoom, 1);+ }+ "view.zoomOut" => {+ v.fit_pending = false;+ v.zoom = crate::canvas::zoom_step(v.zoom, -1);+ }+ "view.actualPixels" => {+ v.fit_pending = false;+ v.zoom = 1.0;+ }+ _ => return Err(format!("unsupported view command: {id}")),+ }+ app.session.journal.push((id.into(), params));+ Ok(Value::Null)+}++fn begin_recording(app: &mut PhotocraftApp, append: bool) {if app.session.actions.recording.is_some() {return;}- let Ok(v) = app.run("actions.record", json!({})) else { return };+ let params = if append { app.ui.actions.selected.map_or(json!({}), |i| json!({"action": i})) } else { json!({}) };+ let Ok(v) = app.run("actions.record", params) else { return };let Some(i) = v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()) else { return };app.ui.actions.selected = Some(i);+ app.ui.actions.selected_step = None;if app.ui.actions.expanded.len() <= i {app.ui.actions.expanded.resize(i + 1, false);}app.ui.actions.expanded[i] = true;}-fn report_play(app: &mut PhotocraftApp, v: &Value) {+pub(crate) fn report_play(app: &mut PhotocraftApp, v: &Value) {let Some(failed) = v.get("failed").filter(|f| f.is_object()) else {let ran = v.get("ran").and_then(Value::as_u64).unwrap_or(0);app.ui.status = format!("Played {ran} steps");+ app.ui.status_error = false;return;};let step = failed.get("step").and_then(Value::as_u64).unwrap_or(0);@@ -64,32 +165,146 @@ fn report_play(app: &mut PhotocraftApp, v: &Value) {app.ui.status_error = true;}+fn visible_steps(app: &PhotocraftApp, action: usize) -> Vec<(String, Value)> {+ app.session.actions.list.get(action).into_iter().flat_map(|a| a.steps.iter()).chain(actions_cmds::pending_steps(&app.session, action)).cloned().collect()+}++fn step_label(id: &str, params: &Value) -> String {+ if id == "actions.play" {+ let target = params.get("action").map(|v| v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string())).unwrap_or_default();+ format!("{}: {target}", label_of(id))+ } else {+ label_of(id)+ }+}++#[derive(Clone, Copy)]+struct DragRow {+ action: usize,+ step: Option<usize>,+}++/// Drops use an insertion line, converted to the final index expected by actions.move.+fn drag_row(ui: &egui::Ui, response: &egui::Response, row: DragRow, t: &Tokens) -> Option<(DragRow, usize)> {+ response.dnd_set_drag_payload(row);+ let source = response.dnd_hover_payload::<DragRow>()?;+ if source.step.is_some() != row.step.is_some() || (source.step.is_some() && source.action != row.action) {+ return None;+ }+ let after = ui.input(|i| i.pointer.hover_pos().is_some_and(|p| p.y >= response.rect.center().y));+ let index = row.step.unwrap_or(row.action);+ let from = source.step.unwrap_or(source.action);+ let slot = index.saturating_add(usize::from(after));+ let to = if from < slot { slot.saturating_sub(1) } else { slot };+ let y = if after { response.rect.bottom() } else { response.rect.top() };+ ui.painter().line_segment([pos2(response.rect.left() + 22.0, y), pos2(response.rect.right(), y)], Stroke::new(2.0, t.accent));+ response.dnd_release_payload::<DragRow>().map(|source| (*source, to))+}++fn move_row(app: &mut PhotocraftApp, source: DragRow, to: usize) {+ let mut params = json!({"action": source.action, "to": to});+ if let Some(step) = source.step {+ params["step"] = json!(step);+ }+ if app.run("actions.move", params).is_err() {+ return;+ }+ if source.step.is_some() {+ app.ui.actions.selected = Some(source.action);+ app.ui.actions.selected_step = Some(to);+ } else {+ app.ui.actions.expanded.resize(app.session.actions.list.len(), false);+ if source.action < app.ui.actions.expanded.len() && to < app.ui.actions.expanded.len() {+ let expanded = app.ui.actions.expanded.remove(source.action);+ app.ui.actions.expanded.insert(to, expanded);+ }+ app.ui.actions.selected = Some(to);+ app.ui.actions.selected_step = None;+ }+}++fn delete_selection(app: &mut PhotocraftApp) {+ let Some(action) = app.ui.actions.selected else { return };+ let step = app.ui.actions.selected_step;+ let mut params = json!({"action": action});+ if let Some(step) = step {+ params["step"] = json!(step);+ }+ if app.run("actions.delete", params).is_err() {+ return;+ }+ // Clear selection after deletion so a second click cannot delete a different+ // step or unexpectedly fall back to deleting the entire action.+ app.ui.actions.selected = None;+ app.ui.actions.selected_step = None;+ if step.is_none() && action < app.ui.actions.expanded.len() {+ app.ui.actions.expanded.remove(action);+ }+}+pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());let recording = app.session.actions.recording;- let live = recording.map(|(from, _)| app.session.journal.iter().skip(from).filter(|(id, _)| actions_cmds::replayable(id)).count()).unwrap_or(0);- let rows: Vec<(String, Vec<String>)> =- app.session.actions.list.iter().map(|a| (a.name.clone(), a.steps.iter().map(|(id, _)| id.clone()).collect())).collect();- if app.ui.actions.selected.is_some_and(|i| i >= rows.len()) {+ let rows: Vec<_> = app.session.actions.list.iter().enumerate().map(|(i, a)| (a.name.clone(), visible_steps(app, i))).collect();+ if app+ .ui+ .actions+ .selected+ .is_some_and(|i| i >= rows.len() || app.ui.actions.selected_step.is_some_and(|step| rows.get(i).is_none_or(|row| step >= row.1.len())))+ {app.ui.actions.selected = None;+ app.ui.actions.selected_step = None;}if app.ui.actions.expanded.len() > rows.len() {app.ui.actions.expanded.truncate(rows.len());}let max_h = (ui.available_height() - 70.0).clamp(80.0, 320.0);let mut play_idx = None;+ let mut moved = None;+ let recording_row = recording.and_then(|(_, i)| rows.get(i).map(|(_, steps)| (i, steps.len())));+ let reveal = recording_row.filter(|row| app.ui.actions.reveal_recording != Some(*row));+ app.ui.actions.reveal_recording = recording_row;+ if let Some((i, _)) = reveal {+ app.ui.actions.expanded.resize(rows.len(), false);+ if let Some(expanded) = app.ui.actions.expanded.get_mut(i) {+ *expanded = true;+ }+ }egui::ScrollArea::vertical().id_salt("actions-rows").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {if rows.is_empty() {ui.label(egui::RichText::new(tl!("Record ● a sequence of edits, then play ▶ it on any document.")).color(t.text_faint).size(11.5));}+ if egui::DragAndDrop::has_payload_of_type::<DragRow>(ui.ctx()) {+ let clip = ui.clip_rect();+ if let Some(p) = ui.input(|i| i.pointer.hover_pos()).filter(|p| clip.contains(*p)) {+ let delta = if p.y < clip.top() + 22.0 {+ 8.0+ } else if p.y > clip.bottom() - 22.0 {+ -8.0+ } else {+ 0.0+ };+ if delta != 0.0 {+ ui.scroll_with_delta(vec2(0.0, delta));+ ui.ctx().request_repaint();+ }+ }+ }for (i, (name, steps)) in rows.iter().enumerate() {- let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click());- let sel = app.ui.actions.selected == Some(i);+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click_and_drag());+ if reveal == Some((i, 0)) {+ ui.scroll_to_rect(rect, Some(egui::Align::BOTTOM));+ }+ let sel = app.ui.actions.selected == Some(i) && app.ui.actions.selected_step.is_none();+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, sel, name));if sel {ui.painter().rect_filled(rect, 0.0, t.row_selected);} else if resp.hovered() {ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5));}+ if let Some(change) = drag_row(ui, &resp, DragRow { action: i, step: None }, &t) {+ moved = Some(change);+ }let expanded = app.ui.actions.expanded.get(i).copied().unwrap_or(false);let tri = Rect::from_center_size(pos2(rect.left() + 12.0, rect.center().y), vec2(8.0, 8.0));let pts =@@ -97,12 +312,17 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {ui.painter().add(egui::Shape::convex_polygon(pts, t.text_dim, Stroke::NONE));crate::icons::paint(ui, Rect::from_center_size(pos2(rect.left() + 30.0, rect.center().y), vec2(16.0, 16.0)), "play", 11.0, t.icon);let recording_this = recording.is_some_and(|(_, r)| r == i);- let nsteps = steps.len() + if recording_this { live } else { 0 };+ let nsteps = steps.len();ui.painter().text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, name, egui::FontId::proportional(12.0), t.text);ui.painter().text(pos2(rect.right() - 8.0, rect.center().y),Align2::RIGHT_CENTER,- format!("{nsteps} steps"),+ app.session+ .prefs()+ .shortcuts+ .get(&shortcut_id(name))+ .filter(|s| !s.is_empty())+ .map_or_else(|| format!("{nsteps} steps"), |key| format!("{key} · {nsteps} steps")),egui::FontId::proportional(11.0),t.text_faint,);@@ -111,6 +331,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}if resp.clicked() {app.ui.actions.selected = Some(i);+ app.ui.actions.selected_step = None;if resp.interact_pointer_pos().is_some_and(|p| p.x < rect.left() + 20.0) {if app.ui.actions.expanded.len() <= i {app.ui.actions.expanded.resize(i + 1, false);@@ -118,17 +339,49 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {app.ui.actions.expanded[i] = !expanded;}}+ resp.context_menu(|ui| {+ ui.label(tl!("Keyboard Shortcuts"));+ let current = app.session.prefs().shortcuts.get(&shortcut_id(name)).cloned().unwrap_or_default();+ for key in std::iter::once(String::new()).chain((1..=12).map(|n| format!("F{n}"))) {+ let label = if key.is_empty() { tl!("None").to_string() } else { key.clone() };+ if ui.selectable_label(current == key, label).clicked() {+ let _ = assign_shortcut(app, name, &key);+ ui.close();+ }+ }+ });if resp.double_clicked() {play_idx = Some(i);}if expanded {- for id in steps {- let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::hover());- ui.painter().text(pos2(r.left() + 44.0, r.center().y), Align2::LEFT_CENTER, label_of(id), egui::FontId::proportional(11.5), t.text_dim);+ for (step, (id, params)) in steps.iter().enumerate() {+ let (r, response) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click_and_drag());+ if reveal == Some((i, step + 1)) {+ ui.scroll_to_rect(r, Some(egui::Align::BOTTOM));+ }+ let label = step_label(id, params);+ let selected = app.ui.actions.selected == Some(i) && app.ui.actions.selected_step == Some(step);+ response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &label));+ if selected {+ ui.painter().rect_filled(r, 0.0, t.row_selected);+ } else if response.hovered() {+ ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5));+ }+ if let Some(change) = drag_row(ui, &response, DragRow { action: i, step: Some(step) }, &t) {+ moved = Some(change);+ }+ ui.painter().text(pos2(r.left() + 44.0, r.center().y), Align2::LEFT_CENTER, label, egui::FontId::proportional(11.5), t.text_dim);+ if response.clicked() {+ app.ui.actions.selected = Some(i);+ app.ui.actions.selected_step = Some(step);+ }}}}});+ if let Some((source, to)) = moved {+ move_row(app, source, to);+ }ui.add_space(4.0);ui.horizontal(|ui| {ui.spacing_mut().item_spacing.x = 2.0;@@ -142,24 +395,22 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}ui.painter().circle_filled(r.center(), 5.5, if recording_now { Color32::from_rgb(230, 60, 60) } else { t.icon });if rec.on_hover_text(tl!("Begin recording")).clicked() && !recording_now {- begin_recording(app);+ begin_recording(app, true);}if crate::icons::button(ui, "play", 24.0, false, tl!("Play selection")).clicked() {play_idx = app.ui.actions.selected;}if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new action")).clicked() && !recording_now {- begin_recording(app);- }- if crate::icons::button(ui, "trash", 24.0, false, tl!("Delete")).clicked()- && !recording_now- && let Some(i) = app.ui.actions.selected- && app.run("actions.delete", json!({"action": i})).is_ok()- {- if i < app.ui.actions.expanded.len() {- app.ui.actions.expanded.remove(i);- }- app.ui.actions.selected = None;+ begin_recording(app, false);}+ let can_delete = app.ui.actions.selected.is_some() && (!recording_now || app.ui.actions.selected_step.is_some());+ ui.add_enabled_ui(can_delete, |ui| {+ let response = crate::icons::button(ui, "trash", 24.0, false, tl!("Delete"));+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, can_delete, tl!("Delete")));+ if response.clicked() {+ delete_selection(app);+ }+ });});if let Some(i) = play_idx&& let Ok(v) = app.run("actions.play", json!({"action": i}))@@ -172,6 +423,190 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {mod tests {use super::*;+ #[test]+ fn recording_reveals_new_action_and_latest_step_in_a_long_panel() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width":4,"height":4})).unwrap();+ for i in 0..30 {+ app.session.actions.list.push(Action { name: format!("Existing {i}"), steps: vec![] });+ }+ let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state(|ui, app| panel(app, ui), app);+ h.run_steps(4);+ begin_recording(h.state_mut(), false);+ h.run_steps(20);+ let rect = h.get_by_label("Action 31").rect();+ assert!(rect.top() >= 0.0 && rect.bottom() <= 205.0, "new action visible: {rect:?}");+ for _ in 0..20 {+ h.state_mut().run("view.zoomOut", json!({})).unwrap();+ }+ h.state_mut().run("view.fitOnScreen", json!({})).unwrap();+ h.run_steps(20);+ let rect = h.get_by_label("Fit on Screen").rect();+ assert!(rect.top() >= 0.0 && rect.bottom() <= 205.0, "latest step visible: {rect:?}");+ }++ #[test]+ fn drag_steps_and_action_headers_reorders_and_keeps_selection() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.actions.list.push(Action {+ name: "First".into(),+ steps: vec![("view.zoomOut".into(), json!({})), ("view.fitOnScreen".into(), json!({})), ("view.actualPixels".into(), json!({}))],+ });+ app.session.actions.list.push(Action { name: "Second".into(), steps: vec![] });+ app.ui.actions.expanded = vec![true, false];+ let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app);+ h.run_steps(4);+ fn drag(h: &mut Harness<'_, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2) {+ h.event(egui::Event::PointerMoved(from));+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });+ h.run_steps(1);+ h.event(egui::Event::PointerMoved(from + vec2(10.0, 0.0)));+ h.run_steps(2);+ h.event(egui::Event::PointerMoved(to));+ h.run_steps(2);+ h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });+ h.run_steps(3);+ }+ let from = h.get_by_label("Zoom Out").rect().center();+ let target = h.get_by_label("100%").rect();+ drag(&mut h, from, pos2(target.center().x, target.bottom() - 2.0));+ assert_eq!(+ h.state().session.actions.list[0].steps.iter().map(|st| st.0.as_str()).collect::<Vec<_>>(),+ ["view.fitOnScreen", "view.actualPixels", "view.zoomOut"]+ );+ assert_eq!(h.state().ui.actions.selected_step, Some(2));+ let from = h.get_by_label("Second").rect().center();+ let target = h.get_by_label("First").rect();+ drag(&mut h, from, pos2(target.center().x, target.top() + 2.0));+ assert_eq!(h.state().session.actions.list[0].name, "Second");+ assert_eq!(h.state().ui.actions.expanded, [false, true]);+ assert_eq!(h.state().ui.actions.selected, Some(0));+ }++ #[test]+ fn nested_shell_actions_include_view_steps_and_propagate_failures() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width":40,"height":40})).unwrap();+ app.session+ .actions+ .list+ .push(Action { name: "Child".into(), steps: vec![("layer.new.layer".into(), json!({})), ("view.fitOnScreen".into(), json!({}))] });+ app.run("actions.record", json!({"name":"Parent"})).unwrap();+ app.run("actions.play", json!({"action":"Child"})).unwrap();+ app.run("actions.stop", json!({})).unwrap();+ assert_eq!(app.session.actions.list[1].steps, [("actions.play".into(), json!({"action":"Child"}))]);+ assert_eq!(step_label("actions.play", &json!({"action":"Child"})), "Play Action: Child");+ app.run("view.actualPixels", json!({})).unwrap();+ let r = app.run("actions.play", json!({"action":"Parent"})).unwrap();+ assert!(r.get("failed").is_none(), "{r}");+ assert!(app.ui.views[0].fit_pending);+ app.session.authorize =+ Some(|id, _| if id == "view.fitOnScreen" { Err(photocraft_engine::EngineError::Other("denied nested view".into())) } else { Ok(()) });+ let r = app.run("actions.play", json!({"action":"Parent"})).unwrap();+ assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested view"));+ assert!(app.session.actions.playback_stack.is_empty());+ assert_eq!(app.session.actions.playing, 0);+ }++ #[test]+ fn panel_shows_pending_steps_and_trash_deletes_only_the_clicked_step() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 40, "height": 40})).unwrap();+ begin_recording(&mut app, false);+ app.run("view.fitOnScreen", json!({})).unwrap();+ app.run("view.zoomOut", json!({})).unwrap();+ let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app);+ h.run_steps(2);+ assert!(h.state().session.actions.recording.is_some());+ h.get_by_label("Fit on Screen");+ h.get_by_label("Zoom Out").click();+ h.run_steps(2);+ assert_eq!(h.state().ui.actions.selected_step, Some(1));+ h.get_by_label("Delete").click();+ h.run_steps(2);+ assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), ["view.fitOnScreen"]);+ assert_eq!(h.state().session.actions.list.len(), 1);+ assert!(h.state().session.actions.recording.is_some());+ assert!(h.state().ui.actions.selected.is_none());+ delete_selection(h.state_mut());+ assert_eq!(h.state().session.actions.list.len(), 1, "repeated trash cannot delete the action");+ h.state_mut().run("view.zoomIn", json!({})).unwrap();+ h.run_steps(2);+ h.get_by_label("Zoom In");+ h.state_mut().run("actions.stop", json!({})).unwrap();+ h.run_steps(2);+ assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), ["view.fitOnScreen", "view.zoomIn"]);+ h.get_by_label("Zoom In").click();+ h.run_steps(2);+ h.get_by_label("Delete").click();+ h.run_steps(2);+ assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), ["view.fitOnScreen"]);+ }++ #[test]+ fn view_menu_commands_record_append_and_replay_after_resize() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ app.run("file.new", json!({"width": 160, "height": 100})).unwrap();+ begin_recording(&mut app, false);+ app.run("image.canvasSize", json!({"width": 80, "height": 60})).unwrap();+ app.run("actions.stop", json!({})).unwrap();+ begin_recording(&mut app, true);+ crate::menus::invoke(&mut app, &ctx, "view.fitOnScreen", json!({})).unwrap();+ app.run("actions.stop", json!({})).unwrap();+ assert_eq!(app.session.actions.list.len(), 1);+ assert_eq!(app.session.actions.list[0].steps.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["image.canvasSize", "view.fitOnScreen"]);+ assert_eq!(label_of("view.fitOnScreen"), "Fit on Screen");+ // Persisted actions retain the menu step, and playback fits the new document.+ let saved = serde_json::to_string(&app.session.actions.list).unwrap();+ app.session.actions.list = serde_json::from_str(&saved).unwrap();+ app.run("file.new", json!({"width": 200, "height": 140})).unwrap();+ app.run("view.actualPixels", json!({})).unwrap();+ let result = app.run("actions.play", json!({"action": 0})).unwrap();+ assert_eq!(result["ran"], 2);+ assert!(result.get("failed").is_none(), "{result}");+ let idx = app.session.active_index().unwrap();+ assert!(app.ui.views[idx].fit_pending);+ let doc = &app.session.active().unwrap().doc;+ crate::canvas::fit_view(&mut app.ui.views[idx], doc, vec2(100.0, 100.0));+ assert_eq!(app.ui.views[idx].zoom, 0.75);+ assert_eq!(app.ui.views[idx].center, [40.0, 30.0]);+ assert!(!app.ui.views[idx].fit_pending);+ }++ #[test]+ fn view_action_failure_resume_and_authorization() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session+ .actions+ .list+ .push(Action { name: "Fit".into(), steps: vec![("view.fitOnScreen".into(), json!({})), ("view.actualPixels".into(), json!({}))] });+ let result = app.run("actions.play", json!({"action": "Fit"})).unwrap();+ assert_eq!(result["ran"], 0);+ assert_eq!(result["failed"]["step"], 0);+ assert_eq!(app.session.actions.playing, 0);+ app.run("file.new", json!({"width": 40, "height": 40})).unwrap();+ app.session.authorize =+ Some(+ |id, _| {+ if id == "view.fitOnScreen" { Err(photocraft_engine::EngineError::BadParams { cmd: id.into(), msg: "denied view".into() }) } else { Ok(()) }+ },+ );+ let result = app.run("actions.play", json!({"action": 0})).unwrap();+ assert_eq!(result["ran"], 0);+ assert!(result["failed"]["error"].as_str().unwrap().contains("denied view"));+ let result = app.run("actions.play", json!({"action": 0, "from": 1})).unwrap();+ assert_eq!(result["ran"], 1);+ assert!(!app.ui.views[0].fit_pending);+ assert!(app.run("actions.play", json!({"action": 0, "from": -1})).is_err());+ app.session.actions.playing = 1;+ assert!(app.run("actions.play", json!({"action": 0})).is_err());+ }+#[test]fn record_and_replay_on_another_document() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex cd1f3f5ae..9ee5681d6 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -681,7 +681,13 @@ impl PhotocraftApp {let params = self.with_mask_target(id, params);let params = vector_ui::with_active_path(self, id, params);let path_mask = vector_ui::takes_path_mask(id) && params.get("path").is_some_and(|v| !v.is_null());- let r = jobs_ui::run(self, id, params);+ let r = if id == "actions.play" {+ actions::play(self, ¶ms)+ } else if photocraft_engine::actions_cmds::shell_view_command(id) {+ actions::run_view(self, id, params)+ } else {+ jobs_ui::run(self, id, params)+ };if r.is_ok() && id == "select.toWorkPath" {// Make Work Path selects the new work path in the Paths panel, as in Photoshop.self.ui.selected_path = Some("work".into());diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rsindex 33df13296..30a085b44 100644--- a/crates/ui-egui/src/menu_catalog.rs+++ b/crates/ui-egui/src/menu_catalog.rs@@ -644,7 +644,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[(&["View"], "---", None, "---"),(&["View"], "Zoom In", Some("Cmd+="), "view.zoomIn"),(&["View"], "Zoom Out", Some("Cmd+-"), "view.zoomOut"),- (&["View"], "Fit on Screen", None, "view.fitOnScreen"),+ (&["View"], "Fit on Screen", Some("Cmd+0"), "view.fitOnScreen"),(&["View"], "Fit Layer(s) on Screen", None, "view.fitLayersOnScreen"),(&["View"], "Fit Artboard on Screen", None, "view.fitArtboardOnScreen"),(&["View"], "100%", Some("Cmd+1"), "view.actualPixels"),diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex cd5f221a6..f9cb95cdb 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -261,23 +261,7 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:}}"file.saveAs" => app.save_as(params.get("path").and_then(Value::as_str).map(str::to_string)),- "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => {- let i = app.session.active_index().ok_or("no document")?;- let v = &mut app.ui.views[i];- match id {- "view.zoomIn" => v.zoom = crate::canvas::zoom_step(v.zoom, 1),- "view.zoomOut" => v.zoom = crate::canvas::zoom_step(v.zoom, -1),- "view.fitOnScreen" => v.fit_pending = true,- _ => v.zoom = 1.0,- }- if id == "view.fitOnScreen" {- v.fill_pending = false;- } else {- v.fit_pending = false;- v.fill_pending = false;- }- Ok(Value::Null)- }+ "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => app.run(id, params),"window.newWindowForDocument" => {let doc = app.session.active_index().ok_or("no document")?;let wid = app.ui.alloc_id();diff --git a/crates/ui-egui/src/shortcut_dispatch.rs b/crates/ui-egui/src/shortcut_dispatch.rsindex 666549d47..5a2b17fdc 100644--- a/crates/ui-egui/src/shortcut_dispatch.rs+++ b/crates/ui-egui/src/shortcut_dispatch.rs@@ -50,6 +50,8 @@ pub const SECONDARY: &[(&str, &str)] = &[("edit.fill", "Shift+Backspace")];/// 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_ids: Vec<String> = app.session.actions.list.iter().map(|a| crate::actions::shortcut_id(&a.name)).collect();+ let actions = action_ids.iter().map(|id| (id.as_str(), prefs.shortcut(id, None)));// 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).@@ -75,6 +77,7 @@ pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> {.iter().filter(|(id, sc)| {!sc.is_empty()+ && !id.starts_with(crate::actions::SHORTCUT_PREFIX)&& photocraft_engine::commands::find(id).is_none()&& !crate::menus::UI_COMMANDS.iter().any(|c| c.0 == id.as_str())&& !crate::hold_keys::is_temporary(id)@@ -85,7 +88,7 @@ pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> {// A key the user assigned in Edit › Keyboard Shortcuts belongs to that command, ahead of any// default that still names it (#1272): OK clears the old owner's row, but that row can be// another id for the same item, or a default the dialog doesn't list.- let mut candidates: Vec<(&str, Option<&str>)> = ui.chain(engine).chain(catalog).chain(overrides).chain(secondary).collect();+ let mut candidates: Vec<(&str, Option<&str>)> = actions.chain(ui).chain(engine).chain(catalog).chain(overrides).chain(secondary).collect();candidates.sort_by_key(|(id, sc)| !(sc.is_some() && prefs.shortcuts.get(*id).map(String::as_str) == *sc));let mut all: Vec<(String, KeyboardShortcut)> = Vec::new();for (id, sc) in candidates {@@ -280,15 +283,24 @@ fn label(id: &str) -> String {/// Run a shortcut's command like its menu item (dialogs included), or say why it can't run.pub fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) {- let outcome = if !crate::menus::is_enabled(app, id) {- let why = disabled_reason(app, id);+ let action = id.strip_prefix(crate::actions::SHORTCUT_PREFIX);+ let command_id = if action.is_some() { "actions.play" } else { id };+ let outcome = if !crate::menus::is_enabled(app, command_id) {+ let why = disabled_reason(app, command_id);app.ui.status = format!("{} is not available: {why}", label(id));app.ui.status_error = true;Outcome::Disabled(why)} else if ctx.data(|d| d.get_temp::<bool>(dry_run_id())).unwrap_or(false) {Outcome::Ran} else {- let r = if crate::adjust_dialog::has_dialog(id) {+ let r = if let Some(name) = action {+ // Use the normal command path: synthetic input and every nested action+ // step must still pass the automation authorizer.+ crate::menus::invoke(app, ctx, "actions.play", json!({"action": name})).and_then(|v| {+ crate::actions::report_play(app, &v);+ if v.get("failed").is_some_and(|f| f.is_object()) { Err(app.ui.status.clone()) } else { Ok(v) }+ })+ } else if crate::adjust_dialog::has_dialog(id) {crate::adjust_dialog::open(app, id);Ok(serde_json::Value::Null)} else {diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/shortcut_dispatch/tests.rsindex ff6c1fac4..3b109bad6 100644--- a/crates/ui-egui/src/shortcut_dispatch/tests.rs+++ b/crates/ui-egui/src/shortcut_dispatch/tests.rs@@ -488,3 +488,95 @@ fn delete_with_a_selection_clears_it() {assert_eq!(logged(&h), ["edit.clear"]);assert_eq!(names(&h), before, "no layer was deleted");}++#[test]+fn named_action_function_key_replays_and_survives_preferences_roundtrip() {+ let mut h = harness();+ let action =+ photocraft_engine::actions_cmds::Action { name: "LivePrint 2R".into(), steps: vec![("layer.new.layer".into(), json!({"name": "F6 overlay"}))] };+ h.state_mut().session.actions.list.push(action);+ crate::actions::assign_shortcut(h.state_mut(), "LivePrint 2R", "F6").unwrap();+ let saved = serde_json::to_value(h.state().session.prefs()).unwrap();+ let restored = serde_json::from_value(saved).unwrap();+ h.state_mut().session.edit_prefs(|p| *p = restored);+ h.state_mut().ui.actions.selected = None;+ press(&mut h, "F6");+ assert_eq!(active_name(&h), "F6 overlay");+ assert_eq!(h.state().ui.status, "Played 1 steps");+ assert!(!h.state().ui.status_error);+ assert_eq!(take_log(&h.ctx), vec![(crate::actions::shortcut_id("LivePrint 2R"), Outcome::Ran)]);+ h.state_mut().run("actions.delete", json!({"action": "LivePrint 2R"})).unwrap();+ assert!(bindings(h.state()).iter().all(|(id, _)| !id.starts_with(crate::actions::SHORTCUT_PREFIX)));+ assert!(bindings(h.state()).iter().any(|(_, sc)| *sc == parse("F6").unwrap()));+}++#[test]+fn assigning_action_function_key_moves_it_and_reports_failed_steps() {+ let mut h = harness();+ for name in ["first", "second"] {+ h.state_mut()+ .session+ .actions+ .list+ .push(photocraft_engine::actions_cmds::Action { name: name.into(), steps: vec![("no.such.command".into(), json!({}))] });+ }+ crate::actions::assign_shortcut(h.state_mut(), "first", "F6").unwrap();+ crate::actions::assign_shortcut(h.state_mut(), "second", "F6").unwrap();+ assert_eq!(h.state().session.prefs().shortcuts[&crate::actions::shortcut_id("first")], "");+ h.state_mut().ui.actions.selected = Some(0);+ press(&mut h, "F6");+ assert!(h.state().ui.status_error);+ assert!(h.state().ui.status.contains("Step 1 (no.such.command) failed"));+ assert!(matches!(&take_log(&h.ctx)[..], [(id, Outcome::Failed(_))] if id == "actions.play:second"));+}++#[test]+fn action_function_key_checks_automation_authorization() {+ let mut h = harness();+ h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action {+ name: "restricted".into(),+ steps: vec![("layer.new.layer".into(), json!({"name": "should not exist"}))],+ });+ crate::actions::assign_shortcut(h.state_mut(), "restricted", "F6").unwrap();+ h.state_mut().services.automation_command = Some(Box::new(|id, _| if id == "actions.play" { Err("denied action playback".into()) } else { Ok(()) }));+ h.state_mut().automation_input = true;+ super::dispatch(h.state_mut(), &egui::Context::default(), "actions.play:restricted");+ assert_eq!(h.state().ui.status, "denied action playback");+ assert_eq!(active_name(&h), "paint");+}++#[test]+fn fit_shortcut_records_and_f6_fits_the_resized_canvas() {+ let mut h = harness();+ h.state_mut().run("actions.record", json!({"name": "Resize and fit"})).unwrap();+ h.state_mut().run("image.canvasSize", json!({"width": 1800, "height": 1080})).unwrap();+ press(&mut h, "Cmd+0");+ h.state_mut().run("actions.stop", json!({})).unwrap();+ assert_eq!(h.state().session.actions.list[0].steps.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["image.canvasSize", "view.fitOnScreen"]);+ let item = crate::menus::menu_items(h.state()).into_iter().find(|i| i.id == "view.fitOnScreen").unwrap();+ assert_eq!(item.shortcut.as_deref(), Some("Cmd+0"));+ crate::actions::assign_shortcut(h.state_mut(), "Resize and fit", "F6").unwrap();+ h.state_mut().ui.views[0].zoom = 0.1;+ h.state_mut().ui.views[0].center = [0.0, 0.0];+ press(&mut h, "F6");+ let view = &h.state().ui.views[0];+ assert!(!view.fit_pending, "the real canvas frame consumed Fit on Screen");+ assert!(view.zoom > 0.1 && view.zoom < 1.0, "{}", view.zoom);+ assert_eq!(view.center, [900.0, 540.0]);+ assert_eq!(h.state().ui.status, "Played 2 steps");+}++#[test]+fn f6_while_recording_records_a_named_call_not_the_child_steps() {+ let mut h = harness();+ h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action {+ name: "LivePrint 2R".into(),+ steps: vec![("layer.new.layer".into(), json!({"name":"Nested overlay"})), ("view.fitOnScreen".into(), json!({}))],+ });+ crate::actions::assign_shortcut(h.state_mut(), "LivePrint 2R", "F6").unwrap();+ h.state_mut().run("actions.record", json!({"name":"Action 2"})).unwrap();+ press(&mut h, "F6");+ assert_eq!(active_name(&h), "Nested overlay");+ h.state_mut().run("actions.stop", json!({})).unwrap();+ assert_eq!(h.state().session.actions.list[1].steps, [("actions.play".into(), json!({"action":"LivePrint 2R"}))]);+}diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 12458e28d..6dcbbb308 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -95,9 +95,32 @@ store expose and persist the same setting; scripts keep using canonical command| `actions.list` | `{}` → `{actions:[{name, steps}], recording}` (the name being recorded, or null) || `actions.get` | `{"action": name or index}` → `{name, steps:[[id, params], …]}`, the shape `file.automate.batch` and droplets take || `actions.record` | `{"name":"Red"}` starts a new action (default name `Action N`). `{"action": name or index}` appends to one that exists |-| `actions.stop` | `{}` → `{action, steps}`. Copies replayable journal entries since `actions.record` (queries and `actions.*` omitted) |-| `actions.play` | `{"action": name or index, "from": step?}`. `from` and `failed.step` are 0-based. Returns `{action, ran, failed?:{step, id, error}}` and still returns ok when a step fails, so a partial run is reported. Leaves one history step per step that ran. Refuses to play while a play is already running. On an untrusted session each step is authorized the same way as a top-level command |-| `actions.delete` | `{"action": name or index}` → `{deleted}`. Refused while recording |+| `actions.stop` | `{}` → `{action, steps}`. Copies replayable journal entries since `actions.record` (queries and action-editing commands omitted) |+| `actions.play` | `{"action": name or index, "from": step?}`. `from` and `failed.step` are 0-based. Returns `{action, ran, failed?:{step, id, error}}` and still returns ok when a step fails, so a partial run is reported. Leaves one history step per step that ran. Supports nested action calls up to 16 levels, rejecting cycles. While recording, playing another action appends one named `actions.play` step instead of its expanded commands. On an untrusted session each step is authorized the same way as a top-level command |+| `actions.move` | `{"action": name or index, "step": index?, "to": index}` moves a step within its action, or moves the whole action when `step` is omitted. `to` is the final zero-based index. Pending steps can be reordered while recording; invalid moves leave the list unchanged. |+| `actions.delete` | `{"action": name or index, "step": index?}`. With a zero-based `step`: `{action, deletedStep, steps}`, also allowed while recording. Without `step`: `{deleted}`, refused while recording |++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+and does not undo the document edit. The control equivalent is+`actions.delete {"action": "Name", "step": 0}` (zero-based). Omitting `step` deletes+the whole action, which still requires recording to be stopped.++Desktop actions also record and replay View › Fit on Screen (`view.fitOnScreen`),+100% (`view.actualPixels`), Zoom In and Zoom Out through their menu commands or shortcuts.+Select an action and press Record to append steps; the plus button starts a new action.+A final `["view.fitOnScreen", {}]` step fits the resized document when the canvas is laid out.+Headless playback reports unsupported view commands as failed steps.++In the desktop Actions panel, right-click an action to assign a function key (F1–F12),+or choose None to remove it. The binding follows the action name, regardless of the selected+row, and is saved in preferences. For example, the existing `edit.keyboardShortcuts` command+accepts `{"set":{"actions.play:My action":"F6"},"allowUnknown":true,"removeConflicts":false}`.+A named action takes precedence over the ordinary menu shortcut while it exists and is bound;+removing its binding or deleting it restores that menu shortcut. The panel moves a key away+from another action when assigning it. Action playback still checks each nested command's+automation permissions.UI-level commands (`view.zoomIn`, `window.theme.pro`, `edit.search`, …) are also accepted by `engine.execute` and `ui.menu.invoke`.@@ -432,3 +455,19 @@ and region changes rebuild only the dependent analysis. Display options and thegeometry persist in preferences `dialogs["filter.cameraRaw.scope"]`; probes and vectorscopevisibility reset when the dialog opens. HDR scopes are not implemented. See[camera-raw-histogram.md](camera-raw-histogram.md).++### Editing and composing actions++Creating an action scrolls its row into view; newly recorded steps are revealed immediately.+Drag a step above or below another step in the same action to reorder it. Drag an action header+to reorder the action list. The insertion line marks the drop position; dragging near the rows'+top or bottom scrolls the list. Reordering is saved with the actions and does not undo image edits.++While recording, press a function key assigned to another action (or play it from the panel).+The recorder adds **Play Action: <name>** as one step, and the called action still executes.+Playback resolves the name each time, so editing or moving the called action does not freeze or+retarget the caller. Reassigning F6 later does not change an already recorded named call.+Missing actions, recursive calls and nesting beyond 16 levels fail visibly; a child failure stops+the parent before its next step. Every nested command retains the normal automation permission check.+Existing recordings containing expanded commands remain unchanged; remove those steps and record+the named call again if desired.