PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Keep a paused action playback's automation gate when it resumes
James Chapmandbacc5a7951d
diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rsindex 3e946b0d7..9b600758b 100644--- a/crates/ui-egui/src/actions.rs+++ b/crates/ui-egui/src/actions.rs@@ -98,7 +98,7 @@ pub(crate) fn play(app: &mut PhotocraftApp, params: &Value) -> Result<Value, Strplay_owned(app, params, None)}-/// `suspended` is the recording a paused part of the same call took (`RECORD`); it comes+/// `suspended` is the recording a paused part of the same call took ([`PausedPlayback::record`]); it comes/// back, with that named call journaled, only when the whole call ends.fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option<Value>) -> Result<Value, String> {let (action, from) = match actions_cmds::playback_plan(&app.session, params) {@@ -134,11 +134,12 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option<Value>)if action.dialogs.contains(&i) && !app.automation_input && (crate::filter_dialog::has_dialog(id) || crate::adjust_dialog::has_dialog(id)) {let label = label_of(id);let dialog = crate::dialogs::open_command_dialog(app, id, &label);+ let token = app.paused_playbacks.pause(action.name.clone(), i + 1, app.session.authorize);if let Some(d) = app.ui.dialog_mut(dialog) {if let Some(o) = p.as_object() {d.fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));}- d.fields.insert(RESUME.into(), json!({"action": action.name, "from": i + 1}));+ d.fields.insert(RESUME.into(), json!(token));}paused = Some(json!({"step": i, "id": id, "dialog": dialog}));break;@@ -186,13 +187,14 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option<Value>)actions_cmds::finish_playback(&mut app.session, None, &action, from);match paused.as_ref().and_then(|p| p.get("dialog")).and_then(Value::as_u64).and_then(|d| app.ui.dialog_mut(d)) {// Paused for a dialog: the call goes on after it, so recording stays suspended.- Some(d) if failed.is_none() => match (owner, d.fields.get_mut(RESUME)) {- (Some(owner), Some(Value::Object(r))) => {- r.insert(RECORD.into(), owner);+ Some(d) if failed.is_none() => {+ let entry = d.fields.get(RESUME).and_then(Value::as_u64).and_then(|t| app.paused_playbacks.paused.get_mut(&t));+ match (owner, entry) {+ (Some(owner), Some(p)) => p.record = Some(owner),+ // No continuation to carry the recording: the call ends here.+ (owner, _) => restore_recording(app, owner.as_ref()),}- // No continuation to carry the recording: the call ends here.- (owner, _) => restore_recording(app, owner.as_ref()),- },+ }_ => restore_recording(app, owner.as_ref()),}Ok(match (failed, paused) {@@ -478,16 +480,9 @@ pub fn insert_stop_confirm(app: &mut PhotocraftApp, fields: &serde_json::Map<StrOk(r)}-/// The key a paused playback leaves in its dialog's fields: `{action, from}`.+/// The key a paused playback leaves in its dialog's fields: the token of its [`PausedPlayback`].pub const RESUME: &str = "__resumeAction";-/// The recording a paused call suspended, kept in its `RESUME` entry:-/// `{index, into, action, from}` (`into` is the name of the action being recorded).-/// A step dialog only closes through `dialogs::confirm` (OK, `↩`, automation) or-/// `dialogs::cancel` (Cancel, Esc, the close box, automation), which end the call through-/// `resume`, `abandoned` or `stopped`, so the recording comes back exactly once.-const RECORD: &str = "record";-/// Resume the recording a paused call suspended and journal that call, once.fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) {let Some(owner) = owner else { return };@@ -511,9 +506,9 @@ fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) {}}-/// Whether a step dialog holds a suspended recording.+/// Whether a paused playback holds a suspended recording.fn suspended(app: &PhotocraftApp) -> bool {- app.ui.dialogs.iter().any(|d| d.fields.get(RESUME).and_then(|r| r.get(RECORD)).is_some())+ app.paused_playbacks.paused.values().any(|p| p.record.is_some())}/// While a step dialog holds a suspended recording, refuse what would lose its call: a new@@ -529,13 +524,58 @@ pub(crate) fn suspended_guard(app: &PhotocraftApp, id: &str) -> Result<(), Strin/// A step dialog's command failed: the action ends there.pub fn abandoned(app: &mut PhotocraftApp, fields: &serde_json::Map<String, Value>) {- restore_recording(app, fields.get(RESUME).and_then(|r| r.get(RECORD)));+ let record = fields.get(RESUME).and_then(Value::as_u64).and_then(|t| app.paused_playbacks.paused.get(&t)).and_then(|p| p.record.clone());+ restore_recording(app, record.as_ref());+}++/// The automation gate a session installs ([`photocraft_engine::Session::authorize`]).+type Gate = fn(&str, &Value) -> photocraft_engine::Result<()>;++/// A playback paused at a step dialog: the action and step it continues from, and the gate it+/// was playing under (`None` for one a person started).+#[derive(Clone, Debug)]+pub(crate) struct PausedPlayback {+ action: String,+ from: usize,+ gate: Option<Gate>,+ /// The recording the paused call suspended: `{index, into, action, from}` (`into` is the+ /// name of the action being recorded). A step dialog only closes through+ /// `dialogs::confirm` (OK, `↩`, automation) or `dialogs::cancel` (Cancel, Esc, the close+ /// box, automation), which end the call through `resume`, `abandoned` or `stopped`, so the+ /// recording comes back exactly once.+ record: Option<Value>,+}++/// The paused playbacks, by the token their dialog carries. The dialog's fields hold only the+/// token; what plays next, and under which gate, is kept here.+#[derive(Debug, Default)]+pub(crate) struct PausedPlaybacks {+ last: u64,+ paused: std::collections::HashMap<u64, PausedPlayback>,+}++impl PausedPlaybacks {+ fn pause(&mut self, action: String, from: usize, gate: Option<Gate>) -> u64 {+ self.last = self.last.wrapping_add(1);+ self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None });+ self.last+ }++ fn take(&mut self, token: &Value) -> Option<PausedPlayback> {+ token.as_u64().and_then(|token| self.paused.remove(&token))+ }}/// A step dialog confirmed: continue the action after it (`dialogs::confirm` calls this).+///+/// The remaining steps run under the gate the playback paused with, however the dialog was+/// confirmed: a control request, synthetic Enter or OK, or a click.pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map<String, Value>) -> Result<(), String> {- let Some(r) = fields.get(RESUME) else { return Ok(()) };- let owner = r.get(RECORD).cloned();+ let Some(token) = fields.get(RESUME) else { return Ok(()) };+ let Some(paused) = app.paused_playbacks.take(token) else {+ return Err("this dialog doesn't belong to a paused action".into());+ };+ let owner = paused.record.clone();// The dialog's command may run as a background job; the next step needs its result.if let Some(doc) = app.session.active().map(|d| d.doc.id)&& let Some(job) = app.session.job_on(doc)@@ -547,8 +587,12 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map<String, Value>)app.ui.status_error = true;return Err(e.to_string());}- let params = json!({"action": r.get("action").cloned().unwrap_or(Value::Null), "from": r.get("from").cloned().unwrap_or(Value::Null)});- match play_owned(app, ¶ms, owner) {+ let params = json!({"action": paused.action, "from": paused.from});+ let saved = app.session.authorize;+ app.session.authorize = paused.gate.or(saved);+ let played = play_owned(app, ¶ms, owner);+ app.session.authorize = saved;+ match played {Ok(v) => {report_play(app, &v);Ok(())@@ -564,8 +608,9 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map<String, Value>)/// A step dialog cancelled: the action stops there, as in Photoshop.pub fn stopped(app: &mut PhotocraftApp, fields: &serde_json::Map<String, Value>) {- if fields.contains_key(RESUME) {- abandoned(app, fields);+ if let Some(token) = fields.get(RESUME) {+ let record = app.paused_playbacks.take(token).and_then(|p| p.record);+ restore_recording(app, record.as_ref());app.ui.status = tl!("Action playback stopped").to_string();app.ui.status_error = false;}@@ -1821,7 +1866,7 @@ mod tests {let id = v["paused"]["dialog"].as_u64().unwrap();let d = app.ui.dialog_mut(id).unwrap();assert_eq!(d.fields["radius"], 3, "the dialog opens on the recorded values");- assert_eq!(d.fields[RESUME], json!({"action": "Blur", "from": 2}));+ assert!(d.fields[RESUME].is_u64(), "the dialog carries only the pause's token: {}", d.fields[RESUME]);assert!(app.session.active().unwrap().doc.selection.is_none(), "nothing after the dialog ran yet");report_play(&mut app, &v);assert!(app.ui.status.contains("dialog"), "{}", app.ui.status);@@ -1982,6 +2027,48 @@ mod tests {assert_eq!(app.session.actions.list[1].steps, child_call());}+ fn deny_select_all(id: &str, _: &Value) -> photocraft_engine::Result<()> {+ if id == "select.all" { Err(photocraft_engine::EngineError::Other("select.all denied".into())) } else { Ok(()) }+ }++ /// An action an automation client plays (`control::handle` installs the gate, then removes+ /// it) pauses at a step dialog; confirming the dialog later, here with synthetic Enter or+ /// OK, runs the remaining steps under the same gate.+ #[test]+ fn a_paused_playback_keeps_its_automation_gate_when_the_dialog_is_confirmed() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 16, "height": 16})).unwrap();+ let mut a = Action::new("Seeded", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("select.all".into(), json!({}))]);+ a.dialogs.insert(0);+ app.session.actions.list.push(a);+ app.session.authorize = Some(deny_select_all);+ let v = play(&mut app, &json!({"action": "Seeded"})).unwrap();+ app.session.authorize = None;+ let id = v["paused"]["dialog"].as_u64().unwrap();+ app.automation_input = true;+ let _ = crate::dialogs::confirm(&mut app, id);+ app.automation_input = false;+ assert!(app.session.active().unwrap().doc.selection.is_none(), "the denied step did not run");+ assert!(app.ui.status.contains("select.all denied"), "{}", app.ui.status);+ }++ /// The dialog names only its pause: changing its fields can't resume another action.+ #[test]+ fn a_step_dialog_resumes_only_the_playback_that_paused_it() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 16, "height": 16})).unwrap();+ let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]);+ a.dialogs.insert(0);+ app.session.actions.list.push(a);+ app.session.actions.list.push(Action::new("Seeded", vec![("select.all".into(), json!({}))]));+ let v = play(&mut app, &json!({"action": "Blur"})).unwrap();+ let id = v["paused"]["dialog"].as_u64().unwrap();+ app.ui.dialog_mut(id).unwrap().fields.insert(RESUME.into(), json!({"action": "Seeded", "from": 0}));+ let r = crate::dialogs::confirm(&mut app, id);+ assert!(app.session.active().unwrap().doc.selection.is_none(), "the other action did not play");+ assert!(r.is_err_and(|e| e.contains("paused action")));+ }+#[test]fn button_mode_plays_the_clicked_action_and_hides_its_steps() {use egui_kittest::{Harness, kittest::Queryable};diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 0b8e35870..6ea5992d4 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -856,6 +856,9 @@ pub struct PhotocraftApp {/// makes shortcut- and dialog-triggered commands pass the same policy as/// direct control calls.pub(crate) automation_input: bool,+ /// Action playbacks paused at a step dialog, by the token in that dialog's fields+ /// ([`actions::RESUME`]): what to play next and the automation gate it paused under.+ pub(crate) paused_playbacks: actions::PausedPlaybacks,/// Levels/Curves histogram cache: (document, adjustment layer, revision it is valid for).pub(crate) tone_hist: Option<(DocId, photocraft_doc::LayerId, u64, std::sync::Arc<tone::Histograms>)>,/// Histogram panel cache: (document, revision, computed at ms, histograms).@@ -1087,6 +1090,7 @@ impl PhotocraftApp {live_adjust_preview: None,synthetic: Vec::new(),automation_input: false,+ paused_playbacks: Default::default(),channel_thumbs: None,channel_views: HashMap::new(),type_layout: None,