diff --git a/crates/engine-core/src/action_history.rs b/crates/engine-core/src/action_history.rs index ddda3475d6..fdbad437c8 100644 --- a/crates/engine-core/src/action_history.rs +++ b/crates/engine-core/src/action_history.rs @@ -272,7 +272,7 @@ impl ActionHistoryContinuation { /// Rebind a completed nonmodal dialog edit, leaving open-dialog time outside its scope. /// Only the scope resumed from this continuation may be taken; a parent remains untouched. pub fn suspend_after_edit(&self, s: &mut Session) -> Result { - if s.actions.playing != 0 || s.active().map(|st| st.doc.id) != self.active { + if s.recording.playing != 0 || s.active().map(|st| st.doc.id) != self.active { return Err(EngineError::Other("the dialog's action scope is no longer current".into())); } let active = self.documents.iter().find(|doc| Some(doc.id) == self.active); @@ -321,7 +321,7 @@ impl ActionHistoryContinuation { /// Publish the completed prefix, then release the active scope while a dialog is open. pub fn suspend_history(s: &mut Session) -> Option { - if s.actions.playing != 1 { + if s.recording.playing != 1 { return None; } Some(ActionHistoryContinuation::capture(s)) @@ -329,7 +329,7 @@ pub fn suspend_history(s: &mut Session) -> Option { /// End a dialog scope if its command or continuation fails before playback starts. pub fn finish_pending_history(s: &mut Session) { - if s.actions.playing == 0 { + if s.recording.playing == 0 { finish_playback(s); } } @@ -428,7 +428,7 @@ mod tests { s.execute("layer.renameLayer", json!({"name":name})).unwrap(); continuation = continuation.suspend_after_edit(&mut s).unwrap(); assert!(s.action_history.is_none(), "idle time must not own a history scope"); - assert_eq!(s.actions.playing, 0); + assert_eq!(s.recording.playing, 0); } continuation.resume(&mut s).unwrap(); finish_document_history(&mut s); diff --git a/crates/engine-core/src/actions_record.rs b/crates/engine-core/src/actions_record.rs index 69e87b3d65..2aef271d55 100644 --- a/crates/engine-core/src/actions_record.rs +++ b/crates/engine-core/src/actions_record.rs @@ -56,7 +56,7 @@ pub(crate) fn portable(s: &Session, id: &str, mut params: Value, before: &Before return serde_json::json!({"offset": offset}); } let Some(doc) = before.doc.as_deref() else { return params }; - if id == "type.create" && s.actions.recording.is_some() && params.get("box").is_none() && doc.size.width > 0 && doc.size.height > 0 { + if id == "type.create" && s.recording.target.is_some() && params.get("box").is_none() && doc.size.width > 0 && doc.size.height > 0 { let x = params.get("x").and_then(Value::as_f64).unwrap_or(0.0); let y = params.get("y").and_then(Value::as_f64).unwrap_or(0.0); let x_percent = x / f64::from(doc.size.width) * 100.0; @@ -153,7 +153,7 @@ pub(crate) fn fold_keystroke(s: &mut Session, id: &str, params: &Value, previous } // A new recording starts at a journal boundary. Its first edit cannot change an entry // before that boundary, or actions.stop would miss the edit altogether. - if s.actions.recording.is_some_and(|(start, _)| s.journal.len() <= start) { + if s.recording.target.is_some_and(|(start, _)| s.journal.len() <= start) { return Keystroke::None; } let Some((last, lp)) = s.journal.last_mut() else { return Keystroke::None }; @@ -222,7 +222,7 @@ pub(crate) fn tool_stroke(id: &str) -> bool { /// Visibility gestures name a layer for replay, since document-local ids change on another image. pub(crate) fn recorded_params(s: &Session, id: &str, mut p: Value) -> Value { - if s.actions.recording.is_none() || id != "layer.setProps" || p.get("visible").is_none() { + if s.recording.target.is_none() || id != "layer.setProps" || p.get("visible").is_none() { return p; } let Some(st) = s.active() else { return p }; diff --git a/crates/engine-core/src/cmd/actions_cmds.rs b/crates/engine-core/src/cmd/actions_cmds.rs index c3033b785f..64e8f864ec 100644 --- a/crates/engine-core/src/cmd/actions_cmds.rs +++ b/crates/engine-core/src/cmd/actions_cmds.rs @@ -64,7 +64,7 @@ pub fn note_automation_step(s: &mut Session, id: &str, params: &Value) { pub(crate) fn note_step_origin(s: &mut Session, automation: bool, id: &str, params: &Value) { if automation && recorded(id, params) - && let Some((_, idx)) = s.actions.recording + && let Some((_, idx)) = s.recording.target { let _ = s.actions.list.set_automation(idx, true); } @@ -198,16 +198,16 @@ pub fn save_target_closed(s: &Session, id: &str, target: Option bool { // Inside a script the step also counts against the script's total: each top-level playback // resets its own counter, so a script playing actions in a row would never reach the limit. - if s.actions.script_depth > 0 { - if s.actions.script_steps >= crate::automate_cmds::MAX_SCRIPT_STEPS { + if s.recording.script_depth > 0 { + if s.recording.script_steps >= crate::automate_cmds::MAX_SCRIPT_STEPS { return false; } - s.actions.script_steps += 1; + s.recording.script_steps += 1; } - if s.actions.playback_steps >= MAX_PLAYBACK_STEPS { + if s.recording.playback_steps >= MAX_PLAYBACK_STEPS { false } else { - s.actions.playback_steps += 1; + s.recording.playback_steps += 1; true } } @@ -215,7 +215,7 @@ pub fn consume_playback_step(s: &mut Session) -> bool { /// Steps of the playback tree the next `actions.play` starts in has charged so far: a top-level /// call starts a new tree ([`begin_playback`] resets the counter). fn playback_steps_used(s: &Session) -> u64 { - if s.actions.playing > 0 || s.actions.budget_shared { s.actions.playback_steps } else { 0 } + if s.recording.playing > 0 || s.recording.budget_shared { s.recording.playback_steps } else { 0 } } /// Steps of `action` playback walks past without running them: the ones before `from` and the @@ -230,7 +230,7 @@ fn skipped_steps(action: &Action, from: usize) -> u64 { /// Shared validation for headless and shell playback. Does not start playback. Returns the /// action's index in [`ActionState::playable`], the action and the step playback starts at. pub fn playback_plan(s: &Session, p: &Value) -> Result<(usize, Action, usize)> { - if s.actions.playing > 0 && s.actions.playback_stack.is_empty() { + if s.recording.playing > 0 && s.recording.playback_stack.is_empty() { return Err(bad("actions.play", "an action is already playing")); } let list = s.actions.playable(); @@ -245,11 +245,11 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(usize, Action, usize)> { } let action = list.action(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?; // The recording's index is into the user's list, which a Batch's called actions stand in for. - let records_it = s.actions.called.is_none() && s.actions.recording.is_some_and(|(_, i)| i == idx); - if s.actions.playback_stack.iter().any(|name| name == &action.name) || records_it { + let records_it = s.actions.called.is_none() && s.recording.target.is_some_and(|(_, i)| i == idx); + if s.recording.playback_stack.iter().any(|name| name == &action.name) || records_it { return Err(bad("actions.play", format!("recursive action call to `{}`", action.name))); } - if s.actions.playback_stack.len() >= 16 { + if s.recording.playback_stack.len() >= 16 { return Err(bad("actions.play", "action nesting exceeds 16 levels")); } let from = from_step(p, action.steps.len())?; @@ -499,8 +499,8 @@ fn from_step(p: &Value, len: usize) -> Result { fn list(s: &mut Session, _p: &Value) -> Result { let actions: Vec = s.actions.list.actions().iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect(); - let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.action(i).map(|a| a.name.clone())); - Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording, "toolRecording": s.actions.record_tools})) + let recording = s.recording.target.and_then(|(_, i)| s.actions.list.action(i).map(|a| a.name.clone())); + Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording, "toolRecording": s.recording.record_tools})) } fn get(s: &mut Session, p: &Value) -> Result { @@ -514,7 +514,7 @@ fn get(s: &mut Session, p: &Value) -> Result { /// it as automation's when an automation gate is installed. fn record(s: &mut Session, p: &Value) -> Result { not_playing(s, "actions.record")?; - if s.actions.recording.is_some() { + if s.recording.target.is_some() { return Err(bad("actions.record", "already recording; stop first")); } let idx = if p.get("action").is_some() { @@ -538,9 +538,9 @@ fn record(s: &mut Session, p: &Value) -> Result { // `push`, not `new_action`: an existing set keeps its exact name, which `new_action` would trim. s.actions.list.push(Action { set, ..Action::new(name, Vec::new()) }).map_err(|e| list_error("actions.record", e))? }; - s.actions.recording = Some((s.journal.len(), idx)); + s.recording.target = Some((s.journal.len(), idx)); note_automation_edit(s, idx); - s.actions.take = s.actions.take.wrapping_add(1); + s.recording.take = s.recording.take.wrapping_add(1); let name = s.actions.list.action(idx).map(|a| a.name.clone()).unwrap_or_default(); Ok(json!({"action": name, "index": idx})) } @@ -556,17 +556,17 @@ const RECORDED_WITH_DIALOG: &[&str] = &["edit.checkSpelling"]; /// Replayable journal entries not yet committed to this action while recording. pub fn pending_steps(s: &Session, action: usize) -> impl Iterator { - let from = s.actions.recording.filter(|(_, i)| *i == action).map_or(s.journal.len(), |(from, _)| from); - s.journal.iter().skip(from).filter(|(id, p)| recorded(id, p) && (s.actions.record_tools || !tool_stroke(id))) + let from = s.recording.target.filter(|(_, i)| *i == action).map_or(s.journal.len(), |(from, _)| from); + s.journal.iter().skip(from).filter(|(id, p)| recorded(id, p) && (s.recording.record_tools || !tool_stroke(id))) } pub(crate) fn flush_recording(s: &mut Session) -> Result<()> { - let Some((_, idx)) = s.actions.recording else { return Ok(()) }; + let Some((_, idx)) = s.recording.target else { return Ok(()) }; if s.actions.list.action(idx).is_none() { return Err(bad("actions.stop", "the action being recorded no longer exists")); } let steps = fold_recorded_nudges(pending_steps(s, idx).cloned()); - s.actions.recording = Some((s.journal.len(), idx)); + s.recording.target = Some((s.journal.len(), idx)); if !steps.is_empty() { let first = s.actions.list.step_count(idx); let with_dialog: Vec = @@ -632,11 +632,11 @@ fn fold_recorded_nudges(steps: impl IntoIterator) -> Vec fn stop(s: &mut Session, _p: &Value) -> Result { not_playing(s, "actions.stop")?; - let Some((_, idx)) = s.actions.recording else { + let Some((_, idx)) = s.recording.target else { return Err(bad("actions.stop", "not recording")); }; flush_recording(s)?; - s.actions.recording = None; + s.recording.target = None; let action = &s.actions.list.actions()[idx]; Ok(json!({"action": action.name, "steps": action.steps.len()})) } @@ -730,31 +730,31 @@ pub fn begin_playback_from(s: &mut Session, action: &Action, from: usize) -> Res // scope opens, so a rejected call leaves none behind. let skipped = skipped_steps(action, from); let max = crate::automate_cmds::MAX_SCRIPT_STEPS; - if s.actions.script_depth > 0 && s.actions.script_steps.saturating_add(skipped) > max { + if s.recording.script_depth > 0 && s.recording.script_steps.saturating_add(skipped) > max { return Err(bad("actions.play", format!("the script ran more than {max} steps in all"))); } - if s.actions.playing == 0 { + if s.recording.playing == 0 { crate::action_history::begin(s, &action.name); // A batch nested in a played action or another batch carries the shared count on. - if !s.actions.budget_shared { - s.actions.playback_steps = 0; + if !s.recording.budget_shared { + s.recording.playback_steps = 0; } } - s.actions.playback_steps = s.actions.playback_steps.saturating_add(skipped); - if s.actions.script_depth > 0 { - s.actions.script_steps = s.actions.script_steps.saturating_add(skipped); + s.recording.playback_steps = s.recording.playback_steps.saturating_add(skipped); + if s.recording.script_depth > 0 { + s.recording.script_steps = s.recording.script_steps.saturating_add(skipped); } - let recording = s.actions.recording.take(); - s.actions.playing = s.actions.playing.saturating_add(1); - s.actions.playback_stack.push(action.name.clone()); + let recording = s.recording.target.take(); + s.recording.playing = s.recording.playing.saturating_add(1); + s.recording.playback_stack.push(action.name.clone()); Ok(recording) } /// Unwind the playback stack and finish grouping only at the outer boundary, then restore suspended 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 s.actions.playing == 0 { + s.recording.playback_stack.pop(); + s.recording.playing = s.recording.playing.saturating_sub(1); + if s.recording.playing == 0 { crate::action_history::finish_playback(s); } if let Some((_, idx)) = recording { @@ -764,7 +764,7 @@ pub fn finish_playback(s: &mut Session, recording: Option<(usize, usize)>, actio /// Resume recording into action `idx` and journal the named call that suspended it. pub fn restore_recording(s: &mut Session, idx: usize, action: &str, from: usize) { - s.actions.recording = Some((s.journal.len(), idx)); + s.recording.target = Some((s.journal.len(), idx)); let mut params = json!({"action": action}); if from > 0 { params["from"] = json!(from); @@ -855,7 +855,7 @@ fn play(s: &mut Session, p: &Value) -> Result { } pub(crate) fn not_playing(s: &Session, cmd: &str) -> Result<()> { - if s.actions.playing > 0 { Err(bad(cmd, "cannot edit actions during playback")) } else { Ok(()) } + if s.recording.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. @@ -875,7 +875,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { 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) { + if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } s.actions.list.move_step(idx, step, idx, to).map_err(|e| list_error("actions.move", e))?; @@ -885,7 +885,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { } else { let name = s.actions.list.actions()[idx].name.clone(); s.actions.list.move_action(idx, to).map_err(|e| list_error("actions.move", e))?; - if let Some((_, recording)) = s.actions.recording.as_mut() { + if let Some((_, recording)) = s.recording.target.as_mut() { *recording = moved_index(*recording, idx, to); } Ok(json!({"action": name, "index": to})) @@ -905,7 +905,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { } // 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) { + if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } s.actions.list.delete_step(idx, step).map_err(|e| list_error("actions.delete", e))?; @@ -914,7 +914,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { note_automation_edit(s, idx); return Ok(result); } - if s.actions.recording.is_some() { + if s.recording.target.is_some() { return Err(bad("actions.delete", "stop recording before deleting an action")); } let name = s.actions.list.delete_action(idx).map_err(|e| list_error("actions.delete", e))?.name; @@ -942,7 +942,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result { if step.is_some_and(|step| step >= len) { return Err(bad(cmd, "step is out of range")); } - if s.actions.recording.is_some_and(|(_, i)| i == idx) { + if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } let action = &s.actions.list.actions()[idx]; @@ -1082,7 +1082,7 @@ fn rename(s: &mut Session, p: &Value) -> Result { None => return Err(bad("actions.rename", "needs \"name\"")), }; let old = s.actions.list.action(idx).map(|a| a.name.clone()).ok_or_else(|| bad("actions.rename", "no such action"))?; - let pending = s.actions.recording.map_or(s.journal.len(), |(start, _)| start); + let pending = s.recording.target.map_or(s.journal.len(), |(start, _)| start); // Names are list-wide, so a call naming `old` reaches this action; a named Batch is checked // against the list before the rename because its set can still refuse it. let before = s.actions.list.actions().to_vec(); @@ -1146,7 +1146,7 @@ fn set_color(s: &mut Session, p: &Value) -> Result { /// Active playback and retained dialog continuations keep their chosen history policy. pub(crate) fn history_policy_in_use(s: &Session) -> bool { - s.actions.playing != 0 || s.action_history.is_some() || s.paused_action_history.iter().any(|lease| lease.strong_count() != 0) + s.recording.playing != 0 || s.action_history.is_some() || s.paused_action_history.iter().any(|lease| lease.strong_count() != 0) } /// Create a single history state alone; `actions.setPlayback` sets it with the performance mode. @@ -1341,7 +1341,7 @@ mod security_tests { #[test] fn playback_budget_is_shared_by_nested_calls() { let mut session = crate::session(); - session.actions.playback_steps = MAX_PLAYBACK_STEPS - 1; + session.recording.playback_steps = MAX_PLAYBACK_STEPS - 1; assert!(consume_playback_step(&mut session)); assert!(!consume_playback_step(&mut session)); } @@ -1353,11 +1353,11 @@ mod security_tests { let mut session = crate::session(); session.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); session.actions.list.push(Action::new("A", vec![ActionStep::new("select.all", json!({}))])).unwrap(); - session.actions.budget_shared = true; - session.actions.playback_steps = MAX_PLAYBACK_STEPS; + session.recording.budget_shared = true; + session.recording.playback_steps = MAX_PLAYBACK_STEPS; let r = session.execute("actions.play", json!({"action": "A"})); assert!(matches!(r, Err(EngineError::BatchLimit(_))), "the carried count leaves no room for the action: {r:?}"); - session.actions.budget_shared = false; + session.recording.budget_shared = false; let r = session.execute("actions.play", json!({"action": "A"})).unwrap(); assert_eq!(r["ran"], 1, "a top-level call starts its own count"); } diff --git a/crates/engine-core/src/cmd/actions_cmds/tests.rs b/crates/engine-core/src/cmd/actions_cmds/tests.rs index 97edf971eb..033b756203 100644 --- a/crates/engine-core/src/cmd/actions_cmds/tests.rs +++ b/crates/engine-core/src/cmd/actions_cmds/tests.rs @@ -608,7 +608,7 @@ fn play_on_another_document_matches_pixels_at_each_depth() { assert_eq!(s.active().unwrap().history.past_len(), before + 3, "depth {depth}: one history step per played step"); let px = pixel(&s, 1, 5, 5); assert!(px.iter().zip([1.0, 0.0, 0.0, 1.0]).all(|(a, b)| (a - b).abs() < 1.0e-5), "depth {depth}: {px:?}"); - assert_eq!(s.actions.playing, 0); + assert_eq!(s.recording.playing, 0); } } @@ -1016,7 +1016,7 @@ fn play_stops_at_the_failing_step_and_reports_it() { assert_eq!(r["failed"]["id"], "not.a.command"); assert!(r["failed"]["error"].as_str().unwrap().contains("unknown command")); assert_eq!(s.active().unwrap().doc.layers.len(), 2, "the step before the failure is kept"); - assert_eq!(s.actions.playing, 0); + assert_eq!(s.recording.playing, 0); // A later play still runs. assert_eq!(s.execute("actions.play", json!({"action": 0, "from": 1})).unwrap()["ran"], 0); } @@ -1037,7 +1037,7 @@ fn play_refuses_recursion() { assert_eq!(r["ran"], 0); assert_eq!(r["failed"]["id"], "actions.play"); assert!(r["failed"]["error"].as_str().unwrap().contains("recursive action"), "{r}"); - assert_eq!(s.actions.playing, 0); + assert_eq!(s.recording.playing, 0); } #[test] @@ -1205,7 +1205,7 @@ fn delete_one_step_while_recording_keeps_journal_and_remaining_steps() { 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.recording.target.is_some()); assert!(s.actions.list.revision() > rev); s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); @@ -1254,7 +1254,7 @@ fn nested_call_records_one_named_step_and_tracks_child_edits() { 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::>(), ["Before", "Child layer", "Added later", "After"]); - assert!(s.actions.playback_stack.is_empty()); + assert!(s.recording.playback_stack.is_empty()); } #[test] @@ -1301,8 +1301,8 @@ fn nested_failure_cycles_depth_and_authorization_stop_parent() { } 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()); + assert_eq!(s.recording.playing, 0); + assert!(s.recording.playback_stack.is_empty()); s.actions.list.delete_step(15, 0).unwrap(); assert!(s.execute("actions.play", json!({"action": "N0"})).unwrap().get("failed").is_none()); } @@ -1345,7 +1345,7 @@ fn new_names_do_not_collide_with_named_calls() { 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()); + assert!(s.recording.target.is_none()); } #[test] @@ -1388,7 +1388,7 @@ fn bad_params_do_not_panic() { let _ = s.execute(id, p.clone()); } } - assert_eq!(s.actions.playing, 0); + assert_eq!(s.recording.playing, 0); assert!(crate::commands::command_specs().iter().any(|c| c.id == "actions.play" && !c.journal && c.menu.is_empty())); } @@ -1658,11 +1658,11 @@ fn record_keeps_an_empty_loaded_sets_exact_name() { fn skipped_steps_count_against_the_script_limit() { let mut s = crate::session(); s.actions.list.push(Action::new("A", (0..3).map(|_| ActionStep::new("select.all", json!({}))).collect())).unwrap(); - s.actions.script_depth = 1; - s.actions.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 1; + s.recording.script_depth = 1; + s.recording.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 1; let e = s.execute("actions.play", json!({"action": "A", "from": 3})).err().map(|e| e.to_string()); assert!(e.is_some_and(|e| e.contains("the script ran more than"))); - assert_eq!(s.actions.playing, 0); + assert_eq!(s.recording.playing, 0); assert!(s.action_history.is_none(), "a rejected call leaves no history scope open"); } diff --git a/crates/engine-core/src/cmd/actions_edit_cmds.rs b/crates/engine-core/src/cmd/actions_edit_cmds.rs index da927f70d8..ef2cfed208 100644 --- a/crates/engine-core/src/cmd/actions_edit_cmds.rs +++ b/crates/engine-core/src/cmd/actions_edit_cmds.rs @@ -36,16 +36,16 @@ fn allow_tool_recording(s: &mut Session, p: &Value) -> Result { let cmd = "actions.allowToolRecording"; not_playing(s, cmd)?; let enabled = match p.get("enabled") { - None | Some(Value::Null) => !s.actions.record_tools, + None | Some(Value::Null) => !s.recording.record_tools, Some(Value::Bool(enabled)) => *enabled, Some(_) => return Err(bad(cmd, "`enabled` must be true or false")), }; - if enabled != s.actions.record_tools { - if s.actions.recording.is_some() && s.tool_stroke_job_running() { + if enabled != s.recording.record_tools { + if s.recording.target.is_some() && s.tool_stroke_job_running() { return Err(bad(cmd, "wait for the current tool stroke before changing recording")); } flush_recording(s)?; - s.actions.record_tools = enabled; + s.recording.record_tools = enabled; } Ok(json!({"enabled": enabled})) } @@ -104,7 +104,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { if at > len { return Err(bad(cmd, format!("`at` {at} is past the last step ({len})"))); } - if s.actions.recording.is_some_and(|(_, i)| i == idx) { + if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } let is_stop = id == crate::atn_cmds::STOP_MESSAGE; @@ -139,7 +139,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { if step >= len { return Err(bad(cmd, "step is out of range")); } - if s.actions.recording.is_some_and(|(_, i)| i == idx) { + if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } s.actions.list.duplicate_step(idx, step).map_err(|e| list_error(cmd, e))?; @@ -148,7 +148,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { result["index"] = json!(idx); return Ok(result); } - if s.actions.recording.is_some() { + if s.recording.target.is_some() { return Err(bad(cmd, "stop recording before duplicating an action")); } let at = s.actions.list.duplicate_action(idx, shift_action_calls).map_err(|e| list_error(cmd, e))?; @@ -159,7 +159,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { /// Copy the named group represented by main, including a session-only empty New Set. fn duplicate_set(s: &mut Session, source: &str) -> Result { let cmd = "actions.duplicate"; - if s.actions.recording.is_some() { + if s.recording.target.is_some() { return Err(bad(cmd, "stop recording before duplicating a set")); } let sets = set_names(s); @@ -190,7 +190,7 @@ fn dialog(s: &mut Session, p: &Value) -> Result { if step.is_some_and(|step| step >= len) { return Err(bad(cmd, "step is out of range")); } - if s.actions.recording.is_some_and(|(_, i)| i == idx) { + if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } let action = &s.actions.list.actions()[idx]; diff --git a/crates/engine-core/src/cmd/actions_edit_cmds/library_commands.rs b/crates/engine-core/src/cmd/actions_edit_cmds/library_commands.rs index 9ab415a0ea..996a70f485 100644 --- a/crates/engine-core/src/cmd/actions_edit_cmds/library_commands.rs +++ b/crates/engine-core/src/cmd/actions_edit_cmds/library_commands.rs @@ -44,7 +44,7 @@ pub(crate) fn enabled(s: &Session) -> std::result::Result<(), String> { fn idle(s: &Session, cmd: &str) -> Result<()> { not_playing(s, cmd)?; - if s.actions.recording.is_some() { + if s.recording.target.is_some() { return Err(bad(cmd, "stop recording before changing the Actions library")); } Ok(()) @@ -112,7 +112,7 @@ pub(crate) fn publish_library(s: &mut Session, cmd: &str, shortcuts: Option Result { let prefs = s.prefs(); let keys = prefs.shortcuts.keys().chain(prefs.alternate_shortcuts.keys()).any(|id| is_action_key(id)); // Before the store attaches, an empty list still clears the stored library. - if count != 0 || !s.actions.list.sets().is_empty() || keys || (s.preset_store.is_none() && !s.actions.replaced_before_attachment) { + if count != 0 || !s.actions.list.sets().is_empty() || keys || (s.preset_store().is_none() && !s.actions.replaced_before_attachment) { publish_library(s, CMD, Some(Shortcuts::new()), ActionList::clear_all)?; } Ok(json!({"cleared": count})) @@ -204,7 +204,7 @@ pub(super) fn undo(s: &mut Session, _: &Value) -> Result { undo_state(s)?; let undo = s.actions.library_undo.take().ok_or_else(|| list_error(CMD, ActionListError::NothingToUndo))?; s.actions.list.undo_library().map_err(|error| list_error(CMD, error))?; - if s.preset_store.is_none() { + if s.preset_store().is_none() { s.actions.replaced_before_attachment = undo.replaced_before_attachment; } replace_bindings(s, undo.shortcuts, undo.alternates); diff --git a/crates/engine-core/src/cmd/actions_edit_cmds/record_again.rs b/crates/engine-core/src/cmd/actions_edit_cmds/record_again.rs index 97b267cba5..d68de77e4d 100644 --- a/crates/engine-core/src/cmd/actions_edit_cmds/record_again.rs +++ b/crates/engine-core/src/cmd/actions_edit_cmds/record_again.rs @@ -15,7 +15,7 @@ pub struct RecordAgainTarget { /// Resolve only executable steps, without flushing recording or editing the library. pub fn target(s: &Session, p: &Value) -> Result { not_playing(s, COMMAND)?; - if s.actions.recording.is_some() { + if s.recording.target.is_some() { return Err(bad(COMMAND, "stop recording before recording a step again")); } if let Some(revision) = p.get("revision") { diff --git a/crates/engine-core/src/cmd/atn_cmds/files.rs b/crates/engine-core/src/cmd/atn_cmds/files.rs index 4bc57ea711..f7cb0388a5 100644 --- a/crates/engine-core/src/cmd/atn_cmds/files.rs +++ b/crates/engine-core/src/cmd/atn_cmds/files.rs @@ -17,7 +17,7 @@ fn renamed_to<'a>(renames: &'a [(String, String)], name: &str) -> Option<&'a Str /// loads is marked as automation's, so it keeps the gate when the user plays it. pub(super) fn load(s: &mut Session, p: &Value) -> Result { let cmd = "actions.load"; - if s.actions.recording.is_some() || s.actions.playing > 0 { + if s.recording.target.is_some() || s.recording.playing > 0 { return Err(bad(cmd, "stop recording or playing before loading actions")); } let encoding = match p.get("encoding") { diff --git a/crates/engine-core/src/cmd/automate_cmds.rs b/crates/engine-core/src/cmd/automate_cmds.rs index a28834b235..8e7aed2244 100644 --- a/crates/engine-core/src/cmd/automate_cmds.rs +++ b/crates/engine-core/src/cmd/automate_cmds.rs @@ -128,8 +128,8 @@ pub(crate) const MAX_SCRIPT_STEPS: u64 = crate::actions_cmds::MAX_PLAYBACK_STEPS fn run_steps(s: &mut Session, steps: &[(String, Value)]) -> Vec { let mut results = Vec::new(); for (id, params) in steps { - s.actions.script_steps = s.actions.script_steps.saturating_add(1); - if s.actions.script_steps > MAX_SCRIPT_STEPS { + s.recording.script_steps = s.recording.script_steps.saturating_add(1); + if s.recording.script_steps > MAX_SCRIPT_STEPS { results.push(json!({"command": id, "error": format!("the script ran more than {MAX_SCRIPT_STEPS} steps in all (scripts calling scripts)")})); break; } @@ -171,15 +171,15 @@ fn browse(s: &mut Session, p: &Value) -> Result { _ => return Err(bad(cmd, "give \"path\" (a script file), \"script\" (its text) or \"steps\"")), }; check_known(&steps, cmd)?; - if s.actions.script_depth >= MAX_SCRIPT_DEPTH { + if s.recording.script_depth >= MAX_SCRIPT_DEPTH { return Err(bad(cmd, format!("scripts are nested more than {MAX_SCRIPT_DEPTH} deep"))); } - if s.actions.script_depth == 0 { - s.actions.script_steps = 0; + if s.recording.script_depth == 0 { + s.recording.script_steps = 0; } - s.actions.script_depth += 1; + s.recording.script_depth += 1; let results = run_steps(s, &steps); - s.actions.script_depth -= 1; + s.recording.script_depth -= 1; let ok = results.iter().all(|r| r.get("error").is_none()); Ok(json!({"steps": steps.len(), "ok": ok, "results": results})) } diff --git a/crates/engine-core/src/cmd/automate_cmds/tests.rs b/crates/engine-core/src/cmd/automate_cmds/tests.rs index e6f98c5c2b..aca34ad5d1 100644 --- a/crates/engine-core/src/cmd/automate_cmds/tests.rs +++ b/crates/engine-core/src/cmd/automate_cmds/tests.rs @@ -797,7 +797,7 @@ fn scripts_nested_deeper_than_the_limit_fail() { let r = s.execute("file.scripts.browse", json!({"path": below})).unwrap(); assert_eq!(r["ok"], false, "{r}"); assert!(r.to_string().contains("nested more than"), "{r}"); - assert_eq!(s.actions.script_depth, 0, "the depth is released"); + assert_eq!(s.recording.script_depth, 0, "the depth is released"); } /// A droplet captures only the actions its enabled steps can call: a disabled Play step in a diff --git a/crates/engine-core/src/cmd/file_cmds/batch_run.rs b/crates/engine-core/src/cmd/file_cmds/batch_run.rs index 1110baf9e8..2e322c7b01 100644 --- a/crates/engine-core/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine-core/src/cmd/file_cmds/batch_run.rs @@ -775,7 +775,7 @@ pub(crate) fn batch_keeps_step(id: &str) -> bool { /// Refuses a batch or droplet nested past [`MAX_BATCH_DEPTH`](crate::actions_cmds::MAX_BATCH_DEPTH), /// before it reads or decodes anything: each level keeps its parent's scratch document open. pub(crate) fn check_batch_depth(s: &Session, cmd: &str) -> Result<()> { - if s.actions.batch_depth >= crate::actions_cmds::MAX_BATCH_DEPTH { + if s.recording.batch_depth >= crate::actions_cmds::MAX_BATCH_DEPTH { return Err(EngineError::BatchLimit(format!( "invalid parameters for `{cmd}`: batches and droplets are nested more than {} deep", crate::actions_cmds::MAX_BATCH_DEPTH @@ -889,7 +889,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { .action_history .as_ref() .map(|group| group.name.clone()) - .or_else(|| s.actions.playback_stack.first().cloned()) + .or_else(|| s.recording.playback_stack.first().cloned()) .or_else(|| called_name.clone()) .or_else(|| p.get("action").and_then(Value::as_str).map(str::to_string)) .or_else(|| p.get("action").and_then(|action| action.get("name")).and_then(Value::as_str).map(str::to_string)) @@ -939,31 +939,31 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // action starts fresh; standalone explicit steps retain their existing behavior. A batch nested // in another batch (a droplet a droplet runs) is charged the same way, so the levels share one budget. let named = called_name.is_some(); - let nested = s.actions.playing > 0 || s.actions.batch_depth > 0; + let nested = s.recording.playing > 0 || s.recording.batch_depth > 0; let mut playback_steps = 0; if nested || named { - let spent = if nested { s.actions.playback_steps } else { 0 }; + let spent = if nested { s.recording.playback_steps } else { 0 }; playback_steps = spent.saturating_add((steps.len().max(1) as u64).saturating_mul(if source == "open" { s.documents().len() } else { inputs.len() } as u64)); if playback_steps > crate::actions_cmds::MAX_PLAYBACK_STEPS { return Err(EngineError::BatchLimit(format!("invalid parameters for `{cmd}`: this batch would exceed the action playback step limit"))); } if nested { - s.actions.playback_steps = playback_steps; + s.recording.playback_steps = playback_steps; } } - let mut playback_stack = s.actions.playback_stack.clone(); + let mut playback_stack = s.recording.playback_stack.clone(); playback_stack.extend(called_name); let actions = crate::actions_cmds::ActionState { list: s.actions.list.clone(), called, - playing: if named { s.actions.playing.saturating_add(1) } else { s.actions.playing }, + playing: if named { s.recording.playing.saturating_add(1) } else { s.recording.playing }, playback_stack, playback_steps, - script_depth: s.actions.script_depth, - script_steps: s.actions.script_steps, + script_depth: s.recording.script_depth, + script_steps: s.recording.script_steps, budget_shared: nested, - batch_depth: s.actions.batch_depth.saturating_add(1), + batch_depth: s.recording.batch_depth.saturating_add(1), ..Default::default() }; if source == "open" { @@ -972,18 +972,18 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // As in ordinary named playback, suspend it while executing and restore the Batch owner. let previous_recording = if named { crate::actions_cmds::flush_recording(s)?; - s.actions.recording.take() + s.recording.target.take() } else { None }; // Swap only the execution context (the playback counters and the actions playback calls); // the user's list, the recorder and the script counters stay. - let previous_playing = std::mem::replace(&mut s.actions.playing, actions.playing); - let previous_stack = std::mem::replace(&mut s.actions.playback_stack, actions.playback_stack); - let previous_steps = std::mem::replace(&mut s.actions.playback_steps, actions.playback_steps); + let previous_playing = std::mem::replace(&mut s.recording.playing, actions.playing); + let previous_stack = std::mem::replace(&mut s.recording.playback_stack, actions.playback_stack); + let previous_steps = std::mem::replace(&mut s.recording.playback_steps, actions.playback_steps); // The nesting depth and shared budget of the levels above travel with the run too. - let previous_shared = std::mem::replace(&mut s.actions.budget_shared, actions.budget_shared); - let previous_depth = std::mem::replace(&mut s.actions.batch_depth, actions.batch_depth); + let previous_shared = std::mem::replace(&mut s.recording.budget_shared, actions.budget_shared); + let previous_depth = std::mem::replace(&mut s.recording.batch_depth, actions.batch_depth); let previous_called = std::mem::replace(&mut s.actions.called, actions.called); let owns_history = s.action_history.is_none() && s.prefs().actions.create_single_history_state; if owns_history { @@ -993,16 +993,16 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { if owns_history { crate::actions_cmds::finish_document_history(s); } - s.actions.playing = previous_playing; - s.actions.playback_stack = previous_stack; - s.actions.budget_shared = previous_shared; - s.actions.batch_depth = previous_depth; + s.recording.playing = previous_playing; + s.recording.playback_stack = previous_stack; + s.recording.budget_shared = previous_shared; + s.recording.batch_depth = previous_depth; s.actions.called = previous_called; if previous_playing == 0 && !previous_shared { - s.actions.playback_steps = previous_steps; + s.recording.playback_steps = previous_steps; } if named { - s.actions.recording = previous_recording; + s.recording.target = previous_recording; } return result; } @@ -1028,7 +1028,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let prefs = s.prefs.clone(); let color_settings = s.color.settings.clone(); let raw_settings = s.batch_raw_open.as_ref().unwrap_or(&s.prefs().raw_defaults).clone(); - let script_count = s.actions.script_steps; + let script_count = s.recording.script_steps; let outputs: Vec<(String, String)> = if save_and_close { inputs.iter().map(|input| (input.path.clone(), input.path.clone())).collect() } else { @@ -1157,8 +1157,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { }; scratch.authorize = authorize; scratch.actions = actions.clone(); - scratch.actions.playback_steps = carried.get(); - scratch.actions.script_steps = script_steps.get(); + scratch.recording.playback_steps = carried.get(); + scratch.recording.script_steps = script_steps.get(); scratch.prefs.edit(|prefs| prefs.actions = action_prefs.clone()); let owns_history = scratch.action_history.is_none() && scratch.prefs().actions.create_single_history_state; if owns_history { @@ -1226,8 +1226,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { if let Some(observe) = history_observer { observe(scratch); } - carried.set(scratch.actions.playback_steps); - script_steps.set(scratch.actions.script_steps); + carried.set(scratch.recording.playback_steps); + script_steps.set(scratch.recording.script_steps); result }; let mut result = process_batch_outputs_with( @@ -1244,9 +1244,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { }, move |s, (result, carried, script_steps)| { if was_playing { - s.actions.playback_steps = carried; + s.recording.playback_steps = carried; } - s.actions.script_steps = script_steps; + s.recording.script_steps = script_steps; let mut result = result; mark_script_limit(s, &mut result); if let (Some(notices), Some(imports)) = (&mut s.batch_open_notices, result.get("notices").and_then(Value::as_array)) { @@ -1402,14 +1402,14 @@ fn batch_open_documents( /// A Batch run from a script charges each step it executes to the script's total, as nested /// playback does (`consume_playback_step`); the Batch itself is only one script step. fn charge_script_step(s: &mut Session) -> Result<()> { - if s.actions.script_depth == 0 { + if s.recording.script_depth == 0 { return Ok(()); } let max = crate::automate_cmds::MAX_SCRIPT_STEPS; - if s.actions.script_steps >= max { + if s.recording.script_steps >= max { return Err(EngineError::Other(format!("the script ran more than {max} steps in all (scripts calling scripts)"))); } - s.actions.script_steps += 1; + s.recording.script_steps += 1; Ok(()) } @@ -1419,7 +1419,7 @@ fn charge_script_step(s: &mut Session) -> Result<()> { fn mark_script_limit(s: &Session, result: &mut Value) { let max = crate::automate_cmds::MAX_SCRIPT_STEPS; let failed = result.get("errors").and_then(Value::as_array).is_some_and(|errors| !errors.is_empty()); - if s.actions.script_depth > 0 && s.actions.script_steps >= max && failed { + if s.recording.script_depth > 0 && s.recording.script_steps >= max && failed { result["scriptLimitError"] = json!(format!("the script ran more than {max} steps in all (scripts calling scripts)")); } } diff --git a/crates/engine-core/src/cmd/file_cmds/tests.rs b/crates/engine-core/src/cmd/file_cmds/tests.rs index cb90a52c4a..52dfb88dc2 100644 --- a/crates/engine-core/src/cmd/file_cmds/tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/tests.rs @@ -33,7 +33,7 @@ fn batch_resolves_action_by_name_and_detects_recursion() { p["output"] = json!(out); assert!(s.execute("file.automate.batch", p).is_err()); } - s.actions.playback_stack.push("Scale".into()); + s.recording.playback_stack.push("Scale".into()); let err = s.execute("file.automate.batch", json!({"action":"Scale","input":[input],"output":out})).unwrap_err(); assert!(err.to_string().contains("recursive action call"), "{err}"); } @@ -416,7 +416,7 @@ fn batch_override_open_authorizes_effective_path_and_carries_failure_budget() { assert_eq!(result["errors"].as_array().unwrap().len(), 1, "{result}"); assert!(result["errors"][0]["error"].as_str().unwrap().contains("effective Open denied")); assert_eq!(OPENS.load(std::sync::atomic::Ordering::SeqCst), 3, "two gates for the first Open, preauthorization denies the second"); - assert_eq!(s.actions.playback_steps, 4); + assert_eq!(s.recording.playback_steps, 4); assert_eq!(std::fs::read(&second).unwrap(), original); assert_eq!(std::fs::read(&existing).unwrap(), intact); assert!(s.documents().is_empty()); @@ -440,12 +440,12 @@ fn batch_override_open_nested_binding_and_save_close_preserve_sources() { ["file.closeAll",{}],["file.openAs",open],["image.adjustments.invert",{}]]); let driver = crate::actions_cmds::Action::new("Driver", vec![]); let recording = crate::actions_cmds::begin_playback(&mut s, &driver).unwrap(); - s.actions.playback_steps = crate::actions_cmds::MAX_PLAYBACK_STEPS - 8; + s.recording.playback_steps = crate::actions_cmds::MAX_PLAYBACK_STEPS - 8; let result = s.execute("file.automate.batch", json!({"input":[first],"output":output,"overrideOpen":true,"steps":steps})).unwrap(); assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); assert_eq!(batch_open_pixel(&join(&output, "a.png")), [0.0, 1.0, 1.0, 1.0]); assert_eq!(batch_open_pixel(&join(&inner, "b.png")), [1.0, 1.0, 0.0, 1.0]); - assert_eq!(s.actions.playback_steps, crate::actions_cmds::MAX_PLAYBACK_STEPS); + assert_eq!(s.recording.playback_steps, crate::actions_cmds::MAX_PLAYBACK_STEPS); crate::actions_cmds::finish_playback(&mut s, recording, &driver, 0); let original = std::fs::read(&first).unwrap(); for steps in [ @@ -549,26 +549,26 @@ fn named_open_document_batch_keeps_cycle_context_and_live_recorder() { crate::actions_cmds::Action::new("Leaf", vec![ActionStep::new("actions.play", json!({"action":0}))]), ]); let definitions = s.actions.list.actions()[1..].to_vec(); - s.actions.playback_stack = vec!["Enclosing".into()]; - s.actions.recording = Some((s.journal.len(), 0)); - let take = s.actions.take; + s.recording.playback_stack = vec!["Enclosing".into()]; + s.recording.target = Some((s.journal.len(), 0)); + let take = s.recording.take; s.authorize = Some(gate); CALLS.store(0, Ordering::SeqCst); let result = batch(&mut s, &json!({"source":"open","action":"Loop A"})).unwrap(); assert!(result["errors"][0]["error"].as_str().unwrap().contains("recursive action"), "{result}"); assert!(CALLS.load(Ordering::SeqCst) <= 2, "the cycle check must beat the finite sentinel"); - assert_eq!(s.actions.playback_stack, ["Enclosing"]); - assert_eq!(s.actions.recording.map(|(_, owner)| owner), Some(0)); - assert_eq!(s.actions.take, take); + assert_eq!(s.recording.playback_stack, ["Enclosing"]); + assert_eq!(s.recording.target.map(|(_, owner)| owner), Some(0)); + assert_eq!(s.recording.take, take); assert_eq!(&s.actions.list.actions()[1..], definitions.as_slice()); let before = doc(&s).walk().len(); let embedded = vec![crate::actions_cmds::Action::new("Embedded", vec![ActionStep::new("layer.new.layer", json!({"name":"visited"}))])]; let result = batch(&mut s, &json!({"source":"open","action":"Leaf","calledActions":embedded})).unwrap(); assert_eq!(result["errors"], json!([]), "{result}"); assert_eq!(doc(&s).walk().len(), before + 1); - assert_eq!(s.actions.playback_stack, ["Enclosing"]); - assert_eq!(s.actions.recording.map(|(_, owner)| owner), Some(0)); - assert_eq!(s.actions.take, take); + assert_eq!(s.recording.playback_stack, ["Enclosing"]); + assert_eq!(s.recording.target.map(|(_, owner)| owner), Some(0)); + assert_eq!(s.recording.take, take); assert_eq!(&s.actions.list.actions()[1..], definitions.as_slice()); } } @@ -3106,8 +3106,8 @@ fn named_batch_cycles_stop_before_the_test_ceiling() { assert_eq!(result["files"], json!([]), "{route}: {result}"); } assert!(!std::path::Path::new(&output).exists()); - assert_eq!(s.actions.playing, 0); - assert!(s.actions.playback_stack.is_empty()); + assert_eq!(s.recording.playing, 0); + assert!(s.recording.playback_stack.is_empty()); } } } @@ -3126,31 +3126,31 @@ fn named_batch_limits_nesting_and_keeps_the_callers_state() { s.execute("file.openAs", json!({"path": input})).unwrap(); } s.actions.list.push(Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap(); - s.actions.playing = 16; - s.actions.playback_stack = (0..16).map(|i| format!("Parent{i}")).collect(); + s.recording.playing = 16; + s.recording.playback_stack = (0..16).map(|i| format!("Parent{i}")).collect(); let before = s.actions.clone(); let error = s.execute("file.automate.batch", params.clone()).unwrap_err(); assert!(error.to_string().contains("nesting exceeds 16"), "{error}"); assert_eq!(s.actions, before); assert!(!std::path::Path::new(&output).exists()); - s.actions.playing = 0; - s.actions.playback_stack.clear(); + s.recording.playing = 0; + s.recording.playback_stack.clear(); s.execute("actions.record", json!({"name": "Recorder"})).unwrap(); - let recording = s.actions.recording; + let recording = s.recording.target; let mut missing_output = params.clone(); missing_output.as_object_mut().unwrap().remove("output"); if source == "open" { missing_output["source"] = json!("invalid"); } assert!(s.execute("file.automate.batch", missing_output).is_err()); - assert_eq!(s.actions.recording, recording); - assert!(s.actions.playback_stack.is_empty()); + assert_eq!(s.recording.target, recording); + assert!(s.recording.playback_stack.is_empty()); let result = s.execute("file.automate.batch", params.clone()).unwrap(); assert_eq!(result["errors"], json!([]), "{result}"); - assert_eq!(s.actions.recording, recording); - assert_eq!(s.actions.playing, 0); - assert!(s.actions.playback_stack.is_empty()); + assert_eq!(s.recording.target, recording); + assert_eq!(s.recording.playing, 0); + assert!(s.recording.playback_stack.is_empty()); s.execute("actions.stop", json!({})).unwrap(); assert_eq!(s.actions.list.actions()[1].steps, vec![ActionStep::new("file.automate.batch", params)]); } @@ -3168,12 +3168,12 @@ fn named_batch_charges_the_existing_budget_across_inputs_and_children() { let result = s.execute("file.automate.batch", json!({"action": "Large", "input": vec![input.clone(); 1001], "output": output})).unwrap_err(); assert!(result.to_string().contains("step limit"), "{result}"); assert!(!std::path::Path::new(&output).exists()); - assert_eq!(s.actions.playing, 0); - assert!(s.actions.playback_stack.is_empty()); + assert_eq!(s.recording.playing, 0); + assert!(s.recording.playback_stack.is_empty()); // A finished playback leaves its count behind; a new named Batch starts fresh. s.actions.list = list_of(vec![Action::new("Empty", Vec::new())]); - s.actions.playback_steps = MAX_PLAYBACK_STEPS; + s.recording.playback_steps = MAX_PLAYBACK_STEPS; let result = s.execute("file.automate.batch", json!({"action": "Empty", "input": [input], "output": join(&dir, "fresh")})).unwrap(); assert_eq!(result["errors"], json!([]), "{result}"); assert_eq!(result["files"].as_array().unwrap().len(), 1); @@ -3182,15 +3182,15 @@ fn named_batch_charges_the_existing_budget_across_inputs_and_children() { Action::new("Outer", vec![ActionStep::new("actions.play", json!({"action": "Leaf"}))]), Action::new("Leaf", vec![ActionStep::new("select.deselect", json!({})); 2]), ]); - s.actions.playing = 1; - s.actions.playback_stack = vec!["Parent".into()]; - s.actions.playback_steps = MAX_PLAYBACK_STEPS - 4; + s.recording.playing = 1; + s.recording.playback_stack = vec!["Parent".into()]; + s.recording.playback_steps = MAX_PLAYBACK_STEPS - 4; let result = s.execute("file.automate.batch", json!({"action": "Outer", "input": [input, input], "output": output, "naming": "{serial}"})).unwrap(); assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); assert!(result["errors"][0]["error"].as_str().unwrap().contains("step limit"), "{result}"); - assert_eq!(s.actions.playback_steps, MAX_PLAYBACK_STEPS); - assert_eq!(s.actions.playing, 1); - assert_eq!(s.actions.playback_stack, ["Parent"]); + assert_eq!(s.recording.playback_steps, MAX_PLAYBACK_STEPS); + assert_eq!(s.recording.playing, 1); + assert_eq!(s.recording.playback_stack, ["Parent"]); } /// Nested named batches honor the caller's authorization and preserve its action state. @@ -4213,13 +4213,13 @@ fn a_droplet_that_runs_itself_stops_at_the_nesting_limit() { let mut s = crate::session(); // Each level runs the next in a scratch session; the innermost is refused, so this returns. let r = s.execute("file.automate.runDroplet", json!({"droplet": droplet, "input": [input], "output": out})).unwrap(); - assert_eq!(s.actions.batch_depth, 0); + assert_eq!(s.recording.batch_depth, 0); // The limit reaches the outermost result: the input failed, nothing was saved unprocessed. assert!(r["errors"][0]["error"].as_str().unwrap().contains("nested more than"), "{r}"); assert_eq!(r["files"], json!([]), "{r}"); assert!(!std::path::Path::new(&out).join("a.png").exists()); // At the limit, the droplet is refused before its file is read (this one doesn't exist). - s.actions.batch_depth = crate::actions_cmds::MAX_BATCH_DEPTH; + s.recording.batch_depth = crate::actions_cmds::MAX_BATCH_DEPTH; let missing = join(&dir, "missing.pcdroplet"); let e = s.execute("file.automate.runDroplet", json!({"droplet": missing, "input": [input], "output": out})).unwrap_err(); assert!(e.to_string().contains("nested more than"), "{e}"); @@ -4589,8 +4589,8 @@ fn batch_steps_inside_a_script_count_against_its_step_limit() { let input = png(&dir, "in.png", 4, 4, "#ff0000"); for source in ["open", "folder"] { let mut s = session(4, 4, 8); - s.actions.script_depth = 1; - s.actions.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 1; + s.recording.script_depth = 1; + s.recording.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 1; let mut p = json!({"source": source, "output": join(&dir, source), "format": "png", "steps": [["image.adjustments.invert", {}], ["image.adjustments.invert", {}]]}); if source == "folder" { @@ -4599,7 +4599,7 @@ fn batch_steps_inside_a_script_count_against_its_step_limit() { let result = s.execute("file.automate.batch", p).unwrap(); let error = result["errors"][0]["error"].as_str().unwrap_or_default(); assert!(error.contains("steps in all"), "{source}: {result}"); - assert_eq!(s.actions.script_steps, crate::automate_cmds::MAX_SCRIPT_STEPS, "{source}"); + assert_eq!(s.recording.script_steps, crate::automate_cmds::MAX_SCRIPT_STEPS, "{source}"); } } @@ -4611,8 +4611,8 @@ fn a_save_only_batch_writes_nothing_once_the_script_steps_are_spent() { let input = png(&dir, "in.png", 4, 4, "#ff0000"); for source in ["open", "folder"] { let mut s = session(4, 4, 8); - s.actions.script_depth = 1; - s.actions.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS; + s.recording.script_depth = 1; + s.recording.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS; let out = join(&dir, &format!("out-{source}")); let mut p = json!({"source": source, "output": out, "format": "png", "steps": [["file.save", {}]]}); if source == "folder" { @@ -4636,8 +4636,8 @@ fn a_direct_batch_that_spends_the_script_budget_fails_the_script() { for source in ["open", "folder"] { let mut s = session(4, 4, 8); // A nested script: the outer one has already spent all but two steps. - s.actions.script_depth = 1; - s.actions.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 2; + s.recording.script_depth = 1; + s.recording.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 2; let mut batch = json!({"source": source, "output": join(&dir, &format!("out-{source}")), "format": "png", "steps": [["image.adjustments.invert", {}], ["image.adjustments.invert", {}]]}); if source == "folder" { diff --git a/crates/engine-core/src/cmd/pattern_cmds.rs b/crates/engine-core/src/cmd/pattern_cmds.rs index 4b3b441863..cb3652015d 100644 --- a/crates/engine-core/src/cmd/pattern_cmds.rs +++ b/crates/engine-core/src/cmd/pattern_cmds.rs @@ -141,7 +141,7 @@ pub fn full(s: &Session, p: &Pattern) -> std::result::Result { if !s.patterns.stored.contains_key(&p.id) { return Ok(p.clone()); } - let st = s.preset_store.as_ref().ok_or_else(|| format!("pattern \"{}\" is not loaded: no preset store", p.display_name()))?; + let st = s.preset_store().ok_or_else(|| format!("pattern \"{}\" is not loaded: no preset store", p.display_name()))?; let mut f = st.load_pattern(&p.id).map_err(|e| format!("pattern \"{}\" could not be loaded: {e}", p.display_name()))?; f.name = p.name.clone(); Ok(f) diff --git a/crates/engine-core/src/jobs.rs b/crates/engine-core/src/jobs.rs index 4259a33946..c250a61744 100644 --- a/crates/engine-core/src/jobs.rs +++ b/crates/engine-core/src/jobs.rs @@ -1048,7 +1048,7 @@ pub struct PendingPsdPreflight { impl Session { /// A recording mode change must not reclassify an in-flight stroke from this take. pub(crate) fn tool_stroke_job_running(&self) -> bool { - self.jobs.running.iter().any(|job| job.started_in_take == Some(self.actions.take) && crate::actions_record::tool_stroke(&job.command)) + self.jobs.running.iter().any(|job| job.started_in_take == Some(self.recording.take) && crate::actions_record::tool_stroke(&job.command)) } /// Run the heavy part of inline (not background) job commands under `ctx`, so another thread @@ -1800,12 +1800,12 @@ impl Session { self.jobs.spawn = background; // Commands this one runs on its own behalf journal after this mark (#3067). let nested_from = self.journal.len(); - let pre_selected = if self.actions.recording.is_some() { self.active().map(|st| st.selected_layers().to_vec()) } else { None }; + let pre_selected = if self.recording.target.is_some() { self.active().map(|st| st.selected_layers().to_vec()) } else { None }; let mut record_before = crate::actions_record::Before::capture(self); // A replayable command is recorded as one step, so recording pauses while it runs: an // action it plays (a script step) must not flush the steps it ran so far into the action // being recorded, nor move the recording mark past the entries it is about to replace. - let recording = if spec.journal && crate::actions_record::replayable(id) { self.actions.recording.take() } else { None }; + let recording = if spec.journal && crate::actions_record::replayable(id) { self.recording.target.take() } else { None }; let before = self.active().map(|st| (st.doc.clone(), st.revision)); let docs_before: Vec<_> = self.docs.iter().map(|st| st.doc.id).collect(); // Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an @@ -1815,8 +1815,8 @@ impl Session { let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (spec.run)(self, &run_params))) .unwrap_or_else(|_| Err(EngineError::Other(format!("`{id}` failed with an internal error (logged); the document is unchanged")))); self.live_commit = None; - if self.actions.recording.is_none() { - self.actions.recording = recording; + if self.recording.target.is_none() { + self.recording.target = recording; } self.jobs.spawn = false; self.coalesce_request = None; @@ -1849,8 +1849,8 @@ impl Session { job.command = id.to_string(); job.params = params; job.journal = spec.journal; - job.started_in_take = self.actions.recording.map(|_| self.actions.take); - job.recorded_by = job.started_in_take.filter(|_| self.actions.record_tools || !crate::actions_record::tool_stroke(id)); + job.started_in_take = self.recording.target.map(|_| self.recording.take); + job.recorded_by = job.started_in_take.filter(|_| self.recording.record_tools || !crate::actions_record::tool_stroke(id)); job.automation = automation; job.pre_selected = pre_selected.clone(); job.before = std::mem::take(&mut record_before); @@ -1986,7 +1986,7 @@ impl Session { self.journal.truncate(from); } let typed = crate::actions_record::typed_layer(self, id, ¶ms); - let params = if self.actions.recording.is_none() { params } else { hooks.recorded(self, id, params, pre_selected) }; + let params = if self.recording.target.is_none() { params } else { hooks.recorded(self, id, params, pre_selected) }; let params = crate::actions_record::recorded_params(self, id, params); let params = crate::actions_record::portable(self, id, params, before); // A step a control client runs while the user records keeps automation's gate. @@ -2060,7 +2060,7 @@ impl Session { } = job; // A recording started after the job (#7289) keeps what it has so far, and the job's step // goes into the journal past its start, so that recording doesn't get it. - let foreign = self.actions.recording.is_some() && *recorded_by != Some(self.actions.take); + let foreign = self.recording.target.is_some() && *recorded_by != Some(self.recording.take); if foreign { for flush in &crate::registry::hooks().flush_recording { flush(self)?; @@ -2104,15 +2104,15 @@ impl Session { // Apply-time hooks can dispatch commands too. Keep the same single-step recording // contract as synchronous dispatch without truncating work done while the worker ran. let nested_from = self.journal.len(); - let recording = if *journal && crate::actions_record::replayable(command) { self.actions.recording.take() } else { None }; + let recording = if *journal && crate::actions_record::replayable(command) { self.recording.target.take() } else { None }; let applied_from = target.and_then(|i| self.docs.get(i)).map(|st| (st.doc.id, st.revision)); let r = match apply { Some(f) => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self, payload))) .unwrap_or_else(|_| Err(EngineError::Other(format!("`{label}` failed with an internal error (logged); the document is unchanged")))), None => Err(EngineError::Other("internal error: job applied twice".into())), }; - if self.actions.recording.is_none() { - self.actions.recording = recording; + if self.recording.target.is_none() { + self.recording.target = recording; } self.coalesce_request = None; self.color_restrict = None; @@ -2128,7 +2128,7 @@ impl Session { // polling it now, and only for the recording that owns it: a foreign recording does // not get the step. self.after_command(command, params.clone(), *journal, *automation && !foreign, Some(nested_from), pre_selected.as_deref(), before); - if foreign && let Some((start, _)) = self.actions.recording.as_mut() { + if foreign && let Some((start, _)) = self.recording.target.as_mut() { *start = self.journal.len(); } } diff --git a/crates/engine-core/src/preset_store.rs b/crates/engine-core/src/preset_store.rs index 624c7e04f3..c5e683c462 100644 --- a/crates/engine-core/src/preset_store.rs +++ b/crates/engine-core/src/preset_store.rs @@ -1175,7 +1175,7 @@ impl Session { } else if self.actions.list.actions().is_empty() && self.actions.list.sets().is_empty() { self.actions.list.replace(disk); name_id_shortcuts(self, &action_ids); - if let Some(st) = self.preset_store.as_mut() { + if let Some(st) = self.preset_store_mut() { st.actions_rev = self.actions.list.revision(); } if !action_ids.is_empty() { @@ -1201,7 +1201,7 @@ impl Session { let mut brush = std::mem::take(&mut *self.tools.brush); let _ = self.load_brush_tips(&mut brush); *self.tools.brush = brush; - if let Some(st) = self.preset_store.as_mut() { + if let Some(st) = self.preset_store_mut() { warnings.extend(st.take_warnings()); } warnings @@ -1210,7 +1210,7 @@ impl Session { /// Write pending brush preset, Actions and pattern changes to the attached store (no-op without one). pub fn sync_preset_store(&mut self) { let rev = self.tools.presets_rev; - if let Some(st) = self.preset_store.as_mut() { + if let Some(st) = self.preset_store_mut() { if st.synced_rev != Some(rev) { st.sync(&mut self.tools.presets); st.synced_rev = Some(rev); @@ -1231,7 +1231,7 @@ impl Session { pub fn load_brush_tips(&self, b: &mut BrushSettings) -> Result<(), String> { let load = |r: &mut StoredTile| -> Result<(), String> { if r.full.is_none() { - let st = self.preset_store.as_ref().ok_or_else(|| format!("brush tip {} is not available: no preset store is attached", r.key))?; + let st = self.preset_store().ok_or_else(|| format!("brush tip {} is not available: no preset store is attached", r.key))?; r.full = Some(st.load_tile(r)?); } Ok(()) diff --git a/crates/engine-core/src/preset_store/tests.rs b/crates/engine-core/src/preset_store/tests.rs index a51638bfe9..9c7723e6f8 100644 --- a/crates/engine-core/src/preset_store/tests.rs +++ b/crates/engine-core/src/preset_store/tests.rs @@ -96,9 +96,9 @@ fn saved_airbrush_group_keeps_legacy_and_explicit_rates_across_reopen() { #[test] fn sessions_have_no_store_by_default() { let mut s = crate::session(); - assert!(s.preset_store.is_none(), "headless sessions must stay hermetic"); + assert!(s.preset_store().is_none(), "headless sessions must stay hermetic"); s.execute("brush.presets.save", json!({"name": "Mine"})).unwrap(); - assert!(s.preset_store.is_none()); + assert!(s.preset_store().is_none()); } #[test] @@ -399,7 +399,7 @@ fn write_failures_are_warnings() { s.attach_preset_store(open_dir(&dir.0)); s.tools.brush.tip = TipShape::Sampled(tip8(4, 4, 0)).into(); s.execute("brush.presets.save", json!({"name": "Nope"})).unwrap(); - let w = s.preset_store.as_mut().unwrap().take_warnings(); + let w = s.preset_store_mut().unwrap().take_warnings(); assert!(!w.is_empty()); let _ = std::fs::remove_file(&dir.0); } @@ -433,7 +433,7 @@ fn bench_load_500_sampled_presets() { let t0 = std::time::Instant::now(); s.sync_preset_store(); let write = t0.elapsed(); - let bytes = s.preset_store.as_ref().unwrap().bytes(); + let bytes = s.preset_store().unwrap().bytes(); let t0 = std::time::Instant::now(); let o = open_dir(&dir.0); let load = t0.elapsed(); @@ -488,7 +488,7 @@ fn library_samples(s: &Session) -> usize { } fn cache(s: &Session) -> TipCacheStats { - s.preset_store.as_ref().unwrap().tip_cache() + s.preset_store().unwrap().tip_cache() } #[test] @@ -541,7 +541,7 @@ fn the_decoded_tip_cache_stays_within_its_budget() { let mut t = crate::session(); t.attach_preset_store(open(Box::new(mem))); let one = 256 * 256 * 2; - t.preset_store.as_ref().unwrap().set_tip_cache_limit(one * 2 + 1); + t.preset_store().unwrap().set_tip_cache_limit(one * 2 + 1); for i in 0..6 { t.execute("tools.setBrush", json!({"preset": format!("Big {i}")})).unwrap(); let c = cache(&t); @@ -555,7 +555,7 @@ fn the_decoded_tip_cache_stays_within_its_budget() { t.execute("tools.setBrush", json!({"preset": "Big 0"})).unwrap(); assert_eq!(cache(&t).decodes, 7); // A budget below one tip still loads it (the brush in use holds its own reference). - t.preset_store.as_ref().unwrap().set_tip_cache_limit(0); + t.preset_store().unwrap().set_tip_cache_limit(0); assert_eq!(cache(&t).tips, 0); t.execute("tools.setBrush", json!({"preset": "Big 1"})).unwrap(); assert!(matches!(&*t.tools.brush.tip, TipShape::Stored(r) if r.is_loaded())); @@ -775,7 +775,7 @@ fn a_group_file_that_failed_to_load_is_not_overwritten() { s.tools.brush.tip = TipShape::Sampled(tip8(4, 4, 0)).into(); s.execute("brush.presets.save", json!({"name": "New"})).unwrap(); assert_eq!(mem.files.lock().unwrap().get(&file), Some(&newer), "a file the store could not read was overwritten"); - assert!(!s.preset_store.as_mut().unwrap().take_warnings().is_empty()); + assert!(!s.preset_store_mut().unwrap().take_warnings().is_empty()); } #[test] @@ -790,7 +790,7 @@ fn an_actions_file_that_failed_to_load_is_not_overwritten() { s.execute("actions.stop", json!({})).unwrap(); s.sync_preset_store(); assert_eq!(mem.files.lock().unwrap().get(ACTIONS_FILE), Some(&newer), "an actions file the store could not read was overwritten"); - assert!(!s.preset_store.as_mut().unwrap().take_warnings().is_empty()); + assert!(!s.preset_store_mut().unwrap().take_warnings().is_empty()); } // A PhotoCraft actions file that keyed calls and shortcuts by stored action id loads with names @@ -1000,7 +1000,7 @@ fn a_patterns_file_that_failed_to_load_is_not_overwritten() { s.execute("edit.definePattern", json!({"name": "New"})).unwrap(); s.sync_preset_store(); assert_eq!(mem.files.lock().unwrap().get(PATTERNS_FILE), Some(&unreadable), "a patterns file the store could not read was overwritten"); - assert!(!s.preset_store.as_mut().unwrap().take_warnings().is_empty()); + assert!(!s.preset_store_mut().unwrap().take_warnings().is_empty()); } /// A `.pat` of one 4×4 pattern with id `id`, filled with `rgba`. @@ -1072,7 +1072,7 @@ fn a_failed_patterns_removal_is_retried() { backend.fail.store(true, std::sync::atomic::Ordering::SeqCst); s.execute("pattern.delete", json!({"pattern": id})).unwrap(); s.sync_preset_store(); - assert!(!s.preset_store.as_mut().unwrap().take_warnings().is_empty(), "the failure is warned"); + assert!(!s.preset_store_mut().unwrap().take_warnings().is_empty(), "the failure is warned"); backend.fail.store(false, std::sync::atomic::Ordering::SeqCst); s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); s.sync_preset_store(); diff --git a/crates/engine/examples/abr_memory.rs b/crates/engine/examples/abr_memory.rs index 71c1460664..588f4b3031 100644 --- a/crates/engine/examples/abr_memory.rs +++ b/crates/engine/examples/abr_memory.rs @@ -72,7 +72,7 @@ fn library_tip_bytes(s: &Session) -> (usize, u64, u64) { fn report(s: &Session, step: &str) { let (n, b, p) = library_tip_bytes(s); - let cache = s.preset_store.as_ref().map(|st| st.tip_cache()).unwrap_or_default(); + let cache = s.preset_store().map(|st| st.tip_cache()).unwrap_or_default(); println!( "{step}: {} | {} presets, {n} full tips in the library ({:.0} MB), previews {:.1} MB, tip cache {} tips {:.0} MB ({} decodes)", memory(), @@ -115,7 +115,7 @@ fn main() { println!("imported {} ({} presets)", f.display(), r["count"]); } println!("import + store sync: {:.2} s", t.elapsed().as_secs_f64()); - for w in s.preset_store.as_mut().map(|st| st.take_warnings()).unwrap_or_default() { + for w in s.preset_store_mut().map(|st| st.take_warnings()).unwrap_or_default() { println!("warning: {w}"); } report(&s, "after import"); diff --git a/crates/engine/tests/it/actions_duplicate.rs b/crates/engine/tests/it/actions_duplicate.rs index ba25dcba26..5f0460be60 100644 --- a/crates/engine/tests/it/actions_duplicate.rs +++ b/crates/engine/tests/it/actions_duplicate.rs @@ -107,7 +107,7 @@ fn invalid_copies_do_not_flush_recording_and_valid_step_copies_keep_recording() s.execute("actions.record", json!({"name": "Recording"})).unwrap(); s.execute("select.all", json!({})).unwrap(); let before = s.actions.list.clone(); - let recording = s.actions.recording; + let recording = s.recording.target; let revision = s.active().unwrap().revision; for params in [ json!({}), @@ -119,12 +119,12 @@ fn invalid_copies_do_not_flush_recording_and_valid_step_copies_keep_recording() ] { assert!(s.execute("actions.duplicate", params.clone()).is_err(), "{params}"); assert_eq!(s.actions.list, before); - assert_eq!(s.actions.recording, recording); + assert_eq!(s.recording.target, recording); assert_eq!(s.active().unwrap().revision, revision); } s.execute("actions.duplicate", json!({"action": 0, "step": 0})).unwrap(); assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("select.all", json!({})); 2]); - assert!(s.actions.recording.is_some()); + assert!(s.recording.target.is_some()); s.execute("select.deselect", json!({})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); assert_eq!(s.actions.list.actions()[0].steps.len(), 3); diff --git a/crates/engine/tests/it/actions_panel_menu.rs b/crates/engine/tests/it/actions_panel_menu.rs index 80256d75e2..f15bbb07c1 100644 --- a/crates/engine/tests/it/actions_panel_menu.rs +++ b/crates/engine/tests/it/actions_panel_menu.rs @@ -54,7 +54,7 @@ fn background_stroke_ownership_does_not_suppress_ordinary_filter_jobs() { let changed = s.execute("actions.allowToolRecording", json!({"enabled":true})); if command == "paint.remove" { assert!(changed.is_err(), "the in-flight stroke retains the mode it started under"); - assert!(!s.actions.record_tools); + assert!(!s.recording.record_tools); } else { changed.unwrap(); } diff --git a/crates/engine/tests/it/atn_review_regressions.rs b/crates/engine/tests/it/atn_review_regressions.rs index 82289d6742..94c8c543bd 100644 --- a/crates/engine/tests/it/atn_review_regressions.rs +++ b/crates/engine/tests/it/atn_review_regressions.rs @@ -1059,15 +1059,15 @@ fn batch_carries_script_limits_and_restores_balanced_depth() { let step = json!({"command":"file.scripts.browse","params":{"steps":[{"command":"select.all"}]}}); for (depth, spending, allowed) in [(16, 0, false), (1, photocraft_engine::actions_cmds::MAX_PLAYBACK_STEPS - 1, false), (1, 2, true)] { let mut s = Session::new(); - s.actions.script_depth = depth; - s.actions.script_steps = spending; + s.recording.script_depth = depth; + s.recording.script_steps = spending; let result = s.execute("file.automate.batch",json!({"input":[input,input],"output":dir.path().join("out"),"steps":[step],"namingComponents":[{"component":"serial2"},{"component":"extension"}]})).unwrap(); assert_eq!(result["errors"].as_array().unwrap().is_empty(), allowed, "{result}"); - assert_eq!(s.actions.script_depth, depth); + assert_eq!(s.recording.script_depth, depth); if depth == 1 { // Per input: the Batch's direct step (the nested script), then that script's one step // unless the playback limit refuses it. - assert_eq!(s.actions.script_steps, spending + if allowed { 4 } else { 2 }); + assert_eq!(s.recording.script_steps, spending + if allowed { 4 } else { 2 }); } } } diff --git a/crates/engine/tests/it/vector_paste_options.rs b/crates/engine/tests/it/vector_paste_options.rs index 7c767458e6..2111c32b7b 100644 --- a/crates/engine/tests/it/vector_paste_options.rs +++ b/crates/engine/tests/it/vector_paste_options.rs @@ -37,7 +37,7 @@ const SVG: &[u8] = br##" Session { let mut s = Session::new(); s.execute("file.new", json!({"width": 20, "height": 16, "depth": depth, "background": "transparent"})).unwrap(); - *s.clipboard = Some(Clip::from_svg(SVG).unwrap()); + *s.clipboard = Some(clip_from_svg(SVG).unwrap()); s } @@ -134,7 +134,7 @@ fn original_svg_drives_pixels_curves_and_shape_paint_with_one_undo() { assert!(legacy[1] > 0.9 && legacy[0] < 0.1, "omission keeps the ordinary raster mirror route"); s.execute("edit.undo", json!({})).unwrap(); let replaced = String::from_utf8(SVG.to_vec()).unwrap().replace("C2 0", "C3 0"); - *s.clipboard = Some(Clip::from_svg(replaced.as_bytes()).unwrap()); + *s.clipboard = Some(clip_from_svg(replaced.as_bytes()).unwrap()); s.execute("edit.paste", json!({"as":"path"})).unwrap(); assert!(s.active().unwrap().doc.paths.last().unwrap().path.subpaths.iter().flat_map(|p| &p.knots).any(|k| k.out_ctrl == Point::new(8.0, 4.0))); s.execute("edit.undo", json!({})).unwrap(); @@ -193,17 +193,17 @@ fn invalid_modes_targets_and_capabilities_preserve_source_and_history() { rejected(&mut s, p); } let multi = br##""##; - *s.clipboard = Some(Clip::from_svg(multi).unwrap()); + *s.clipboard = Some(clip_from_svg(multi).unwrap()); rejected(&mut s, json!({"as":"shape"})); s.execute("edit.paste", json!({"as":"path"})).unwrap(); assert_eq!(s.active().unwrap().doc.paths.last().unwrap().path.subpaths.len(), 2); let opacity = br##""##; - *s.clipboard = Some(Clip::from_svg(opacity).unwrap()); + *s.clipboard = Some(clip_from_svg(opacity).unwrap()); for mode in ["path", "shape"] { rejected(&mut s, json!({"as":mode})); } let mut empty = Session::new(); - *empty.clipboard = Some(Clip::from_svg(SVG).unwrap()); + *empty.clipboard = Some(clip_from_svg(SVG).unwrap()); assert!(empty.execute("edit.paste", json!({"as":"pixels"})).is_err()); assert!(empty.active().is_none()); let mut locked = scene(8); @@ -227,16 +227,16 @@ fn invalid_modes_targets_and_capabilities_preserve_source_and_history() { /// Existing geometry and cache limits apply before publication, including intermediate caches. #[test] fn source_and_destination_work_limits_refuse_before_editing() { - assert!(Clip::from_svg(b"not svg").is_err()); - assert!(Clip::from_svg(&vec![b' '; 16 * 1024 * 1024 + 1]).is_err()); - assert!(Clip::from_svg(br##""##).is_err()); + assert!(clip_from_svg(b"not svg").is_err()); + assert!(clip_from_svg(&vec![b' '; 16 * 1024 * 1024 + 1]).is_err()); + assert!(clip_from_svg(br##""##).is_err()); let mut s = scene(8); let mut many = String::from(""); for _ in 0..1025 { many.push_str(""); } many.push_str(""); - *s.clipboard = Some(Clip::from_svg(many.as_bytes()).unwrap()); + *s.clipboard = Some(clip_from_svg(many.as_bytes()).unwrap()); assert!(rejected(&mut s, json!({"as":"path"})).contains("4096")); // The original position covers 36MP in this destination; the final position covers zero. let oversized = br##""##; @@ -246,7 +246,7 @@ fn source_and_destination_work_limits_refuse_before_editing() { doc.layers.push(Layer::raster("Pixels", doc.pixel_format())); let mut large = Session::new(); large.add_document(doc, None); - *large.clipboard = Some(Clip::from_svg(oversized).unwrap()); + *large.clipboard = Some(clip_from_svg(oversized).unwrap()); assert!(rejected(&mut large, json!({"as":"shape","center":[-10000,-10000]})).contains("cache exceeds 24 megapixels")); } @@ -354,7 +354,7 @@ fn recorded_pixels_paste(in_place: bool) -> Descriptor { fn recorded_pixels_paste_keeps_the_ordinary_route() { let mut s = Session::new(); s.execute("file.new", json!({"width": 20, "height": 16, "background": "transparent"})).unwrap(); - *s.clipboard = Some(Clip::from_svg(SVG).unwrap()); + *s.clipboard = Some(clip_from_svg(SVG).unwrap()); s.execute("edit.paste", json!({"as":"shape"})).unwrap(); s.execute("edit.copy", json!({})).unwrap(); assert_eq!(load(&mut s, &recorded(recorded_pixels_paste(false)))["unsupported"], json!([])); diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 3083119205..6be1f92cb1 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -57,7 +57,7 @@ impl PhotocraftApp { if self.os_clip_svg.as_deref().is_some_and(|old| old == &source) && holds_vectors_or_newer { return Ok(true); } - let clip = photocraft_engine::edit_cmds::Clip::from_svg(&source).map_err(|error| { + let clip = photocraft_engine::edit_cmds::clip_from_svg(&source).map_err(|error| { let error = error.to_string(); self.ui.status = error.clone(); self.ui.status_error = true; diff --git a/crates/ui-egui/src/menus/facts.rs b/crates/ui-egui/src/menus/facts.rs index aacc54fdfc..4456145246 100644 --- a/crates/ui-egui/src/menus/facts.rs +++ b/crates/ui-egui/src/menus/facts.rs @@ -222,7 +222,7 @@ impl<'a> RuleFacts<'a> { type_defaults: s.type_defaults.is_some(), measurement_log: s.analysis.log.is_empty(), mask_targeted: s.tools.mask_targeted, - actions: (s.actions.list.revision(), s.actions.recording, s.actions.playing), + actions: (s.actions.list.revision(), s.recording.target, s.recording.playing), undo_label: crate::actions::library::edit_undo_label(app), plugins: photocraft_plugins::registry::revision(), }, diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 12388f286b..777bbca655 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -238,7 +238,7 @@ pub(crate) fn new_action_set(app: &PhotocraftApp) -> Option { /// Start recording: into action `into`, or into a new action in [`new_action_set`] when `None`. /// The recorded action is selected and shown open, with its set open. pub(crate) fn begin_recording(app: &mut PhotocraftApp, into: Option) { - if app.session.actions.recording.is_some() { + if app.session.recording.target.is_some() { return; } let params = match into { @@ -355,7 +355,7 @@ fn apply_event(app: &mut PhotocraftApp, event: ActionsEvent) -> Result<(), Strin ActionsEvent::BeginRecording { into, .. } => begin_recording(app, into), ActionsEvent::NewAction => begin_recording(app, None), ActionsEvent::StopRecording => { - if !playback::stop(app) && app.session.actions.recording.is_some() { + if !playback::stop(app) && app.session.recording.target.is_some() { app.run("actions.stop", json!({}))?; } } diff --git a/crates/ui-egui/src/panels/actions/drag_drop_tests.rs b/crates/ui-egui/src/panels/actions/drag_drop_tests.rs index c549671a09..e8c850a783 100644 --- a/crates/ui-egui/src/panels/actions/drag_drop_tests.rs +++ b/crates/ui-egui/src/panels/actions/drag_drop_tests.rs @@ -49,7 +49,7 @@ fn action_dragged_onto_plus_adds_a_copy_after_it() { assert_eq!(steps(&app, 1), steps(&app, 0)); assert_eq!(app.ui.actions.panel.selected, Some(ActionSelection::Action(1))); assert!(app.ui.actions.panel.expanded.contains(&names[1]), "the copy is open as its source was"); - assert!(app.session.actions.recording.is_none()); + assert!(app.session.recording.target.is_none()); } #[test] diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index a078b627ee..a10935559e 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -59,7 +59,7 @@ pub(super) fn load_dialog(app: &mut PhotocraftApp) -> Result { // The panel menu greys this row while a recording or a paced playback holds the library (see // [`super::menu::states`]); a keyboard, shortcut or control-channel route says so before the // picker opens, since `actions.load` only refuses after it has read the chosen file. - if app.session.actions.recording.is_some() || app.session.actions.playing > 0 || super::playback::pending(app) { + if app.session.recording.target.is_some() || app.session.recording.playing > 0 || super::playback::pending(app) { return Err(tl!("Stop recording or playback before changing the Actions library.").into()); } let mut request = PickRequest::open_many("actions").filter("Actions", &["atn"]); diff --git a/crates/ui-egui/src/panels/actions/host.rs b/crates/ui-egui/src/panels/actions/host.rs index 0d4905376b..6d933fd91e 100644 --- a/crates/ui-egui/src/panels/actions/host.rs +++ b/crates/ui-egui/src/panels/actions/host.rs @@ -20,7 +20,7 @@ pub(crate) struct PhotoActions<'a> { impl<'a> PhotoActions<'a> { /// The host for this pass; `paced` is whether a paced playback waits for its next step. pub(crate) fn new(session: &'a Session, paced: bool) -> Self { - let recording = session.actions.recording.map(|(_, action)| action); + let recording = session.recording.target.map(|(_, action)| action); let pending = recording .map(|index| actions_cmds::pending_steps(session, index).map(|(id, params)| ActionStep::new(id.clone(), params.clone())).collect()) .unwrap_or_default(); @@ -76,6 +76,6 @@ impl ActionsHost for PhotoActions<'_> { } fn playing(&self) -> bool { - self.session.actions.playing > 0 || self.paced + self.session.recording.playing > 0 || self.paced } } diff --git a/crates/ui-egui/src/panels/actions/library.rs b/crates/ui-egui/src/panels/actions/library.rs index 3581b4a34d..5caff25cdb 100644 --- a/crates/ui-egui/src/panels/actions/library.rs +++ b/crates/ui-egui/src/panels/actions/library.rs @@ -73,7 +73,7 @@ pub(crate) fn idle(app: &PhotocraftApp, command: &str) -> Result<(), String> { let paused = &app.paused_playbacks.paused; let editor = paused.values().any(|p| p.menu_editor.is_some()); let spelling = app.ui.type_panels.spell.as_ref().and_then(|spell| spell.resume).is_some_and(|token| paused.contains_key(&token)); - if app.session.actions.recording.is_some() || app.session.actions.playing > 0 || super::playback::pending(app) || editor || spelling { + if app.session.recording.target.is_some() || app.session.recording.playing > 0 || super::playback::pending(app) || editor || spelling { return Err(tl!("Stop recording or playback before changing the Actions library.").into()); } Ok(()) diff --git a/crates/ui-egui/src/panels/actions/menu.rs b/crates/ui-egui/src/panels/actions/menu.rs index 6961d913f7..f22bb2e749 100644 --- a/crates/ui-egui/src/panels/actions/menu.rs +++ b/crates/ui-egui/src/panels/actions/menu.rs @@ -11,10 +11,10 @@ use crate::PhotocraftApp; fn facts(app: &PhotocraftApp) -> ActionsMenuFacts { let path_selected = app.ui.selected_path.as_deref().is_some_and(|name| actions_edit_cmds::selected_recording_path(&app.session, name).is_ok()); ActionsMenuFacts::new() - .recording(app.session.actions.recording.is_some()) + .recording(app.session.recording.target.is_some()) .path_selected(path_selected) .waiting(super::playback::pending(app)) - .tool_recording(app.session.actions.record_tools) + .tool_recording(app.session.recording.record_tools) } /// Whether the app offers `command`: Set Options…, Batch… and Button Mode have no counterpart here. diff --git a/crates/ui-egui/src/panels/actions/playback.rs b/crates/ui-egui/src/panels/actions/playback.rs index 1ab7b5ee26..b6b66bbe90 100644 --- a/crates/ui-egui/src/panels/actions/playback.rs +++ b/crates/ui-egui/src/panels/actions/playback.rs @@ -102,7 +102,7 @@ pub(crate) fn stop(app: &mut PhotocraftApp) -> bool { pub(crate) fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { let Some(timer) = app.paused_playbacks.timer else { return }; let esc = !app.dialog_open() && crate::window_keys::take_escape(ctx); - let changed = timer.rev != app.session.actions.list.revision() || app.session.actions.recording.is_some(); + let changed = timer.rev != app.session.actions.list.revision() || app.session.recording.target.is_some(); if esc || changed || !app.paused_playbacks.paused.contains_key(&timer.token) { stop(app); return; diff --git a/crates/ui-egui/src/panels/actions/playback_tests.rs b/crates/ui-egui/src/panels/actions/playback_tests.rs index 3e05319776..94f50bc68e 100644 --- a/crates/ui-egui/src/panels/actions/playback_tests.rs +++ b/crates/ui-egui/src/panels/actions/playback_tests.rs @@ -39,8 +39,8 @@ fn esc() -> egui::Event { } fn assert_idle(app: &PhotocraftApp) { - assert_eq!(app.session.actions.playing, 0); - assert!(app.session.actions.playback_stack.is_empty()); + assert_eq!(app.session.recording.playing, 0); + assert!(app.session.recording.playback_stack.is_empty()); assert!(app.paused_playbacks.paused.is_empty()); assert!(app.paused_playbacks.timer.is_none()); } diff --git a/crates/ui-egui/src/panels/actions/record_again.rs b/crates/ui-egui/src/panels/actions/record_again.rs index a87e317134..2b8936a22b 100644 --- a/crates/ui-egui/src/panels/actions/record_again.rs +++ b/crates/ui-egui/src/panels/actions/record_again.rs @@ -34,8 +34,8 @@ fn authorize(app: &PhotocraftApp, held: &Held, id: &str, params: &Value) -> Resu fn unchanged(app: &PhotocraftApp, held: &Held) -> Result<(), String> { super::suspended_guard(app, COMMAND)?; if held.selection.get("revision").and_then(Value::as_u64) != Some(app.session.actions.list.revision()) - || app.session.actions.recording.is_some() - || app.session.actions.playing > 0 + || app.session.recording.target.is_some() + || app.session.recording.playing > 0 { return Err(tl!("The actions changed. Request Record Again again.").into()); } diff --git a/crates/ui-egui/src/panels/actions/runner.rs b/crates/ui-egui/src/panels/actions/runner.rs index ffce7c8641..950cf8bde3 100644 --- a/crates/ui-egui/src/panels/actions/runner.rs +++ b/crates/ui-egui/src/panels/actions/runner.rs @@ -673,7 +673,7 @@ fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { let list = app.session.actions.list.actions(); let target = if list.get(idx).is_some_and(|a| a.name == into) { Some(idx) } else { list.iter().position(|a| a.name == into) }; if let Some(idx) = target - && app.session.actions.recording.is_none() + && app.session.recording.target.is_none() { actions_cmds::restore_recording(&mut app.session, idx, name, from); } diff --git a/crates/ui-egui/src/panels/actions/runner_tests.rs b/crates/ui-egui/src/panels/actions/runner_tests.rs index 7bcb642197..5b6cf5f076 100644 --- a/crates/ui-egui/src/panels/actions/runner_tests.rs +++ b/crates/ui-egui/src/panels/actions/runner_tests.rs @@ -195,7 +195,7 @@ fn single_history_dialog_confirmation_and_cancel() { assert!(app.session.redo()); assert_eq!(app.session.active().unwrap().doc.as_ref(), after.as_ref()); assert!(app.paused_playbacks.paused.is_empty()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); let count = app.session.active().unwrap().history.past_len(); app.session.execute("layer.renameLayer", json!({"name":"Outside"})).unwrap(); assert_eq!(app.session.active().unwrap().history.past_len(), count + 1); @@ -229,7 +229,7 @@ fn single_history_dialog_refuses_intervening_edit_or_document_switch() { assert_eq!(app.session.active().unwrap().history.entries(), history); assert!(app.filter_preview.is_none()); assert!(app.paused_playbacks.paused.is_empty()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); } } @@ -273,7 +273,7 @@ fn paused_spelling_repeated_changes_and_errors_keep_one_owned_history() { spelling_change(&mut app, params).unwrap(); let token = app.ui.type_panels.spell.as_ref().unwrap().resume.unwrap(); assert!(app.paused_playbacks.paused[&token].history.is_some()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); } let st = app.session.active().unwrap(); let texts: Vec<_> = st @@ -311,7 +311,7 @@ fn paused_spelling_repeated_changes_and_errors_keep_one_owned_history() { #[test] fn spelling_playback_blocks_library_edits_until_done() { let (mut app, _, _) = paused_history_spelling(false, None); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); let error = app.run("actions.clearAll", json!({"confirm": true})).unwrap_err(); assert_eq!(app.ui.status, error); assert!(app.ui.status_error); @@ -356,7 +356,7 @@ fn paused_spelling_rejects_external_edit_switch_and_original_gate_before_change( } close_spelling(&mut app); assert!(app.paused_playbacks.paused.is_empty()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); if scenario == "gate" { assert_eq!(app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().name, "Tail"); } else { @@ -420,8 +420,8 @@ fn nested_shell_actions_include_view_steps_and_propagate_failures() { 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); + assert!(app.session.recording.playback_stack.is_empty()); + assert_eq!(app.session.recording.playing, 0); app.session.authorize = None; let dir = tempfile::tempdir().unwrap(); @@ -527,7 +527,7 @@ fn view_action_failure_resume_and_authorization() { 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); + assert_eq!(app.session.recording.playing, 0); app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); app.session.authorize = Some( @@ -542,7 +542,7 @@ fn view_action_failure_resume_and_authorization() { assert_eq!(result["ran"], 1); assert_eq!(app.ui.views[0].pending.last(), Some(&ViewRequest::Command(ViewCommands::ActualPixels)), "played from step 1: no fit after 100%"); assert!(app.run("actions.play", json!({"action": 0, "from": -1})).is_err()); - app.session.actions.playing = 1; + app.session.recording.playing = 1; assert!(app.run("actions.play", json!({"action": 0})).is_err()); } @@ -980,8 +980,8 @@ fn dialog_worker_failure_stops_action_before_following_steps() { } else { assert!(result.is_ok(), "the successful worker lets the action continue: {result:?}"); } - assert_eq!(app.session.actions.playing, 0); - assert!(app.session.actions.playback_stack.is_empty()); + assert_eq!(app.session.recording.playing, 0); + assert!(app.session.recording.playback_stack.is_empty()); } } @@ -1260,7 +1260,7 @@ fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() { // Confirm: the dialog command and the resumed rest stay inside the one named call. let live = app.session.journal.len(); let id = pause_child(&mut app); - assert!(app.session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); + assert!(app.session.recording.target.is_none(), "recording stays suspended while the step dialog is open"); let names = |app: &PhotocraftApp| app.session.actions.list.actions().iter().map(|a| a.name.clone()).collect::>(); let before = names(&app); assert_eq!(app.run("actions.record", json!({"name": "Intruder"})), Err(refusal.clone()), "no second recording while the call is suspended"); @@ -1268,7 +1268,7 @@ fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() { assert_eq!(app.run("actions.move", json!({"action": "Owner", "to": 0})), Err(refusal.clone()), "the suspended owner can't be moved"); assert_eq!(names(&app), before, "the refused commands leave the list alone"); answer_ok(&mut app, id).unwrap(); - assert!(app.session.actions.recording.is_some(), "recording comes back when the call completes"); + assert!(app.session.recording.target.is_some(), "recording comes back when the call completes"); app.run("actions.stop", json!({})).unwrap(); assert_eq!(pairs(&app, 1), child_call()); assert_eq!(suffixes(&app), 1); @@ -1292,7 +1292,7 @@ fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() { app.run("actions.record", json!({"name": "Cancelled"})).unwrap(); let id = pause_child(&mut app); answer_cancel(&mut app, id).unwrap(); - assert!(app.session.actions.recording.is_some(), "cancel restores recording"); + assert!(app.session.recording.target.is_some(), "cancel restores recording"); app.run("actions.stop", json!({})).unwrap(); assert_eq!(pairs(&app, 2), child_call()); } @@ -1301,11 +1301,11 @@ fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() { fn a_failing_step_dialog_command_ends_the_recorded_call_once() { let mut app = recording_with_dialog_child(); let id = pause_child(&mut app); - assert!(app.session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); + assert!(app.session.recording.target.is_none(), "recording stays suspended while the step dialog is open"); // The dialog takes only values its row accepts, so the command fails on the document: the layer it filters is locked. app.run("layer.lockLayers", json!({"all": true})).unwrap(); assert!(answer_ok(&mut app, id).is_err(), "the dialog command fails"); - assert!(app.session.actions.recording.is_some(), "recording comes back when the dialog command fails"); + assert!(app.session.recording.target.is_some(), "recording comes back when the dialog command fails"); assert_eq!(suffixes(&app), 0, "the action stops at the failed step"); app.run("actions.stop", json!({})).unwrap(); assert_eq!(pairs(&app, 1), child_call()); @@ -1331,7 +1331,7 @@ fn a_failing_resumed_playback_ends_the_recorded_call_once() { // The rest of the call can't be found any more: resuming it fails. app.session.actions.list.rename(0, "Renamed", |_, _, _| {}).unwrap(); assert!(answer_ok(&mut app, id).is_err(), "the resumed playback fails"); - assert!(app.session.actions.recording.is_some(), "recording comes back when the resumed playback fails"); + assert!(app.session.recording.target.is_some(), "recording comes back when the resumed playback fails"); app.run("actions.stop", json!({})).unwrap(); assert_eq!(pairs(&app, 1), child_call()); } @@ -1360,11 +1360,11 @@ fn escape_on_a_step_dialog_ends_the_recorded_call_once() { h.run_steps(2); pause_child(h.state_mut()); h.run_steps(4); - assert!(h.state().session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); + assert!(h.state().session.recording.target.is_none(), "recording stays suspended while the step dialog is open"); h.key_press(egui::Key::Escape); h.run_steps(2); assert!(!h.state().dialog_open(), "Esc closes the step dialog"); - assert!(h.state().session.actions.recording.is_some(), "Esc restores recording"); + assert!(h.state().session.recording.target.is_some(), "Esc restores recording"); let app = h.state_mut(); app.run("actions.stop", json!({})).unwrap(); assert_eq!(pairs(app, 1), child_call()); @@ -1417,7 +1417,7 @@ fn assert_displace_call_finished(app: &mut PhotocraftApp, suffix_count: usize) { assert!(!app.file_dialog_open()); assert!(!app.dialog_open()); assert!(app.paused_playbacks.paused.is_empty()); - assert!(app.session.actions.recording.is_some()); + assert!(app.session.recording.target.is_some()); assert_eq!(suffixes(app), suffix_count); app.run("actions.stop", json!({})).unwrap(); assert_eq!(pairs(app, 1), child_call(), "record the child call exactly once"); @@ -1440,7 +1440,7 @@ fn a_displace_step_restores_recording_when_the_map_picker_fails_or_is_cancelled( let id = pause_child(&mut app); answer_ok(&mut app, id).unwrap(); assert!(app.file_dialog_open()); - assert!(app.session.actions.recording.is_none()); + assert!(app.session.recording.target.is_none()); app.poll_file_dialog(); assert_displace_call_finished(&mut app, 0); } @@ -1543,7 +1543,7 @@ fn a_paused_dialog_authorizes_edited_params_before_history_or_worker_admission() assert!(app.session.job_on(state.doc.id).is_none(), "no worker was admitted"); assert!(app.session.authorize.is_none()); assert!(app.paused_playbacks.paused.is_empty()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); app.run("layer.renameLayer", json!({"name": "Outside"})).unwrap(); assert_eq!(app.session.active().unwrap().history.past_len(), count + 1, "no action scope leaked"); } @@ -1567,7 +1567,7 @@ fn an_allowed_paused_edit_and_an_ordinary_manual_dialog_still_run() { assert!(app.session.job_on(state.doc.id).is_none(), "the resumed action waited for its worker"); assert!(app.session.authorize.is_none(), "the transient captured gate was restored"); assert!(app.paused_playbacks.paused.is_empty()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); } } @@ -1659,7 +1659,7 @@ fn a_changed_live_gate_cannot_be_replaced_for_the_remaining_action() { assert!(app.session.undo()); assert_eq!(app.session.active().unwrap().doc.as_ref(), before.as_ref()); assert!(app.paused_playbacks.paused.is_empty()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); } } } @@ -1741,7 +1741,7 @@ fn configured_gates_require_one_composed_policy_for_automated_resume() { assert!(std::ptr::fn_addr_eq(app.session.authorize.unwrap(), deny_wide_blur as Gate)); assert!(std::ptr::fn_addr_eq(app.services.automation_authorize.unwrap(), service)); assert!(app.paused_playbacks.paused.is_empty()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); } } @@ -1906,7 +1906,7 @@ fn an_implicit_paused_filter_refuses_a_public_api_receiver_change() { assert_eq!(after.as_ref(), before.as_ref(), "neither layer may be edited after stale implicit targeting"); } assert!(app.paused_playbacks.paused.is_empty()); - assert_eq!(app.session.actions.playing, 0); + assert_eq!(app.session.recording.playing, 0); } } } @@ -2152,7 +2152,7 @@ fn save_hook_closing_the_target_stops_an_imported_close_with_save() { } else { assert!(r.get("failed").is_none(), "hook={hook}: {r}"); } - assert_eq!(app.session.actions.playing, 0); - assert!(app.session.actions.playback_stack.is_empty()); + assert_eq!(app.session.recording.playing, 0); + assert!(app.session.recording.playback_stack.is_empty()); } } diff --git a/crates/ui-egui/src/panels/actions/stop_tests.rs b/crates/ui-egui/src/panels/actions/stop_tests.rs index 6c2dd09bd0..d83a00202d 100644 --- a/crates/ui-egui/src/panels/actions/stop_tests.rs +++ b/crates/ui-egui/src/panels/actions/stop_tests.rs @@ -60,8 +60,8 @@ fn nested_app(allow: bool) -> Box { } pub(super) fn assert_idle(app: &PhotocraftApp) { - assert_eq!(app.session.actions.playing, 0); - assert!(app.session.actions.playback_stack.is_empty()); + assert_eq!(app.session.recording.playing, 0); + assert!(app.session.recording.playback_stack.is_empty()); assert!(app.paused_playbacks.paused.is_empty()); assert!(!app.dialog_open()); } @@ -166,12 +166,12 @@ fn a_stop_restores_a_suspended_recording_once_for_every_exit() { app.run("actions.record", json!({"name": "Owner"})).unwrap(); let v = play(&mut app, &json!({"action": "Stop Test"})).unwrap(); assert_eq!(v["paused"]["step"], 1, "{v}"); - assert!(app.session.actions.recording.is_none()); + assert!(app.session.recording.target.is_none()); { let prompt = stop_prompt(&app); answer(&mut app, prompt, confirm).unwrap(); } - assert!(app.session.actions.recording.is_some()); + assert!(app.session.recording.target.is_some()); app.run("actions.stop", json!({})).unwrap(); let owner = app.session.actions.list.actions().iter().find(|a| a.name == "Owner").unwrap(); assert_eq!(owner.steps, vec![ActionStep::new("actions.play", json!({"action": "Stop Test"}))]); @@ -199,7 +199,7 @@ fn continue_inside_a_called_action_finishes_every_caller_once() { assert_eq!(prompts_open(&app), 1, "Parent goes on into its own Stop"); let second = stop_prompt(&app); assert_ne!(second, first, "Parent's Stop is a prompt of its own"); - assert!(app.session.actions.recording.is_none(), "recording stays suspended through both pauses"); + assert!(app.session.recording.target.is_none(), "recording stays suspended through both pauses"); answer(&mut app, second, true).unwrap(); assert_idle(&app); let edits: Vec<_> = app.session.journal.iter().filter(|(id, _)| id == "layer.new.layer").map(|(_, p)| p["name"].as_str().unwrap().to_string()).collect(); @@ -208,7 +208,7 @@ fn continue_inside_a_called_action_finishes_every_caller_once() { let st = app.session.active().unwrap(); assert_eq!(st.history.past_len(), history + 1); assert_eq!(st.history.undo_label(), Some("Action: Grandparent")); - assert!(app.session.actions.recording.is_some()); + assert!(app.session.recording.target.is_some()); app.run("actions.stop", json!({})).unwrap(); let owner = app.session.actions.list.actions().iter().find(|a| a.name == "Owner").unwrap(); assert_eq!(owner.steps, vec![ActionStep::new("actions.play", json!({"action": "Grandparent"}))]); diff --git a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs index 9b4a6e2d0f..1968305985 100644 --- a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs +++ b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs @@ -125,7 +125,7 @@ pub(crate) fn close_spelling(app: &mut PhotocraftApp, ctx: &egui::Context) { } let Some(d) = app.ui.type_panels.spell.take() else { return }; let mut recording_error = None; - if app.session.actions.recording.is_some() && run(app, "edit.checkSpelling", json!({ "allLayers": d.all_layers })).is_none() { + if app.session.recording.target.is_some() && run(app, "edit.checkSpelling", json!({ "allLayers": d.all_layers })).is_none() { recording_error = Some(app.ui.status.clone()); } if let Some(token) = d.resume { diff --git a/crates/ui-egui/src/prefs/prefs_ui/startup.rs b/crates/ui-egui/src/prefs/prefs_ui/startup.rs index 277e06a07d..c19dee2210 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/startup.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/startup.rs @@ -220,7 +220,7 @@ pub(super) fn presets_store(app: &mut PhotocraftApp) { Err(std::sync::mpsc::TryRecvError::Disconnected) => app.services.preset_store = None, } } - if let Some(w) = app.session.preset_store.as_mut().map(|s| s.take_warnings()).and_then(|w| w.into_iter().next()) { + if let Some(w) = app.session.preset_store_mut().map(|s| s.take_warnings()).and_then(|w| w.into_iter().next()) { app.ui.status = w; } } diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 4f57c45f55..b9382ee221 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -974,7 +974,7 @@ fn restart_cases() -> Vec { assert!(early.files.lock().unwrap().is_empty()); tx.send(photocraft_engine::preset_store::open(Box::new(early.clone()))).unwrap(); tick(app, ctx); - assert!(app.services.preset_store.is_none() && app.session.preset_store.is_some()); + assert!(app.services.preset_store.is_none() && app.session.preset_store().is_some()); app.run("brush.presets.save", json!({"name": "Late"})).unwrap(); }), check: Box::new(move |_, _, _| { diff --git a/crates/ui-egui/tests/it/actions_duplicate.rs b/crates/ui-egui/tests/it/actions_duplicate.rs index 347a079c1d..c3ae109d3d 100644 --- a/crates/ui-egui/tests/it/actions_duplicate.rs +++ b/crates/ui-egui/tests/it/actions_duplicate.rs @@ -64,13 +64,13 @@ fn duplicate_cannot_shift_the_owner_of_a_suspended_recording() { let result = app.run("actions.play", json!({"action": "Menu"})).unwrap(); let dialog = result["paused"]["dialog"].clone(); let list = app.session.actions.list.clone(); - assert!(app.session.actions.recording.is_none()); + assert!(app.session.recording.target.is_none()); let error = app.run("actions.duplicate", json!({"action": "Menu"})).unwrap_err(); assert!(error.contains("Confirm or cancel"), "{error}"); assert_eq!(app.session.actions.list, list); let app_ctx = app.ctx().clone(); let cancelled = control(&mut app, &app_ctx, "ui.dialog.cancel", json!({"dialog": dialog})); assert_eq!(cancelled["ok"], true, "{cancelled}"); - assert_eq!(app.session.actions.recording.map(|(_, i)| i), Some(1)); + assert_eq!(app.session.recording.target.map(|(_, i)| i), Some(1)); app.run("actions.stop", json!({})).unwrap(); } diff --git a/crates/ui-egui/tests/it/actions_panel_menu.rs b/crates/ui-egui/tests/it/actions_panel_menu.rs index 337547ffb4..bc60979f5b 100644 --- a/crates/ui-egui/tests/it/actions_panel_menu.rs +++ b/crates/ui-egui/tests/it/actions_panel_menu.rs @@ -60,7 +60,7 @@ fn allow_tool_recording_checkbox_records_only_enabled_strokes() { h.state_mut().run("actions.record", json!({"action":"A"})).unwrap(); for enabled in [true, false] { fire(&mut h, ActionsPanelCommands::ToolRecording); - assert_eq!(h.state().session.actions.record_tools, enabled); + assert_eq!(h.state().session.recording.record_tools, enabled); h.state_mut().run("paint.stroke", json!({"points":[[2,3],[10,3]],"size":2,"color":if enabled {"#ff0000"} else {"#00ff00"}})).unwrap(); } h.state_mut().run("actions.stop", json!({})).unwrap(); diff --git a/scripts/engine_split/session_state.py b/scripts/engine_split/session_state.py new file mode 100755 index 0000000000..0cba5639df --- /dev/null +++ b/scripts/engine_split/session_state.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""Engine split, step 5: `Session` state. + +The action recording and playback state left `ActionState` (`s.actions`) for the core type +`ActionRecording` (`s.recording`); the journal mark `recording` is called `target` there. Small +state types moved to `crates/engine-core/src/state.rs` (their old paths are re-exported), the +action-history bookkeeping to `action_history.rs`, and the stored-preferences document with the +methods that combine preferences, colour settings and presets to `prefs/saved.rs`. +`Clip::from_svg` is the free function `edit_cmds::clip_from_svg`, and the preset store is a session +slot read through `preset_store::PresetStoreExt` (`s.preset_store()`, `s.preset_store_mut()`). + + python3 scripts/engine_split/session_state.py split + Rewrites every Rust file under `crates/` and `apps/`: the recording fields, + `Clip::from_svg` and the preset store field. The rest of the step (type moves, slots, hooks) is hand-written, its + own commit. + + python3 scripts/engine_split/session_state.py branch --base --head + On a branch rebased onto the step. `--head` is the branch commit from before the rebase + (`ORIG_HEAD` right after it). Rewrites the files the branch changed, and lists the + branch's edits to definitions that moved (re-apply those in the new file). + +Running either mode twice gives the same result. What it cannot do is printed at the end of +every run. +""" +import argparse, os, re, subprocess, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from rust_source import git # noqa: E402 + +FIELDS = ["record_tools", "recording", "take", "playing", "playback_stack", "playback_steps", "budget_shared", "batch_depth", "script_depth", "script_steps"] +RENAMED = {"recording": "target"} +RECORDING = re.compile(r"\.actions\.(" + "|".join(FIELDS) + r")\b") +FROM_SVG = re.compile(r"\bedit_cmds::Clip::from_svg\(") +BARE_FROM_SVG = re.compile(r"(?` now; + - a file that now calls `preset_store()` / `preset_store_mut()` needs + `use photocraft_engine::preset_store::PresetStoreExt;` (`crate::preset_store::...` in core); + - an assignment to the old field (`s.preset_store = Some(store)`): attach a store with + `Session::attach_preset_store`, which keeps it in the preset store slot; + - edits to a moved definition: re-apply them in the new file named above; + - a new `Session` field: a plain core field when the pipeline reads it, else a slot its crate + registers (`Install::slot`, read through the crate's extension trait). +""" + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="mode", required=True) + sub.add_parser("split") + b = sub.add_parser("branch") + b.add_argument("--base", required=True) + b.add_argument("--head", required=True) + args = ap.parse_args() + os.chdir(git("rev-parse", "--show-toplevel").strip()) + if args.mode == "split": + split() + else: + branch(args.base, args.head) + for line in REPORT: + print(line) + print(CANNOT_DO) + + +if __name__ == "__main__": + main()