diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index 8e8d532d5b..b9f98b9829 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -106,6 +106,12 @@ pub struct ActionState { /// Steps run by the current top-level script and everything it calls. #[serde(skip)] pub script_steps: u64, + /// Sets made with New Set (`actions.newSet`), or loaded from an `.atn` with no actions, that + /// hold no action yet: the Actions panel shows them as empty folders. Save Actions… writes one + /// to an `.atn` as Photoshop does, but the preset store keeps sets through their actions, so + /// an empty one isn't remembered past the session. + #[serde(skip)] + pub sets: Vec, /// Bumped whenever `list` changes, so the preset store can skip unchanged writes. #[serde(skip)] pub rev: u64, @@ -366,7 +372,15 @@ fn record(s: &mut Session, p: &Value) -> Result { if s.actions.list.iter().any(|action| action.name == name) { return Err(bad("actions.record", "an action with this name already exists")); } - s.actions.list.push(Action::new(name, Vec::new())); + let set = match p.get("set") { + None | Some(Value::Null) => None, + // An existing set, empty ones included, keeps its exact name (an older actions.json or + // a `.atn` may pad it); a new one is trimmed. + Some(Value::String(n)) if crate::actions_edit_cmds::set_names(s).contains(n) => Some(n.clone()), + Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), + Some(_) => return Err(bad("actions.record", "\"set\" must be a set name or null")), + }; + s.actions.list.push(Action { set, ..Action::new(name, Vec::new()) }); s.actions.touch(); s.actions.list.len() - 1 }; @@ -766,7 +780,7 @@ pub fn specs() -> Vec { label: "Record Action", menu: &[], shortcut: None, - params: r##"{"name":str? (new action, default "Action N")} or {"action":name|index} (append) → {action, index}"##, + params: r##"{"name":str? (new action, default "Action N"),"set":name? (the set it goes in, as New Action records into the selected set)} or {"action":name|index} (append) → {action, index}"##, enabled: always, run: record, journal: false, diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index caddcaa892..1eef6d4b34 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -1176,3 +1176,35 @@ fn arrange_that_cannot_move_is_a_noop_in_playback() { assert_eq!(played["ran"], 0, "{played}"); assert!(played["failed"].is_object(), "{played}"); } + +/// #10459 review: recording into an existing set keeps that set's exact name, even one with +/// surrounding spaces (from an older actions.json); a new set name is trimmed. +#[test] +fn record_keeps_an_existing_sets_exact_name() { + let mut s = Session::new(); + s.actions.list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) }); + s.execute("actions.record", json!({"name": "New", "set": " Web "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let set_of = |s: &Session, n: &str| s.actions.list.iter().find(|a| a.name == n).and_then(|a| a.set.clone()); + assert_eq!(set_of(&s, "New").as_deref(), Some(" Web "), "the existing set"); + s.execute("actions.record", json!({"name": "Fresh", "set": " Print "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(set_of(&s, "Fresh").as_deref(), Some("Print"), "a new set is trimmed"); +} + +/// CodeRabbit review on #10459: an empty set loaded from a `.atn` (or made by New Set) keeps its +/// exact name too, so the first action recorded into it lands in that folder and saves with it. +#[test] +fn record_keeps_an_empty_loaded_sets_exact_name() { + let mut src = Session::new(); + src.actions.sets.push(" Web ".into()); + let saved = src.execute("actions.save", json!({"set": " Web "})).unwrap(); + let mut s = Session::new(); + assert_eq!(s.execute("actions.load", json!({"data": saved["data"]})).unwrap()["set"], " Web "); + s.execute("actions.record", json!({"name": "First", "set": " Web "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let set = s.actions.list.iter().find(|a| a.name == "First").and_then(|a| a.set.clone()); + assert_eq!(set.as_deref(), Some(" Web ")); + assert_eq!(crate::actions_edit_cmds::set_names(&s), [" Web "], "one folder, not a trimmed second one"); + assert_eq!(s.execute("actions.save", json!({"set": " Web "})).unwrap()["actions"], json!(["First"])); +} diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index 1f9cce3431..380fc764e9 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -1,6 +1,7 @@ //! Editing an action's steps and its set, as the Actions panel does beyond recording: //! `actions.insert` (Photoshop's Insert Stop… and Insert Menu Item…), `actions.dialog` (the -//! panel's dialog toggle column) and `actions.assignSet` (which set folder an action sits in). +//! panel's dialog toggle column), `actions.assignSet` (which set folder an action sits in) and +//! `actions.newSet` (New Set…, an empty set folder). //! //! All three refuse to run during playback, commit pending recorded steps first, and keep the //! per-step flag sets (`disabled`, `dialogs`) in step with the moved indices, like @@ -126,6 +127,38 @@ fn assign_set(s: &mut Session, p: &Value) -> Result { Ok(result) } +/// Every set name, in the Actions panel's order: the sets of the actions as they first appear, +/// then the empty ones New Set made. +pub fn set_names(s: &Session) -> Vec { + let mut names: Vec = Vec::new(); + for set in s.actions.list.iter().filter_map(|a| a.set.as_ref()).chain(&s.actions.sets) { + if !names.contains(set) { + names.push(set.clone()); + } + } + names +} + +/// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New +/// Action can record into. +fn new_set(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.newSet"; + not_playing(s, cmd)?; + let names = set_names(s); + let name = match p.get("name") { + None | Some(Value::Null) => (1u32..).map(|n| format!("Set {n}")).find(|n| !names.contains(n)).ok_or_else(|| bad(cmd, "no free set name"))?, + Some(Value::String(n)) if !n.trim().is_empty() => n.trim().to_string(), + Some(Value::String(_)) => return Err(bad(cmd, "`name` is empty")), + Some(_) => return Err(bad(cmd, "`name` must be a string")), + }; + if names.contains(&name) { + return Err(bad(cmd, format!("a set named `{name}` already exists"))); + } + s.actions.sets.push(name.clone()); + s.actions.touch(); + Ok(json!({"set": name})) +} + /// The conditions of Photoshop's Insert Conditional, by their string ids. pub const CONDITIONS: &[&str] = &[ "always", @@ -285,6 +318,16 @@ pub fn specs() -> Vec { run: assign_set, journal: false, }, + CommandSpec { + id: "actions.newSet", + label: "New Set", + menu: &[], + shortcut: None, + params: r##"{"name":str? (default "Set N")} → {set}. An empty set folder in the Actions panel, as Photoshop's New Set… makes; New Action records into the selected set (actions.record's `set`). Save Actions… (actions.save's `set`) writes it even while empty; it is remembered between sessions once it holds an action."##, + enabled: always, + run: new_set, + journal: false, + }, ] } @@ -412,6 +455,26 @@ mod tests { } } + #[test] + fn new_set_makes_an_empty_folder_that_new_actions_record_into() { + let mut s = session_with(&["select.all"]); + s.execute("actions.assignSet", json!({"action": "A", "set": "Set 1"})).unwrap(); + // Numbered past the sets the actions already have. + assert_eq!(s.execute("actions.newSet", json!({})).unwrap()["set"], "Set 2"); + assert_eq!(s.execute("actions.newSet", json!({"name": " Retouch "})).unwrap()["set"], "Retouch"); + assert_eq!(set_names(&s), ["Set 1", "Set 2", "Retouch"]); + assert!(s.execute("actions.newSet", json!({"name": "Set 1"})).is_err(), "a set an action is in"); + assert!(s.execute("actions.newSet", json!({"name": "Retouch"})).is_err(), "an empty set"); + assert!(s.execute("actions.newSet", json!({"name": " "})).is_err()); + // New Action into the empty set. + let r = s.execute("actions.record", json!({"set": "Retouch"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let i = r["index"].as_u64().unwrap() as usize; + assert_eq!(s.actions.list[i].set.as_deref(), Some("Retouch")); + assert_eq!(set_names(&s), ["Set 1", "Retouch", "Set 2"], "Retouch now holds an action"); + assert!(s.execute("actions.record", json!({"set": 3})).is_err()); + } + #[test] fn assign_set_moves_an_action_between_folders() { let mut s = session_with(&["select.all"]); diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 42a4722479..cd267e083b 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -112,7 +112,7 @@ pub fn specs() -> Vec { label: "Save Actions…", menu: &[], shortcut: None, - params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##, + params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions, none for an empty New Set set; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##, enabled: always, run: save, journal: false, diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index be7bd45151..2cb5d565d9 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -59,6 +59,11 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { } } s.actions.list.extend(added); + // A set saved with no actions (Photoshop saves an empty set) is an empty folder, like one New + // Set made. + if !s.actions.list.iter().any(|a| a.set.as_deref() == Some(imp.set.as_str())) && !s.actions.sets.contains(&imp.set) { + s.actions.sets.push(imp.set.clone()); + } let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); if !keys.is_empty() { s.edit_prefs(|prefs| { @@ -90,6 +95,9 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { }; let set_param = match p.get("set") { None | Some(Value::Null) => None, + // A set is found by its exact name, as `actions.record` finds it: one loaded from a + // Photoshop file or an older actions.json may have surrounding spaces. Others are trimmed. + Some(Value::String(n)) if crate::actions_edit_cmds::set_names(s).contains(n) => Some(n.clone()), Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), }; @@ -99,16 +107,17 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) } else if let Some(set) = set_param { let list: Vec<&Action> = s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect(); - if list.is_empty() { + // An empty set New Set made is written with no actions, as Photoshop saves one. + if list.is_empty() && !s.actions.sets.contains(&set) { return Err(bad(cmd, format!("no actions in a set named `{set}`"))); } (set, list) } else { + if s.actions.list.is_empty() { + return Err(bad(cmd, "there are no actions to save")); + } (DEFAULT_SET.to_string(), s.actions.list.iter().collect()) }; - if actions.is_empty() { - return Err(bad(cmd, "there are no actions to save")); - } let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); let keys: Vec<(String, String)> = s.prefs().shortcuts.iter().filter_map(|(k, v)| k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX).map(|n| (n.to_string(), v.clone()))).collect(); diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 9101d1b108..2ab4674205 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3624,3 +3624,48 @@ fn pattern_fill_missing_everywhere_names_the_pattern() { let e = s.execute("layer.fill.pattern.set", json!({"pattern": "5e1c0000-aaaa-4bbb-8ccc-000000000000", "patternName": "My Wood"})).unwrap_err(); assert!(e.to_string().contains("\"My Wood\""), "{e}"); } + +/// FredApps review on #10459: a set whose name has surrounding spaces (a Photoshop `.atn` or an +/// older actions.json can have one, and New Action records into it under that exact name) saves +/// by that name. `actions.save` used to trim it and then find no set. +#[test] +fn save_finds_a_set_by_its_exact_name_with_spaces() { + let mut s = Session::new(); + s.actions.list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) }); + s.execute("actions.record", json!({"name": "New", "set": " Web "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let saved = s.execute("actions.save", json!({"set": " Web "})).unwrap(); + assert_eq!((&saved["set"], &saved["actions"]), (&json!(" Web "), &json!(["Old", "New"]))); + // The file keeps the name, as Photoshop's does. + let mut reloaded = Session::new(); + let r = reloaded.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!(r["set"], " Web "); + // Other names are still trimmed. + s.execute("actions.assignSet", json!({"action": "Old", "set": "Print"})).unwrap(); + assert_eq!(s.execute("actions.save", json!({"set": " Print "})).unwrap()["set"], "Print"); +} + +/// FredApps review on #10459: Save Actions… on an empty set made with New Set writes it, as +/// Photoshop saves an empty set to the `.atn`, and loading that file brings the empty set back. +#[test] +fn an_empty_new_set_saves_and_loads_back() { + let mut s = Session::new(); + s.execute("actions.newSet", json!({"name": "Later"})).unwrap(); + let saved = s.execute("actions.save", json!({"set": "Later"})).unwrap(); + assert_eq!((&saved["set"], &saved["actions"], &saved["steps"]), (&json!("Later"), &json!([]), &json!(0))); + let mut other = Session::new(); + let r = other.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!((&r["set"], &r["actions"]), (&json!("Later"), &json!([]))); + assert_eq!(crate::actions_edit_cmds::set_names(&other), ["Later"], "an empty folder"); + other.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!(crate::actions_edit_cmds::set_names(&other), ["Later"], "loaded twice, still one folder"); + // New Action records into it as into any set, and it saves with that action. + other.execute("actions.record", json!({"name": "Now", "set": "Later"})).unwrap(); + other.execute("actions.stop", json!({})).unwrap(); + assert_eq!(other.execute("actions.save", json!({"set": "Later"})).unwrap()["actions"], json!(["Now"])); + // A set that doesn't exist is still refused, and so is saving every action when there is none. + let err = s.execute("actions.save", json!({"set": "Nope"})).unwrap_err().to_string(); + assert!(err.contains("no actions in a set named `Nope`"), "{err}"); + let err = Session::new().execute("actions.save", json!({})).unwrap_err().to_string(); + assert!(err.contains("there are no actions to save"), "{err}"); +} diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 3925bf8321..82a5421445 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -45,8 +45,11 @@ pub(crate) use open::{import, tag_exr_colorspace}; use paths::is_file; #[cfg(test)] use paths::openable_name; -pub use paths::{extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, same_file, saves_in_place, template_name, untitled_name}; -pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, portable_device_name, read_file, sanitize, stem, write_file}; +pub use paths::{ + extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, portable_device_name, same_file, saves_in_place, template_name, + untitled_name, +}; +pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, read_file, sanitize, stem, write_file}; use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack}; use save::save_a_copy; pub(crate) use save::{SaveOpts, encode, save_doc}; diff --git a/crates/engine/src/cmd/file_cmds/paths.rs b/crates/engine/src/cmd/file_cmds/paths.rs index 840609d826..8f3abdc6b8 100644 --- a/crates/engine/src/cmd/file_cmds/paths.rs +++ b/crates/engine/src/cmd/file_cmds/paths.rs @@ -212,7 +212,7 @@ pub(crate) fn sanitize(name: &str) -> String { /// `name` with a `_` before its first dot when it is a Windows device name (`nul` → `nul_`, /// `com1.v2` → `com1_.v2`); a `_` at the end would leave the device stem in place. -pub(crate) fn portable_device_name(name: String) -> String { +pub fn portable_device_name(name: String) -> String { if !is_windows_device_name(&name) { return name; } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index bc0435806e..1c8eabb30e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -295,6 +295,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: _ if crate::disk_change_prompt::owns(fields) => crate::disk_change_prompt::body(ui, fields), _ if crate::replace_prompt::owns(fields) => crate::replace_prompt::body(ui, fields), _ if crate::actions::owns_insert_stop(fields) => crate::actions::insert_stop_body(ui, fields), + _ if crate::actions::owns_new_set(fields) => crate::actions::new_set_body(ui, fields), _ if crate::new_layer_ui::owns(fields) => crate::new_layer_ui::body(ui, fields), _ if crate::mask_trash_prompt::owns(fields) => crate::mask_trash_prompt::body(ui, fields), _ if crate::rasterize_prompt::owns(fields) => crate::rasterize_prompt::body(ui, fields), @@ -833,6 +834,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ crate::delete_layer_prompt::owns, crate::disk_change_prompt::owns, crate::actions::owns_insert_stop, + crate::actions::owns_new_set, crate::new_layer_ui::owns, crate::new_group_ui::owns, crate::mask_trash_prompt::owns, @@ -989,6 +991,7 @@ fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result _ if crate::disk_change_prompt::owns(&d.fields) => crate::disk_change_prompt::confirm(app, &d.fields), _ if crate::replace_prompt::owns(&d.fields) => crate::replace_prompt::confirm(app), _ if crate::actions::owns_insert_stop(&d.fields) => crate::actions::insert_stop_confirm(app, &d.fields), + _ if crate::actions::owns_new_set(&d.fields) => crate::actions::new_set_confirm(app, &d.fields), _ if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields), _ if crate::mask_trash_prompt::owns(&d.fields) => crate::mask_trash_prompt::confirm(app, &d.fields), _ if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields), diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index c1ba436d22..5f2ab0a45c 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -27,6 +27,10 @@ pub struct ActionsUi { /// Photoshop's Button Mode: each action is a coloured button, and a click plays it. #[serde(default)] pub button_mode: bool, + /// The set whose folder row was clicked last (or New Set made), while no action is selected: + /// New Action records into it, as Photoshop's does into the selected set (#7535). + #[serde(skip)] + pub selected_set: Option, #[serde(skip)] reveal_recording: Option<(usize, usize)>, /// The action whose name is being edited in place (double-click on its name). @@ -34,6 +38,16 @@ pub struct ActionsUi { renaming: Option, } +impl ActionsUi { + /// Select an action (and one of its steps): it replaces a selected set, so a later deselect + /// (Delete, a removed row) doesn't bring back a set the user moved away from. + fn select(&mut self, action: usize, step: Option) { + self.selected = Some(action); + self.selected_step = step; + self.selected_set = None; + } +} + #[derive(Clone, Debug, PartialEq)] struct RenameAction { index: usize, @@ -51,11 +65,70 @@ pub(crate) fn label_of(id: &str) -> String { .unwrap_or_else(|| id.to_string()) } -/// The selected action, or the first one when nothing is selected. +/// The selected action, else the first action of the selected set (Batch and Create Droplet start +/// on the panel's selection), else the first one. pub fn selected_action(app: &PhotocraftApp) -> Option<&Action> { let list = &app.session.actions.list; let idx = app.ui.actions.selected.filter(|i| *i < list.len()); - idx.and_then(|i| list.get(i)).or_else(|| list.first()) + idx.and_then(|i| list.get(i)).or_else(|| selected_set_actions(app).first().and_then(|i| list.get(*i))).or_else(|| list.first()) +} + +/// The selected set folder, if no action is selected and the set still exists. +fn selected_set(app: &PhotocraftApp) -> Option<&str> { + if app.ui.actions.selected.is_some_and(|i| i < app.session.actions.list.len()) { + return None; + } + let set = app.ui.actions.selected_set.as_deref()?; + photocraft_engine::actions_edit_cmds::set_names(&app.session).iter().any(|n| n == set).then_some(set) +} + +/// The actions of the selected set, in list order (empty when no set is selected, or it is empty). +fn selected_set_actions(app: &PhotocraftApp) -> Vec { + let Some(set) = selected_set(app) else { return Vec::new() }; + app.session.actions.list.iter().enumerate().filter(|(_, a)| a.set.as_deref() == Some(set)).map(|(i, _)| i).collect() +} + +/// What Play plays: the selected action; with a set folder selected, every action of that set in +/// order, as Photoshop plays a selected set (nothing for an empty set); else the first action. +fn playback_targets(app: &PhotocraftApp) -> Vec { + if selected_set(app).is_some() { + return selected_set_actions(app); + } + playback_selection(app).into_iter().collect() +} + +/// Play `targets` one after another, stopping at the first that fails or can't start. One that +/// pauses for a step dialog of its own hands the rest to that dialog, which plays them after its OK +/// (Cancel stops them all, as it stops one action). A pause inside an action it calls resumes only +/// the called action, so the set stops there rather than run its next action on an unfinished one. Returns the last result with `ran` counting the steps +/// of all of them, or `None` when there was nothing to play. +fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result, String> { + let (mut last, mut ran) = (None, 0u64); + for (n, &i) in targets.iter().enumerate() { + let name = app.session.actions.list.get(i).map(|a| a.name.clone()); + let mut v = app.run("actions.play", json!({"action": i}))?; + ran = ran.saturating_add(v.get("ran").and_then(Value::as_u64).unwrap_or(0)); + let failed = v.get("failed").is_some_and(Value::is_object); + let paused = v.get("paused").filter(|p| p.is_object()).and_then(|p| p.get("dialog")).and_then(Value::as_u64); + if let Some(o) = v.as_object_mut() { + o.insert("ran".into(), json!(ran)); + } + last = Some(v); + if let Some(dialog) = paused.filter(|_| !failed) { + let rest = targets.get(n + 1..).unwrap_or_default().to_vec(); + let token = app.ui.dialog_mut(dialog).and_then(|d| d.fields.get(RESUME)).and_then(Value::as_u64); + if let Some(entry) = token.and_then(|t| app.paused_playbacks.paused.get_mut(&t)) + && name.as_ref() == Some(&entry.action) + { + entry.then = rest; + } + break; + } + if failed { + break; + } + } + Ok(last) } /// Index of the playback target. Photoshop's Play button uses the first action when @@ -253,19 +326,35 @@ pub(crate) fn run_view(app: &mut PhotocraftApp, id: &str, params: Value) -> Resu Ok(Value::Null) } +/// The set New Action records into: the selected action's, else the selected set folder's. +fn new_action_set(app: &PhotocraftApp) -> Option { + match app.ui.actions.selected.and_then(|i| app.session.actions.list.get(i)) { + Some(action) => action.set.clone(), + None => app.ui.actions.selected_set.clone().filter(|set| photocraft_engine::actions_edit_cmds::set_names(&app.session).contains(set)), + } +} + fn begin_recording(app: &mut PhotocraftApp, append: bool) { if app.session.actions.recording.is_some() { return; } - let params = if append { app.ui.actions.selected.map_or(json!({}), |i| json!({"action": i})) } else { json!({}) }; + // Recording appends to the selected action; with none (a set folder selected, say) it makes a + // new action like New Action does, in the selected set. + let params = match app.ui.actions.selected { + Some(i) if append => json!({"action": i}), + _ => new_action_set(app).map_or(json!({}), |set| json!({"set": set})), + }; let Ok(v) = app.run("actions.record", params) else { return }; let Some(i) = v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()) else { return }; - app.ui.actions.selected = Some(i); - app.ui.actions.selected_step = None; + app.ui.actions.select(i, None); if app.ui.actions.expanded.len() <= i { app.ui.actions.expanded.resize(i + 1, false); } app.ui.actions.expanded[i] = true; + // Its set too, in case its folder is collapsed. + if let Some(set) = app.session.actions.list.get(i).and_then(|a| a.set.as_ref()) { + app.ui.actions.collapsed_sets.retain(|c| c != set); + } } pub(crate) fn report_play(app: &mut PhotocraftApp, v: &Value) { @@ -396,8 +485,7 @@ pub fn load_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result Result { app.pick_file_bytes_filtered(&["atn"], |app, name, bytes| load_bytes(app, &name, &bytes)) } -/// Save Actions…: the selected action's set (every action of it), or every action when none -/// came from a set, as a `.atn` file Photoshop loads. +/// Save Actions…: the selected action's set (every action of it), else the selected set folder, +/// or every action when none came from a set, as a `.atn` file Photoshop loads. fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result { - let set = set.or_else(|| selected_action(app).and_then(|a| a.set.clone())); + let selected_set = app.ui.actions.selected.is_none().then(|| app.ui.actions.selected_set.clone()).flatten(); + let selected_set = selected_set.filter(|set| photocraft_engine::actions_edit_cmds::set_names(&app.session).contains(set)); + let set = set.or(selected_set).or_else(|| selected_action(app).and_then(|a| a.set.clone())); let params = match &set { Some(set) => json!({"set": set, "skipUnsupported": true}), None => json!({"skipUnsupported": true}), @@ -423,7 +513,15 @@ fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result' | '|') { '_' } else { c }) + .collect(); + let file = format!("{}.atn", photocraft_engine::file_cmds::portable_device_name(stem)); app.pick_save(&file, move |app, path| { let write = app.services.write.as_mut().ok_or("no writer configured")?; write(&path, &bytes)?; @@ -449,6 +547,40 @@ fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result) -> bool { + fields.contains_key(NEW_SET) +} + +/// New Set…: name an empty set folder (Photoshop's default "Set N"). +fn new_set_dialog(app: &mut PhotocraftApp) -> Result { + let names = photocraft_engine::actions_edit_cmds::set_names(&app.session); + let name = (1u32..).map(|n| format!("Set {n}")).find(|n| !names.contains(n)).unwrap_or_default(); + let fields = json!({NEW_SET: true, "__command": "actions.newSet", "__label": "New Set", "name": name}); + let id = app.ui.open_dialog(crate::state::DialogKind::Command, fields.as_object().cloned().unwrap_or_default()); + Ok(json!({"dialog": id})) +} + +pub fn new_set_body(ui: &mut egui::Ui, fields: &mut serde_json::Map) { + ui.horizontal(|ui| { + let label = ui.label(tl!("Name:")); + let mut name = fields.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + ui.add(egui::TextEdit::singleline(&mut name).desired_width(220.0)).labelled_by(label.id); + fields.insert("name".into(), json!(name)); + }); +} + +/// Make the set and select it, so New Action records into it. +pub fn new_set_confirm(app: &mut PhotocraftApp, fields: &serde_json::Map) -> Result { + let r = app.run("actions.newSet", json!({"name": fields.get("name").cloned().unwrap_or(Value::Null)}))?; + app.ui.actions.selected_set = r["set"].as_str().map(str::to_string); + app.ui.actions.selected = None; + app.ui.actions.selected_step = None; + Ok(r) +} + pub fn owns_insert_stop(fields: &serde_json::Map) -> bool { fields.contains_key(INSERT_STOP) } @@ -485,8 +617,7 @@ pub fn insert_stop_confirm(app: &mut PhotocraftApp, fields: &serde_json::Map, + /// The actions still to play after this one, when Play started a whole set. + then: Vec, } /// The paused playbacks, by the token their dialog carries. The dialog's fields hold only the @@ -572,7 +705,7 @@ pub(crate) struct PausedPlaybacks { impl PausedPlaybacks { fn pause(&mut self, action: String, from: usize, gate: Option) -> u64 { self.last = self.last.wrapping_add(1); - self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None }); + self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None, then: Vec::new() }); self.last } @@ -605,7 +738,33 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) 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); + let mut played = play_owned(app, ¶ms, owner); + // Paused again at a later dialog of the same action (not of one it calls, which resumes + // alone): that dialog carries the rest of the set. + if let Ok(v) = &played + && let Some(dialog) = v.get("paused").and_then(|p| p.get("dialog")).and_then(Value::as_u64) + && let Some(token) = app.ui.dialog_mut(dialog).and_then(|d| d.fields.get(RESUME)).and_then(Value::as_u64) + && let Some(entry) = app.paused_playbacks.paused.get_mut(&token) + && entry.action == paused.action + { + entry.then = paused.then.clone(); + } + // The rest of a set Play started: under the same gate, and only if this action finished. + if let Ok(v) = &played + && !paused.then.is_empty() + && v.get("failed").is_none() + && v.get("paused").is_none() + { + let ran = v.get("ran").and_then(Value::as_u64).unwrap_or(0); + played = play_targets(app, &paused.then).map(|rest| { + let mut rest = rest.unwrap_or(Value::Null); + let total = ran.saturating_add(rest.get("ran").and_then(Value::as_u64).unwrap_or(0)); + if let Some(o) = rest.as_object_mut() { + o.insert("ran".into(), json!(total)); + } + rest + }); + } app.session.authorize = saved; match played { Ok(v) => { @@ -640,6 +799,9 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if ui.add_enabled(!recording, egui::Button::new(tl!("New Action…"))).clicked() { act = Some("new"); } + if ui.button(tl!("New Set…")).clicked() { + act = Some("newSet"); + } if ui.add_enabled(any, egui::Button::new(tl!("Play"))).clicked() { act = Some("play"); } @@ -661,7 +823,9 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if ui.button(tl!("Load Actions…")).clicked() { act = Some("load"); } - if ui.add_enabled(any, egui::Button::new(tl!("Save Actions…"))).clicked() { + // A selected set folder saves even when empty, as Photoshop saves an empty set. + let set_selected = app.ui.actions.selected_set.as_ref().is_some_and(|set| photocraft_engine::actions_edit_cmds::set_names(&app.session).contains(set)); + if ui.add_enabled(any || set_selected, egui::Button::new(tl!("Save Actions…"))).clicked() { act = Some("save"); } let Some(a) = act else { return }; @@ -676,16 +840,21 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Ok(Value::Null) } "stopRec" => app.run("actions.stop", json!({})), - "play" => playback_selection(app).map_or(Ok(Value::Null), |i| { - let v = app.run("actions.play", json!({"action": i}))?; - report_play(app, &v); - Ok(v) - }), + "play" => { + let targets = playback_targets(app); + play_targets(app, &targets).map(|v| { + if let Some(v) = &v { + report_play(app, v); + } + v.unwrap_or(Value::Null) + }) + } "delete" => { delete_selection(app); Ok(Value::Null) } "load" => load_dialog(app), + "newSet" => new_set_dialog(app), "stop" => insert_stop_dialog(app), _ => save_dialog(app, None), }; @@ -729,16 +898,14 @@ fn move_row(app: &mut PhotocraftApp, source: DragRow, to: usize) { return; } if source.step.is_some() { - app.ui.actions.selected = Some(source.action); - app.ui.actions.selected_step = Some(to); + app.ui.actions.select(source.action, Some(to)); } else { app.ui.actions.expanded.resize(app.session.actions.list.len(), false); if source.action < app.ui.actions.expanded.len() && to < app.ui.actions.expanded.len() { let expanded = app.ui.actions.expanded.remove(source.action); app.ui.actions.expanded.insert(to, expanded); } - app.ui.actions.selected = Some(to); - app.ui.actions.selected_step = None; + app.ui.actions.select(to, None); // Dropped among another set's actions: the action joins that set (the row above wins). let list = &app.session.actions.list; let neighbour = to.checked_sub(1).and_then(|j| list.get(j)).or_else(|| list.get(to + 1)).and_then(|a| a.set.clone()); @@ -833,14 +1000,19 @@ fn display_order(rows: &[Row]) -> Vec { } struct SetHeaderResult { + /// A click on the disclosure triangle (or an activation without a pointer): collapse or expand. toggled: bool, + /// A click on the rest of the row (or an activation without a pointer): select the set. + picked: bool, save: bool, } -fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, tokens: &Tokens) -> SetHeaderResult { +fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, selected: bool, tokens: &Tokens) -> SetHeaderResult { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, !collapsed, set)); - if response.hovered() { + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, set)); + if selected { + ui.painter().rect_filled(rect, 0.0, tokens.row_selected); + } else if response.hovered() { ui.painter().rect_filled(rect, 0.0, tokens.hover.gamma_multiply(0.5)); } let triangle = Rect::from_center_size(pos2(rect.left() + 12.0, rect.center().y), vec2(8.0, 8.0)); @@ -860,7 +1032,12 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, to ui.painter().text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, set, egui::FontId::proportional(12.0), tokens.text); let summary = crate::i18n::trn(crate::i18n::current(), count, "{n} action", "{n} actions"); ui.painter().text(pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, summary, egui::FontId::proportional(11.0), tokens.text_faint); - let toggled = response.clicked(); + // As on an action row, a click in the triangle's column collapses or expands and one on the + // rest of the row selects. An activation without a pointer (keyboard, accessibility) does + // both, so the set can still be collapsed and expanded without a mouse. + let pointer = response.interact_pointer_pos(); + let toggled = response.clicked() && pointer.is_none_or(|p| p.x < rect.left() + 20.0); + let picked = response.clicked() && pointer.is_none_or(|p| p.x >= rect.left() + 20.0); let mut save = false; response.context_menu(|ui| { if ui.button(tl!("Save Set…")).clicked() { @@ -868,7 +1045,26 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, to ui.close(); } }); - SetHeaderResult { toggled, save } + SetHeaderResult { toggled, picked, save } +} + +/// The sets New Set made that hold no action yet: empty folder rows after the rest. Returns the +/// set whose row was clicked (whether it toggles, whether it selects) and the set whose Save Set… +/// was chosen. +fn draw_empty_sets(app: &PhotocraftApp, ui: &mut egui::Ui, rows: &[Row], t: &Tokens) -> (Option<(String, bool, bool)>, Option) { + let (mut clicked, mut save) = (None, None); + for set in app.session.actions.sets.iter().filter(|set| !rows.iter().any(|r| r.set.as_ref() == Some(*set))) { + let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_ref() == Some(set); + let collapsed = app.ui.actions.collapsed_sets.contains(set); + let result = draw_set_header(ui, set, 0, collapsed, selected, t); + if result.toggled || result.picked { + clicked = Some((set.clone(), result.toggled, result.picked)); + } + if result.save { + save = Some(set.clone()); + } + } + (clicked, save) } fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index: usize, name: &str, swatch: &str) { @@ -949,10 +1145,10 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let mut renamed = None; let mut toggled = None; let mut dialog_toggled = None; - let mut set_toggled: Option = None; + let mut set_toggled: Option<(String, bool, bool)> = None; let mut save_set: Option = None; let max_h = (ui.available_height() - 38.0).max(0.0); - let mut play_idx = None; + let mut play_idx: Option> = None; let mut moved = None; let recording_row = recording.and_then(|(_, i)| rows.get(i).map(|r| (i, r.steps.len()))); let reveal = recording_row.filter(|row| app.ui.actions.reveal_recording != Some(*row)); @@ -978,9 +1174,10 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { shown_set = Some(set); let collapsed = app.ui.actions.collapsed_sets.iter().any(|c| c == set); let count = rows.iter().filter(|r| r.set.as_deref() == Some(set)).count() as u64; - let result = draw_set_header(ui, set, count, collapsed, &t); - if result.toggled { - set_toggled = Some(set.to_string()); + let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_deref() == Some(set); + let result = draw_set_header(ui, set, count, collapsed, selected, &t); + if result.toggled || result.picked { + set_toggled = Some((set.to_string(), result.toggled, result.picked)); } if result.save { save_set = Some(set.to_string()); @@ -1050,11 +1247,10 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.painter().circle_filled(pos2(rect.right() - 64.0, rect.center().y), 4.0, Color32::from_rgb(230, 60, 60)); } if resp.clicked() { - app.ui.actions.selected = Some(i); - app.ui.actions.selected_step = None; + app.ui.actions.select(i, None); if button_mode { if !resp.double_clicked() { - play_idx = Some(i); + play_idx = Some(vec![i]); } } else if resp.interact_pointer_pos().is_some_and(|p| p.x < x0 + 20.0) { if app.ui.actions.expanded.len() <= i { @@ -1071,7 +1267,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if resp.interact_pointer_pos().is_some_and(|p| name_rect.expand2(vec2(4.0, 13.0)).contains(p)) { app.ui.actions.renaming = Some(RenameAction { index: i, text: name.clone(), focused: false }); } else { - play_idx = Some(i); + play_idx = Some(vec![i]); } } if expanded { @@ -1082,6 +1278,9 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { dialog_toggled = dialog_toggled.or(events.dialog_toggled); } } + let (empty_toggled, empty_save) = draw_empty_sets(app, ui, &rows, &t); + set_toggled = set_toggled.take().or(empty_toggled); + save_set = save_set.take().or(empty_save); }); if let Some((action, step)) = toggled { let _ = app.run("actions.toggle", json!({"action": action, "step": step})); @@ -1089,12 +1288,21 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some((action, step)) = dialog_toggled { let _ = app.run("actions.dialog", json!({"action": action, "step": step})); } - if let Some(set) = set_toggled { - match app.ui.actions.collapsed_sets.iter().position(|c| *c == set) { - Some(i) => { - app.ui.actions.collapsed_sets.remove(i); + if let Some((set, toggle, pick)) = set_toggled { + // The rest of the folder row selects the set, for New Action and Play. + if pick { + app.ui.actions.selected = None; + app.ui.actions.selected_step = None; + app.ui.actions.selected_set = Some(set.clone()); + } + // The disclosure triangle collapses or expands the set and leaves the selection alone. + if toggle { + match app.ui.actions.collapsed_sets.iter().position(|c| *c == set) { + Some(i) => { + app.ui.actions.collapsed_sets.remove(i); + } + None => app.ui.actions.collapsed_sets.push(set), } - None => app.ui.actions.collapsed_sets.push(set), } } if let Some(set) = save_set @@ -1128,7 +1336,13 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let play = crate::icons::button(ui, "play", 24.0, false, tl!("Play selection")); play.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Play selection"))); if play.clicked() { - play_idx = playback_selection(app); + play_idx = Some(playback_targets(app)); + } + if crate::icons::button(ui, "folder", 24.0, false, tl!("Create new set")).clicked() + && let Err(e) = new_set_dialog(app) + { + app.ui.status = e; + app.ui.status_error = true; } if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new action")).clicked() && !recording_now { begin_recording(app, false); @@ -1148,9 +1362,10 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.actions.button_mode = !app.ui.actions.button_mode; } }); - if let Some(i) = play_idx { - match app.run("actions.play", json!({"action": i})) { - Ok(v) => report_play(app, &v), + if let Some(targets) = play_idx { + match play_targets(app, &targets) { + Ok(Some(v)) => report_play(app, &v), + Ok(None) => {} Err(e) => { let template = "Action playback failed: {error}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); @@ -1213,8 +1428,7 @@ fn draw_step_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, context: &StepRows } else if dialog.clicked() { events.dialog_toggled = Some((context.action, step)); } else if response.clicked() { - app.ui.actions.selected = Some(context.action); - app.ui.actions.selected_step = Some(step); + app.ui.actions.select(context.action, Some(step)); } } events diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index a2f7629513..7a233fcdf5 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -643,18 +643,563 @@ fn set_folders_group_actions_and_collapse() { assert!(h.get_by_label("Sharpen").rect().top() > folder.top()); assert!(h.get_by_label("Soften").rect().top() > h.get_by_label("Sharpen").rect().top()); assert_eq!(display_order(&[]), Vec::::new()); - // Clicking the folder collapses it; its actions disappear and the state is remembered. - h.get_by_label("Retouch").click(); - h.run_steps(3); + // Clicking the folder's triangle collapses it; its actions disappear and the state is remembered. + click_set_triangle(&mut h, "Retouch"); assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"]); assert!(h.query_by_label("Sharpen").is_none()); assert!(h.query_by_label("Loose").is_some()); - h.get_by_label("Retouch").click(); - h.run_steps(3); + click_set_triangle(&mut h, "Retouch"); assert!(h.state().ui.actions.collapsed_sets.is_empty()); assert!(h.query_by_label("Sharpen").is_some()); } +/// Two sets, Web listed first: "Resize" (Web) adds a layer "w", "Sharpen" and "Soften" (Retouch) +/// add "r1" and "r2". +fn two_set_panel() -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, set, layer) in [("Resize", "Web", "w"), ("Sharpen", "Retouch", "r1"), ("Soften", "Retouch", "r2")] { + let mut a = Action::new(name, vec![("layer.new.layer".into(), json!({"name": layer}))]); + a.set = Some(set.into()); + app.session.actions.list.push(a); + } + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h +} + +fn layer_names(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().doc.walk().iter().map(|(_, _, l)| l.name.clone()).filter(|n| n != "Background").collect() +} + +/// Click a set folder row's disclosure triangle (a plain `click()` lands on the row's middle, +/// which selects the set). +fn click_set_triangle(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, set: &str) { + use egui_kittest::kittest::Queryable; + let pos = h.get_by_label(set).rect().left_center() + vec2(12.0, 0.0); + h.event(egui::Event::PointerMoved(pos)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + } + h.run_steps(2); +} + +/// #10459 fix-up: a click on a set folder row (not its triangle) selects the set, and Play +/// then plays every action of that set in order, as Photoshop plays a selected set, not the first +/// action of the whole list. +#[test] +fn play_with_a_set_folder_selected_plays_that_sets_actions() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.get_by_label("Resize").click(); + h.run_steps(2); + h.get_by_label("Retouch").click(); + h.run_steps(2); + assert!(h.state().ui.actions.collapsed_sets.is_empty(), "a click on the row selects, it doesn't collapse"); + h.get_by_label("Play selection").click(); + h.run_steps(2); + let mut names = layer_names(h.state()); + names.sort(); + assert_eq!(names, ["r1", "r2"], "the Retouch set played, not Resize"); + assert!(!h.state().ui.status_error, "{}", h.state().ui.status); + // Batch and Create Droplet start on the selected set too. + assert_eq!(selected_action(h.state()).map(|a| a.name.as_str()), Some("Sharpen")); +} + +/// #10459 fix-up: Play with an empty set selected plays nothing. +#[test] +fn play_with_an_empty_set_selected_plays_nothing() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.state_mut().run("actions.newSet", json!({"name": "Print"})).unwrap(); + h.run_steps(2); + h.get_by_label("Print").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Print")); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert!(layer_names(h.state()).is_empty(), "{:?}", layer_names(h.state())); +} + +/// #10459 fix-up: the common case is unchanged: a selected action plays alone, also after a set +/// folder was selected before it, and a later Delete doesn't bring that set back. +#[test] +fn play_with_an_action_selected_plays_only_that_action() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.get_by_label("Retouch").click(); + h.run_steps(2); + h.get_by_label("Retouch").click(); + h.run_steps(2); + h.get_by_label("Sharpen").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["r1"]); + assert_eq!(selected_action(h.state()).map(|a| a.name.as_str()), Some("Sharpen")); + h.get_by_label("Delete").click(); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, None)); +} + +/// #10459 fix-up: the disclosure triangle collapses and expands a set and leaves the selection +/// alone, so Play still plays the selected action, not the set that was looked into. +#[test] +fn collapsing_a_set_keeps_the_selected_action_for_play() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.get_by_label("Resize").click(); + h.run_steps(2); + click_set_triangle(&mut h, "Retouch"); + assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"]); + assert!(h.query_by_label("Sharpen").is_none()); + click_set_triangle(&mut h, "Retouch"); + assert!(h.state().ui.actions.collapsed_sets.is_empty()); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (Some(0), None)); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["w"]); +} + +/// #10459 fix-up: selecting a step (or any other way an action becomes the selection) drops a +/// selected set, so deleting that step doesn't bring the set back as Play's target. +#[test] +fn a_selected_step_replaces_the_selected_set() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.state_mut().session.actions.list[0].steps.push(("select.all".into(), json!({}))); + h.state_mut().ui.actions.expanded = vec![true, false, false]; + h.run_steps(2); + h.get_by_label("Retouch").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Retouch")); + h.get_by_label(&label_of("select.all")).click(); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_step), (Some(0), Some(1))); + h.get_by_label("Delete").click(); + h.run_steps(2); + assert_eq!(h.state().session.actions.list[0].steps.len(), 1, "the step went"); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, None)); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["w"], "the first action, not the Retouch set"); +} + +/// #10459 fix-up: a set whose first action pauses at step dialogs plays the rest of the set +/// after OK, and Cancel stops the whole set, as it stops one action. +#[test] +fn a_set_paused_at_a_step_dialog_plays_its_other_actions_after_ok() { + use egui_kittest::kittest::Queryable; + for ok in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut a = Action::new( + "A", + vec![ + ("layer.new.layer".into(), json!({"name": "a"})), + ("filter.blur.gaussianBlur".into(), json!({"radius": 1})), + ("filter.blur.gaussianBlur".into(), json!({"radius": 2})), + ("layer.new.layer".into(), json!({"name": "a2"})), + ], + ); + a.set = Some("S".into()); + a.dialogs.extend([1, 2]); + let mut b = Action::new("B", vec![("layer.new.layer".into(), json!({"name": "b"}))]); + b.set = Some("S".into()); + app.session.actions.list.extend([a, b]); + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("S").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["a"]); + assert!(h.state().ui.status.contains("dialog"), "{}", h.state().ui.status); + let first = h.state().ui.dialogs.last().map(|d| d.id).expect("the first blur's dialog"); + if !ok { + crate::dialogs::cancel(h.state_mut(), first).unwrap(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["a"], "Cancel stops the set"); + continue; + } + crate::dialogs::confirm(h.state_mut(), first).unwrap(); + h.run_steps(2); + // The second dialog of A pauses again; the rest of the set waits behind it. + let second = h.state().ui.dialogs.last().map(|d| d.id).expect("the second blur's dialog"); + assert_ne!(first, second); + crate::dialogs::confirm(h.state_mut(), second).unwrap(); + h.run_steps(2); + let mut names = layer_names(h.state()); + names.sort(); + assert_eq!(names, ["a", "a2", "b"], "B played after A's dialogs"); + assert!(h.state().ui.status.starts_with("Played"), "{}", h.state().ui.status); + } +} + +/// #10459 fix-up: a set whose action pauses at a dialog inside an action it calls stops there: +/// the called action resumes alone, so the next action of the set must not run on a caller that +/// never finished. +#[test] +fn a_set_paused_inside_a_called_action_stops_there() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut a = Action::new("A", vec![("actions.play".into(), json!({"action": "C"})), ("layer.new.layer".into(), json!({"name": "a-tail"}))]); + a.set = Some("S".into()); + let mut b = Action::new("B", vec![("layer.new.layer".into(), json!({"name": "b"}))]); + b.set = Some("S".into()); + let mut c = Action::new("C", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("layer.new.layer".into(), json!({"name": "c"}))]); + c.dialogs.insert(0); + app.session.actions.list.extend([a, b, c]); + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("S").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + let dialog = h.state().ui.dialogs.last().map(|d| d.id).expect("C's blur dialog"); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["c"], "C finished; B didn't run ahead of A's tail"); +} + +/// #10459 fix-up: a set folder activated without a pointer (keyboard, accessibility) still +/// collapses and expands, and selects the set; the row reports whether it is selected. +#[test] +fn a_set_folder_toggles_without_a_pointer() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + use egui::accesskit::Toggled; + use egui_kittest::kittest::NodeT; + let selected = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.get_by_label("Retouch").accesskit_node().toggled(); + assert_eq!(selected(&h), Some(Toggled::False)); + h.get_by_label("Retouch").click_accesskit(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"]); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Retouch")); + assert_eq!(selected(&h), Some(Toggled::True), "selected and collapsed reads as selected"); + h.get_by_label("Retouch").click_accesskit(); + h.run_steps(2); + assert!(h.state().ui.actions.collapsed_sets.is_empty()); +} + +/// #7535: the folder button (and the panel menu's New Set…) names an empty set, shown as a folder +/// row with no actions; New Action then records into it, as into any selected set. +#[test] +fn new_set_makes_an_empty_folder_that_new_action_records_into() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + let mut h = Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("Create new set").click(); + h.run_steps(2); + let id = h.state().ui.dialogs.last().map(|d| d.id).expect("the New Set dialog"); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + assert!(owns_new_set(&d.fields)); + assert_eq!(d.fields["name"], "Set 1"); + d.fields.insert("name".into(), json!("Web")); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(2); + // An empty folder row, selected. + assert!(h.query_by_label("Web").is_some()); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Web")); + h.get_by_label("Create new action").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let list = &h.state().session.actions.list; + assert_eq!((list[1].name.as_str(), list[1].set.as_deref()), ("Action 2", Some("Web"))); + // With an action selected, New Action records into that action's set. + h.state_mut().ui.actions.selected = Some(0); + h.run_steps(2); + h.get_by_label("Create new action").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + assert_eq!(h.state().session.actions.list[2].set.as_deref(), Some("Retouch")); +} + +/// FredApps review on #10459: with no action and no set selected, New Action makes an action +/// outside every set, even when sets (empty ones included) exist. +#[test] +fn new_action_with_no_set_selected_is_in_no_set() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + app.run("actions.newSet", json!({"name": "Web"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, None)); + h.get_by_label("Create new action").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let list = &h.state().session.actions.list; + assert_eq!((list.len(), list[1].name.as_str(), list[1].set.as_deref()), (2, "Action 2", None)); +} + +/// FredApps review on #10459: closing the Actions panel and opening it again keeps the selected +/// set and the empty sets New Set made, so New Action still records into the selected one. +#[test] +fn reopening_the_actions_panel_keeps_the_selected_set_and_empty_sets() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + app.run("actions.newSet", json!({"name": "Web"})).unwrap(); + app.run("actions.newSet", json!({"name": "Print"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state( + |ui, app| { + // The Actions panel is the History group's second tab. + if app.ui.panels.history && app.ui.dock_tabs.history == 1 { + panel(app, ui); + } + }, + app, + ); + let ctx = h.ctx.clone(); + let toggle = |h: &mut Harness<'_, PhotocraftApp>| { + crate::menus::invoke(h.state_mut(), &ctx, "window.panel.actions", json!({})).unwrap(); + h.run_steps(2); + }; + if !(h.state().ui.panels.history && h.state().ui.dock_tabs.history == 1) { + toggle(&mut h); + } + h.run_steps(2); + h.get_by_label("Web").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Web")); + toggle(&mut h); + assert!(!h.state().ui.panels.history, "closed"); + assert!(h.query_by_label("Web").is_none()); + toggle(&mut h); + assert!(h.state().ui.panels.history && h.state().ui.dock_tabs.history == 1, "open again"); + assert!(h.query_by_label("Web").is_some() && h.query_by_label("Print").is_some(), "the empty sets"); + assert_eq!(h.state().session.actions.sets, ["Web", "Print"]); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, Some("Web"))); + h.get_by_label("Create new action").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + assert_eq!(h.state().session.actions.list[1].set.as_deref(), Some("Web")); +} + +/// #7535: with a set's folder row selected and no action, Start Recording (like the Record button) +/// has no action to append to, so it records a new action into that set, as New Action does. +#[test] +fn start_recording_with_a_set_selected_records_a_new_action_into_it() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + app.run("actions.newSet", json!({"name": "Web"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(360.0, 600.0)).build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + h.get_by_label("Web").click(); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, Some("Web"))); + h.get_by_label("Start Recording").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let list = &h.state().session.actions.list; + assert_eq!(list.len(), 2); + assert_eq!(list[1].set.as_deref(), Some("Web")); +} + +/// Recording into a collapsed, selected set (New Action or Start Recording) expands the set +/// again, so the new action and its steps show. +#[test] +fn recording_into_a_collapsed_set_expands_it() { + use egui_kittest::{Harness, kittest::Queryable}; + for label in ["Create new action", "Start Recording"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + let mut h = Harness::builder().with_size(vec2(360.0, 600.0)).build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + click_set_triangle(&mut h, "Retouch"); + h.get_by_label("Retouch").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"], "{label}"); + assert!(h.query_by_label("Sharpen").is_none(), "{label}"); + h.get_by_label(label).click(); + h.run_steps(2); + assert!(h.state().ui.actions.collapsed_sets.is_empty(), "{label}"); + assert_eq!(h.state().ui.actions.selected, Some(1), "{label}"); + assert!(h.query_by_label("Action 2").is_some(), "{label}"); + h.state_mut().run("actions.stop", json!({})).unwrap(); + } +} + +/// Save Actions… after a click on set B's folder row saves set B, not the first action's set. +#[test] +fn save_actions_with_a_set_selected_saves_that_set() { + use egui_kittest::{Harness, kittest::Queryable}; + let (file_dialog, asked) = crate::file_dialog::fake(vec![None]); + let services = crate::Services { file_dialog: Some(file_dialog), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, set) in [("Sharpen", "Retouch"), ("Resize", "Web")] { + let mut action = Action::new(name, vec![("layer.new.layer".into(), json!({}))]); + action.set = Some(set.into()); + app.session.actions.list.push(action); + } + let mut h = Harness::builder().with_size(vec2(360.0, 600.0)).build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + h.get_by_label("Web").click(); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, Some("Web"))); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!(matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Web.atn"), "{:?}", asked.borrow()); +} + +/// FredApps review on #10459: a set name can hold characters a file name can't. Save Actions… +/// suggests the file with them replaced, and the set keeps its name in the file. The set here +/// is an empty one New Set made, which Save Actions… writes as Photoshop does. +#[test] +fn save_actions_suggests_a_file_name_without_path_characters() { + use egui_kittest::{Harness, kittest::Queryable}; + let (file_dialog, asked) = crate::file_dialog::fake(vec![None]); + let services = crate::Services { file_dialog: Some(file_dialog), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.session.actions.list.push(Action::new("Loose", vec![])); + let set = "Web/Print\\Mail: v2"; + app.run("actions.newSet", json!({"name": set})).unwrap(); + let mut h = Harness::builder().with_size(vec2(360.0, 600.0)).build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + h.get_by_label(set).click(); + h.run_steps(2); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!( + matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Web_Print_Mail_ v2.atn"), + "{:?}", + asked.borrow() + ); + let saved = h.state_mut().run("actions.save", json!({"set": set})).unwrap(); + assert_eq!(saved["set"], set, "the file keeps the set's name"); +} + +/// An app with no actions and one empty set New Set made, its folder row shown with the panel +/// menu, and a fake Save dialog whose requests the test reads. +fn empty_set_save_harness( + set: &str, +) -> (egui_kittest::Harness<'static, PhotocraftApp>, std::rc::Rc>>) { + let (file_dialog, asked) = crate::file_dialog::fake(vec![None]); + let services = crate::Services { file_dialog: Some(file_dialog), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.run("actions.newSet", json!({"name": set})).unwrap(); + // With no action, the panel shows its "Record ● … play ▶" hint, which the test fonts lack. + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 600.0)).allow_missing_glyphs().build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + (h, asked) +} + +/// CodeRabbit review on #10459: with no action at all, Save Actions… is still enabled for a +/// selected empty set (the engine saves it), and stays disabled with nothing to save. +#[test] +fn save_actions_is_enabled_for_a_selected_empty_set_with_no_actions() { + use egui_kittest::kittest::Queryable; + let (mut h, asked) = empty_set_save_harness("Later"); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!(asked.borrow().is_empty(), "no set selected, nothing to save: {:?}", asked.borrow()); + h.get_by_label("Later").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Later")); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!( + matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Later.atn"), + "{:?}", + asked.borrow() + ); +} + +/// CodeRabbit review on #10459: Save Set… in an empty set folder's context menu saves that set, +/// as it does for a folder with actions. +#[test] +fn save_set_on_an_empty_set_folder_opens_the_save_dialog() { + use egui_kittest::kittest::Queryable; + let (mut h, asked) = empty_set_save_harness("Later"); + h.get_by_label("Later").click_secondary(); + h.run_steps(2); + h.get_by_label("Save Set…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!( + matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Later.atn"), + "{:?}", + asked.borrow() + ); +} + +/// CodeRabbit review on #10459: a set named after a Windows device (`CON`, `com1.v2`) or holding a +/// control character gets a suggested file name Windows can create. +#[test] +fn save_actions_suggests_a_windows_safe_name_for_device_and_control_character_sets() { + use egui_kittest::kittest::Queryable; + for (set, suggested) in [("CON", "CON_.atn"), ("com1.v2", "com1_.v2.atn"), ("Web\u{1}Print\tMail", "Web_Print_Mail.atn"), ("Print", "Print.atn")] { + let (mut h, asked) = empty_set_save_harness(set); + h.get_by_label(set).click(); + h.run_steps(2); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!( + matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested: s }] if s == suggested), + "{set:?}: {:?}", + asked.borrow() + ); + } +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());