mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
Confirm whole-library Actions replacement before importing
This commit is contained in:
1 parent
ca11c144d9
commit
5faeb4ab24
13 files changed
+470
-9
No files matched your search
@@ -465,6 +465,7 @@ fn preference_uses_ambient_filesystem(path: &str) -> bool {
|
||||
fn command_uses_ambient_path(id: &str, params: &Value) -> bool {
|
||||
match id {
|
||||
"actions.load"
|
||||
| "actions.replace"
|
||||
| "brush.presets.importAbr"
|
||||
| "brush.presets.importImage"
|
||||
| "gradient.presets.importGrd"
|
||||
|
||||
@@ -435,6 +435,7 @@ fn apply_data_set_is_judged_by_the_values_it_applies() {
|
||||
assert!(!visible(&headless));
|
||||
}
|
||||
|
||||
/// Path-reading commands are refused before access; inline data keeps its precedence.
|
||||
#[test]
|
||||
fn automation_rejects_ambient_path_commands_and_preferences() {
|
||||
for (id, params) in [
|
||||
@@ -448,6 +449,7 @@ fn automation_rejects_ambient_path_commands_and_preferences() {
|
||||
("swatches.import", serde_json::json!({"path": "/outside/set.aco"})),
|
||||
("swatches.export", serde_json::json!({"path": "/outside/set.ase"})),
|
||||
("actions.load", serde_json::json!({"path": "/outside/set.atn"})),
|
||||
("actions.replace", serde_json::json!({"path": "/outside/set.atn", "confirm": true})),
|
||||
("actions.save", serde_json::json!({"path": "/outside/set.atn"})),
|
||||
("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})),
|
||||
("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})),
|
||||
@@ -465,6 +467,8 @@ fn automation_rejects_ambient_path_commands_and_preferences() {
|
||||
("swatches.import", serde_json::json!({"data": "QUJD"})),
|
||||
("swatches.export", serde_json::json!({"format": "ase"})),
|
||||
("actions.load", serde_json::json!({"data": "QUJD"})),
|
||||
("actions.replace", serde_json::json!({"data": "QUJD", "confirm": true})),
|
||||
("actions.replace", serde_json::json!({"data": "QUJD", "path": "/outside/unused.atn", "confirm": true})),
|
||||
("actions.save", serde_json::json!({"set": "S"})),
|
||||
("style.presets.importAsl", serde_json::json!({"data": "QUJD"})),
|
||||
("style.presets.exportAsl", serde_json::json!({"group": "Basics"})),
|
||||
|
||||
@@ -55,7 +55,7 @@ use descriptors::{jbool, jstr};
|
||||
use events::{EVENTS, event_and_descriptor, event_for};
|
||||
#[cfg(test)]
|
||||
use fields::Mapped;
|
||||
use files::{load, save};
|
||||
use files::{load, replace, save};
|
||||
pub use menu_item::{MENU_ITEM, menu_item_command};
|
||||
#[cfg(test)]
|
||||
use steps_doc::crop_from;
|
||||
@@ -110,6 +110,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
run: load,
|
||||
journal: false,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "actions.replace",
|
||||
label: "Replace Actions…",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name?,"confirm":true} → {set,actions:[names],steps,unsupported,functionKeys,warnings}. Parse and validate the file before replacing the entire action library and its function-key bindings. Requires explicit confirmation and stopped recording/playback. Other shortcuts and the document are unchanged."##,
|
||||
enabled: always,
|
||||
run: replace,
|
||||
journal: false,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "actions.save",
|
||||
label: "Save Actions…",
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
use super::convert::{UniqueNames, export, import};
|
||||
use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json};
|
||||
|
||||
/// Load with the existing append or same-named-set replacement semantics.
|
||||
pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "actions.load";
|
||||
import_actions(s, p, false)
|
||||
}
|
||||
|
||||
/// Whole-library replacement requires explicit consent before reading or changing anything.
|
||||
pub(super) fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("confirm").and_then(Value::as_bool) != Some(true) {
|
||||
return Err(bad("actions.replace", "replacing all actions requires `confirm`: true"));
|
||||
}
|
||||
if p.get("replace").is_some() {
|
||||
return Err(bad("actions.replace", "use `confirm`: true; `replace` belongs to actions.load's same-set mode"));
|
||||
}
|
||||
import_actions(s, p, true)
|
||||
}
|
||||
|
||||
/// Prepare names, references and shortcuts before committing either import mode.
|
||||
fn import_actions(s: &mut Session, p: &Value, whole: bool) -> Result<Value> {
|
||||
let cmd = if whole { "actions.replace" } else { "actions.load" };
|
||||
if s.actions.recording.is_some() || s.actions.playing > 0 {
|
||||
return Err(bad(cmd, "stop recording or playing before loading actions"));
|
||||
}
|
||||
@@ -23,10 +40,8 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(_) => return Err(bad(cmd, "`replace` must be true or false")),
|
||||
};
|
||||
if replace {
|
||||
s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str()));
|
||||
}
|
||||
let mut taken = UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone()));
|
||||
let retained = s.actions.list.iter().filter(|a| !whole && (!replace || a.set.as_deref() != Some(imp.set.as_str())));
|
||||
let mut taken = UniqueNames::new(retained.map(|a| a.name.clone()));
|
||||
let mut names = Vec::with_capacity(imp.actions.len());
|
||||
// The file's name of each action that had to be renamed, and its new name.
|
||||
let mut renamed: std::collections::HashMap<String, String> = std::collections::HashMap::new();
|
||||
@@ -58,10 +73,21 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
s.actions.list.extend(added);
|
||||
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() {
|
||||
let removed_keys: std::collections::HashSet<_> =
|
||||
if whole { s.actions.list.iter().map(|a| format!("{}{}", crate::actions_cmds::PLAY_SHORTCUT_PREFIX, a.name)).collect() } else { Default::default() };
|
||||
// Everything that can reject the input has completed. No callbacks or I/O split this commit.
|
||||
if whole {
|
||||
s.actions.list.clear();
|
||||
} else if replace {
|
||||
s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str()));
|
||||
}
|
||||
s.actions.list.extend(added);
|
||||
if !keys.is_empty() || !removed_keys.is_empty() {
|
||||
s.edit_prefs(|prefs| {
|
||||
if !removed_keys.is_empty() {
|
||||
prefs.shortcuts.retain(|key, _| !removed_keys.contains(key));
|
||||
}
|
||||
for (name, key) in &keys {
|
||||
// A function key belongs to one action.
|
||||
prefs.shortcuts.retain(|k, v| !(k.starts_with(crate::actions_cmds::PLAY_SHORTCUT_PREFIX) && v == key));
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Whole-library replacement shares import semantics without clearing before validation.
|
||||
use photocraft_engine::{Session, actions_cmds::Action, atn_cmds};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A caller, its named target and an action sharing an old name expose reference/key ownership.
|
||||
fn input() -> Vec<u8> {
|
||||
let mut caller = Action::new("Caller", vec![("actions.play".into(), json!({"action": "NewChild"})), ("select.deselect".into(), json!({}))]);
|
||||
caller.disabled.insert(1);
|
||||
caller.dialogs.insert(0);
|
||||
let child = Action::new("NewChild", vec![("select.all".into(), json!({}))]);
|
||||
let reused = Action::new("OldA", vec![("select.deselect".into(), json!({}))]);
|
||||
atn_cmds::export("Incoming", &[&caller, &child, &reused], &[("NewChild".into(), "F8".into())], false).unwrap().0
|
||||
}
|
||||
|
||||
/// Two old sets and owned/unloaded/global bindings distinguish whole from same-set replacement.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
|
||||
for (name, set) in [("OldA", "Incoming"), ("OldB", "Other")] {
|
||||
let mut a = Action::new(name, vec![("select.deselect".into(), json!({}))]);
|
||||
a.set = Some(set.into());
|
||||
s.actions.list.push(a);
|
||||
}
|
||||
s.prefs.edit(|p| {
|
||||
for (id, key) in [("actions.play:OldA", "F5"), ("actions.play:OldB", "F6"), ("actions.play:Unloaded", "F9"), ("view.zoomIn", "Cmd+0")] {
|
||||
p.shortcuts.insert(id.into(), key.into());
|
||||
}
|
||||
});
|
||||
s
|
||||
}
|
||||
|
||||
/// Same-set Load keeps other sets; confirmed Replace swaps all definitions and their keys.
|
||||
#[test]
|
||||
fn replace_preserves_imported_flags_references_and_keys_without_inheriting_old_bindings() {
|
||||
let data = photocraft_engine::paint::tile::b64_encode(&input());
|
||||
let mut loaded = session();
|
||||
loaded.execute("actions.load", json!({"data": data})).unwrap();
|
||||
assert!(loaded.actions.list.iter().any(|a| a.name == "OldB"), "ordinary Load still replaces only the matching set");
|
||||
let mut s = session();
|
||||
let revision = s.active().unwrap().revision;
|
||||
let history = s.active().unwrap().history.entries();
|
||||
let journal = s.journal.clone();
|
||||
let result = s.execute("actions.replace", json!({"data": data, "confirm": true})).unwrap();
|
||||
assert_eq!(result["actions"], json!(["Caller", "NewChild", "OldA"]));
|
||||
assert_eq!(s.actions.list.len(), 3);
|
||||
assert!(s.actions.list.iter().all(|a| a.set.as_deref() == Some("Incoming")));
|
||||
assert_eq!(s.actions.list[0].disabled.iter().copied().collect::<Vec<_>>(), [1]);
|
||||
assert_eq!(s.actions.list[0].dialogs.iter().copied().collect::<Vec<_>>(), [0]);
|
||||
assert!(!s.prefs().shortcuts.contains_key("actions.play:OldA"), "an identically named replacement does not inherit the old function key");
|
||||
assert!(!s.prefs().shortcuts.contains_key("actions.play:OldB"));
|
||||
assert_eq!(s.prefs().shortcuts["actions.play:NewChild"], "F8");
|
||||
assert_eq!(s.prefs().shortcuts["actions.play:Unloaded"], "F9");
|
||||
assert_eq!(s.prefs().shortcuts["view.zoomIn"], "Cmd+0");
|
||||
assert_eq!(s.active().unwrap().revision, revision);
|
||||
assert_eq!(s.active().unwrap().history.entries(), history);
|
||||
assert_eq!(s.journal, journal);
|
||||
let played = s.execute("actions.play", json!({"action": "Caller"})).unwrap();
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
assert!(s.active().unwrap().doc.selection.is_some(), "the imported named call still targets NewChild");
|
||||
let empty = atn_cmds::export("Empty", &[], &[], false).unwrap().0;
|
||||
let result = s.execute("actions.replace", json!({"data": photocraft_engine::paint::tile::b64_encode(&empty), "confirm": true})).unwrap();
|
||||
assert_eq!(result["set"], "Empty");
|
||||
assert!(s.actions.list.is_empty());
|
||||
assert!(!s.prefs().shortcuts.contains_key("actions.play:NewChild"));
|
||||
}
|
||||
|
||||
/// Rejected input, absent consent and active recording/playback never clear or flush definitions.
|
||||
#[test]
|
||||
fn invalid_or_unconfirmed_replacement_preserves_the_library_and_preferences() {
|
||||
let data = photocraft_engine::paint::tile::b64_encode(&input());
|
||||
let mut s = session();
|
||||
let list = s.actions.list.clone();
|
||||
let shortcuts = s.prefs().shortcuts.clone();
|
||||
let revision = s.active().unwrap().revision;
|
||||
let rev = s.actions.rev;
|
||||
for params in [
|
||||
json!({"data": data}),
|
||||
json!({"data": data, "confirm": false}),
|
||||
json!({"data": data, "confirm": "yes"}),
|
||||
json!({"data": data, "confirm": true, "replace": false}),
|
||||
json!({"data": "!invalid!", "confirm": true}),
|
||||
json!({"data": "QUJD", "confirm": true}),
|
||||
json!({"confirm": true}),
|
||||
json!({"data": data, "confirm": true, "set": " "}),
|
||||
json!({"data": data, "confirm": true, "set": 7}),
|
||||
] {
|
||||
assert!(s.execute("actions.replace", params.clone()).is_err(), "{params}");
|
||||
assert_eq!(s.actions.list, list);
|
||||
assert_eq!(s.prefs().shortcuts, shortcuts);
|
||||
assert_eq!(s.actions.rev, rev);
|
||||
assert_eq!(s.active().unwrap().revision, revision);
|
||||
}
|
||||
s.execute("actions.record", json!({"action": "OldA"})).unwrap();
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
let recording = s.actions.recording;
|
||||
assert!(s.execute("actions.replace", json!({"data": data, "confirm": true})).is_err());
|
||||
assert_eq!(s.actions.list, list, "pending recorded steps were not flushed");
|
||||
assert_eq!(s.actions.recording, recording);
|
||||
s.execute("actions.stop", json!({})).unwrap();
|
||||
s.actions.list.push(Action::new("Try Replace", vec![("actions.replace".into(), json!({"data": data, "confirm": true}))]));
|
||||
let list = s.actions.list.clone();
|
||||
let result: Value = s.execute("actions.play", json!({"action": "Try Replace"})).unwrap();
|
||||
assert!(result["failed"].is_object(), "{result}");
|
||||
assert_eq!(s.actions.list, list);
|
||||
assert_eq!(s.prefs().shortcuts, shortcuts);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod actions_clear_all;
|
||||
mod actions_duplicate;
|
||||
mod actions_replace;
|
||||
mod affinity;
|
||||
mod artboard_export_names;
|
||||
mod atn_crystallize_cell_size;
|
||||
|
||||
@@ -193,6 +193,7 @@ impl PhotocraftApp {
|
||||
dds_options: None,
|
||||
held_opens: Default::default(),
|
||||
held_preset_import: None,
|
||||
held_actions_replace: None,
|
||||
allow_close: false,
|
||||
stylus: Default::default(),
|
||||
control_click: Default::default(),
|
||||
|
||||
@@ -297,6 +297,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields:
|
||||
_ if crate::preset_group_prompt::owns(fields) => crate::preset_group_prompt::body(ui, fields),
|
||||
_ if crate::actions::owns_insert_stop(fields) => crate::actions::insert_stop_body(ui, fields),
|
||||
_ if crate::actions::clear_all::owns(fields) => crate::actions::clear_all::body(ui),
|
||||
_ if crate::actions::replace::owns(fields) => crate::actions::replace::body(app, ui, d.id),
|
||||
_ 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),
|
||||
@@ -847,6 +848,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[
|
||||
crate::disk_change_prompt::owns,
|
||||
crate::actions::owns_insert_stop,
|
||||
crate::actions::clear_all::owns,
|
||||
crate::actions::replace::owns,
|
||||
crate::new_layer_ui::owns,
|
||||
crate::new_group_ui::owns,
|
||||
crate::mask_trash_prompt::owns,
|
||||
@@ -1006,6 +1008,7 @@ fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value, String>
|
||||
_ if crate::preset_group_prompt::owns(&d.fields) => crate::preset_group_prompt::confirm(app, &d.fields),
|
||||
_ if crate::actions::owns_insert_stop(&d.fields) => crate::actions::insert_stop_confirm(app, &d.fields),
|
||||
_ if crate::actions::clear_all::owns(&d.fields) => crate::actions::clear_all::confirm(app, &d.fields),
|
||||
_ if crate::actions::replace::owns(&d.fields) => crate::actions::replace::confirm(app, d.id, &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),
|
||||
@@ -1057,6 +1060,9 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
|
||||
pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
|
||||
let closed = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?;
|
||||
crate::actions::stopped(app, &closed.fields);
|
||||
if crate::actions::replace::owns(&closed.fields) {
|
||||
crate::actions::replace::cancel(app, id);
|
||||
}
|
||||
if crate::guide_layout_ui::owns(&closed.fields) {
|
||||
app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id));
|
||||
}
|
||||
|
||||
@@ -689,6 +689,8 @@ pub struct PhotocraftApp {
|
||||
pub(crate) held_opens: std::collections::VecDeque<open_prompt::Held>,
|
||||
/// A brush or gradient file waiting on the group-name prompt (see `preset_group_prompt`).
|
||||
pub(crate) held_preset_import: Option<preset_group_prompt::Held>,
|
||||
/// The exact Actions input awaiting its own replacement confirmation.
|
||||
pub(crate) held_actions_replace: Option<actions::replace::Held>,
|
||||
/// Set once the user has agreed to quit, so the resulting close request goes through.
|
||||
pub(crate) allow_close: bool,
|
||||
/// Pen pressure/tilt from the platform (see `stylus`).
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::icons;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
pub(crate) mod clear_all;
|
||||
pub(crate) mod replace;
|
||||
|
||||
/// Which row is selected and which rows are expanded. The action list itself is
|
||||
/// [`photocraft_engine::Session::actions`].
|
||||
@@ -566,7 +567,7 @@ fn suspended(app: &PhotocraftApp) -> bool {
|
||||
/// action could go away or change place). The engine checks these against `recording`, which
|
||||
/// is `None` then.
|
||||
pub(crate) fn suspended_guard(app: &PhotocraftApp, id: &str) -> Result<(), String> {
|
||||
if matches!(id, "actions.record" | "actions.delete" | "actions.move" | "actions.duplicate" | "actions.clearAll") && suspended(app) {
|
||||
if matches!(id, "actions.record" | "actions.delete" | "actions.move" | "actions.duplicate" | "actions.clearAll" | "actions.replace") && suspended(app) {
|
||||
return Err(tl!("Confirm or cancel the open action step dialog first").into());
|
||||
}
|
||||
Ok(())
|
||||
@@ -710,6 +711,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(!recording, egui::Button::new(tl!("Replace Actions…"))).clicked() {
|
||||
act = Some("replace");
|
||||
}
|
||||
if ui.add_enabled(any, egui::Button::new(tl!("Save Actions…"))).clicked() {
|
||||
act = Some("save");
|
||||
}
|
||||
@@ -737,6 +741,7 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
"duplicate" => duplicate_selection(app),
|
||||
"clearAll" => clear_all::open(app),
|
||||
"load" => load_dialog(app),
|
||||
"replace" => replace::open(app),
|
||||
"stop" => insert_stop_dialog(app),
|
||||
_ => save_dialog(app, None),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! A picked Actions file belongs to one confirmation and never gets reread after consent.
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::{PhotocraftApp, state::DialogKind};
|
||||
|
||||
const COMMAND: &str = "actions.replace";
|
||||
const MARK: &str = "__replaceActions";
|
||||
|
||||
/// Frozen input and authority, kept out of editable and inspectable dialog fields.
|
||||
pub(crate) struct Held {
|
||||
dialog: u64,
|
||||
revision: u64,
|
||||
params: Value,
|
||||
gate: Option<super::Gate>,
|
||||
automated: bool,
|
||||
file: String,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
/// Identify the replacement handler through the existing protected route mechanism.
|
||||
pub(crate) fn owns(fields: &Map<String, Value>) -> bool {
|
||||
fields.contains_key(MARK)
|
||||
}
|
||||
|
||||
/// Apply both the request's authority and the current confirmation's authority.
|
||||
fn authorize(app: &PhotocraftApp, params: &Value, gate: Option<super::Gate>, automated: bool) -> Result<(), String> {
|
||||
if let Some(gate) = gate {
|
||||
gate(COMMAND, params).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if let Some(current) = app.session.authorize {
|
||||
current(COMMAND, params).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if (automated || app.automation_input || app.session.authorize.is_some())
|
||||
&& let Some(check) = app.services.automation_command.as_ref()
|
||||
{
|
||||
check(COMMAND, params)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A file picker or warning must not discard an active or suspended recording.
|
||||
fn idle(app: &PhotocraftApp) -> Result<(), String> {
|
||||
super::suspended_guard(app, COMMAND)?;
|
||||
if app.session.actions.recording.is_some() || app.session.actions.playing > 0 {
|
||||
return Err(tl!("Stop recording or playback before replacing actions.").into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pick a single file without changing Load Actions' separate bulk-import behavior.
|
||||
pub(super) fn open(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
idle(app)?;
|
||||
if app.held_actions_replace.is_some() {
|
||||
return Err(tl!("Confirm or cancel the pending Actions replacement first.").into());
|
||||
}
|
||||
let revision = app.session.actions.rev;
|
||||
let gate = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None });
|
||||
let automated = app.automation_input || gate.is_some();
|
||||
authorize(app, &json!({"confirm": true}), gate, automated)?;
|
||||
app.pick_file_bytes_filtered(&["atn"], move |app, name, bytes| {
|
||||
idle(app)?;
|
||||
if app.session.actions.rev != revision || app.held_actions_replace.is_some() {
|
||||
return Err(tl!("The actions changed. Request Replace Actions again.").into());
|
||||
}
|
||||
if bytes.len() as u64 > photocraft_engine::preset_import_cmds::MAX_FILE_BYTES {
|
||||
return Err(tl!("The Actions file is too large.").into());
|
||||
}
|
||||
// Validate before asking to discard the library. The normal command parses this
|
||||
// same immutable input again on confirmation, keeping dispatch authoritative.
|
||||
let count = photocraft_engine::atn_cmds::import(&bytes)?.actions.len();
|
||||
let params = json!({"data": photocraft_engine::paint::tile::b64_encode(&bytes), "confirm": true});
|
||||
drop(bytes);
|
||||
authorize(app, ¶ms, gate, automated)?;
|
||||
let fields = json!({MARK: true, "__command": COMMAND, "__label": "Replace Actions"});
|
||||
let dialog = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap_or_default());
|
||||
app.held_actions_replace = Some(Held { dialog, revision, params, gate, automated, file: crate::file_open::display_name(&name), count });
|
||||
Ok(json!({"dialog": dialog, "confirmationPending": true}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Show the actual held file and action count, never metadata supplied by dialog edits.
|
||||
pub(crate) fn body(app: &PhotocraftApp, ui: &mut egui::Ui, dialog: u64) {
|
||||
if let Some(held) = app.held_actions_replace.as_ref().filter(|held| held.dialog == dialog) {
|
||||
let text = crate::i18n::fmt(tl!("Replace all actions with {count} actions from {file}?"), &[("count", &held.count.to_string()), ("file", &held.file)]);
|
||||
ui.label(text);
|
||||
ui.label(tl!("This removes the current action library and cannot be undone."));
|
||||
}
|
||||
}
|
||||
|
||||
/// Only this warning may consume its input; every refusal releases that owned input.
|
||||
pub(crate) fn confirm(app: &mut PhotocraftApp, dialog: u64, fields: &Map<String, Value>) -> Result<Value, String> {
|
||||
if app.held_actions_replace.as_ref().is_none_or(|held| held.dialog != dialog) {
|
||||
return Err(tl!("No Actions replacement belongs to this dialog.").into());
|
||||
}
|
||||
let held = app.held_actions_replace.take().ok_or(tl!("No Actions replacement is waiting."))?;
|
||||
if fields.get("__command").and_then(Value::as_str) != Some(COMMAND) || app.session.actions.rev != held.revision {
|
||||
return Err(tl!("The actions or replacement command changed. Request Replace Actions again.").into());
|
||||
}
|
||||
idle(app)?;
|
||||
authorize(app, &held.params, held.gate, held.automated)?;
|
||||
let saved = app.session.authorize;
|
||||
app.session.authorize = saved.or(held.gate);
|
||||
let result = app.run(COMMAND, held.params);
|
||||
app.session.authorize = saved;
|
||||
let result = result?;
|
||||
app.ui.actions.selected = (!app.session.actions.list.is_empty()).then_some(0);
|
||||
app.ui.actions.selected_step = None;
|
||||
app.ui.actions.expanded = vec![false; app.session.actions.list.len()];
|
||||
if let Some(first) = app.ui.actions.expanded.first_mut() {
|
||||
*first = true;
|
||||
}
|
||||
app.ui.actions.renaming = None;
|
||||
app.ui.actions.reveal_recording = None;
|
||||
app.ui.panels.history = true;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Cancelling another dialog cannot discard this warning's staged replacement.
|
||||
pub(crate) fn cancel(app: &mut PhotocraftApp, dialog: u64) {
|
||||
if app.held_actions_replace.as_ref().is_some_and(|held| held.dialog == dialog) {
|
||||
app.held_actions_replace = None;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Replace Actions exercises the real asynchronous picker and its owned confirmation.
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
rc::Rc,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use photocraft_engine::{EngineError, Session, actions_cmds::Action, atn_cmds};
|
||||
use photocraft_ui_egui::{FileDialogAnswer, FileDialogReply, FileDialogRequest, PhotocraftApp, Services, actions, dialogs, state::DialogKind};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type Picker = Rc<RefCell<Vec<(FileDialogRequest, FileDialogReply)>>>;
|
||||
|
||||
/// Retain actual picker replies while drawing the menu, picker polling and confirmation.
|
||||
fn harness() -> (Harness<'static, PhotocraftApp>, Picker) {
|
||||
let picker: Picker = Default::default();
|
||||
let held = picker.clone();
|
||||
let services = Services { file_dialog: Some(Box::new(move |request, _, reply| held.borrow_mut().push((request, reply)))), ..Default::default() };
|
||||
let mut app = PhotocraftApp::new(Session::new(), services);
|
||||
app.run("file.new", json!({"width": 8, "height": 6})).unwrap();
|
||||
for (name, set) in [("A", "One"), ("B", "Two")] {
|
||||
let mut action = Action::new(name, vec![("select.deselect".into(), json!({}))]);
|
||||
action.set = Some(set.into());
|
||||
app.session.actions.list.push(action);
|
||||
}
|
||||
app.session.prefs.edit(|p| {
|
||||
p.shortcuts.insert("actions.play:A".into(), "F5".into());
|
||||
});
|
||||
app.ui.actions.selected = Some(1);
|
||||
app.ui.actions.selected_step = Some(0);
|
||||
app.ui.actions.expanded = vec![true, true];
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1000.0, 760.0)).build_ui_state(
|
||||
|ui, app| {
|
||||
actions::panel_menu(app, ui);
|
||||
app.poll_file_dialog(ui.ctx(), None);
|
||||
dialogs::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
PhotocraftApp::setup_context(&h.ctx, Default::default());
|
||||
h.run_steps(3);
|
||||
(h, picker)
|
||||
}
|
||||
|
||||
/// Encode a small valid file with visibly different action and set names.
|
||||
fn input() -> Vec<u8> {
|
||||
let action = Action::new("New", vec![("select.all".into(), json!({}))]);
|
||||
atn_cmds::export("Incoming", &[&action], &[], false).unwrap().0
|
||||
}
|
||||
|
||||
/// Open through the menu and verify that Replace does not use Load's multi-file picker.
|
||||
fn pick(h: &mut Harness<'static, PhotocraftApp>, picker: &Picker) {
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, "Replace Actions…").click();
|
||||
h.run_steps(3);
|
||||
assert!(matches!(picker.borrow().as_slice(), [(FileDialogRequest::Open { multiple: false, extensions: Some(ext), .. }, _)] if ext == &["atn"]));
|
||||
}
|
||||
|
||||
/// Deliver a platform answer through the real continuation, without bypassing staging.
|
||||
fn answer(h: &mut Harness<'static, PhotocraftApp>, picker: &Picker, answer: Option<FileDialogAnswer>) {
|
||||
picker.borrow_mut().pop().unwrap().1.send(answer);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// Stage a valid inline file and return its actual warning identity.
|
||||
fn stage(h: &mut Harness<'static, PhotocraftApp>, picker: &Picker) -> u64 {
|
||||
pick(h, picker);
|
||||
answer(h, picker, Some(FileDialogAnswer::Contents("Chosen.atn".into(), input())));
|
||||
let dialog = h.state().ui.dialogs.last().unwrap();
|
||||
assert_eq!(dialog.fields["__replaceActions"], true);
|
||||
assert!(!dialog.fields.contains_key("data"));
|
||||
dialog.id
|
||||
}
|
||||
|
||||
/// Both cancellations and malformed input preserve state; OK uses the bytes already picked.
|
||||
#[test]
|
||||
fn cancelling_preserves_actions_and_confirmation_never_rereads_the_source_path() {
|
||||
let (mut h, picker) = harness();
|
||||
let actions = h.state().session.actions.list.clone();
|
||||
let shortcuts = h.state().session.prefs().shortcuts.clone();
|
||||
let revision = h.state().session.active().unwrap().revision;
|
||||
pick(&mut h, &picker);
|
||||
answer(&mut h, &picker, None);
|
||||
assert!(h.state().ui.dialogs.is_empty());
|
||||
pick(&mut h, &picker);
|
||||
answer(&mut h, &picker, Some(FileDialogAnswer::Contents("Broken.atn".into(), b"bad".to_vec())));
|
||||
assert!(h.state().ui.dialogs.is_empty());
|
||||
stage(&mut h, &picker);
|
||||
h.get_by_label("Cancel").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().session.actions.list, actions);
|
||||
assert_eq!(h.state().session.prefs().shortcuts, shortcuts);
|
||||
assert_eq!(h.state().ui.actions.selected, Some(1));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("Picked.atn");
|
||||
std::fs::write(&path, input()).unwrap();
|
||||
pick(&mut h, &picker);
|
||||
answer(&mut h, &picker, Some(FileDialogAnswer::Paths(vec![path.to_str().unwrap().into()])));
|
||||
assert!(h.state().ui.dialogs.last().unwrap().fields.contains_key("__replaceActions"));
|
||||
std::fs::write(&path, b"changed after the warning").unwrap();
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().ui.dialogs.is_empty());
|
||||
assert_eq!(h.state().session.actions.list.len(), 1);
|
||||
assert_eq!(h.state().session.actions.list[0].name, "New");
|
||||
assert_eq!(h.state().ui.actions.selected, Some(0));
|
||||
assert_eq!(h.state().ui.actions.selected_step, None);
|
||||
assert_eq!(h.state().ui.actions.expanded, [true]);
|
||||
assert!(!h.state().session.prefs().shortcuts.contains_key("actions.play:A"));
|
||||
assert_eq!(h.state().session.active().unwrap().revision, revision);
|
||||
}
|
||||
|
||||
static DENIED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Model a retained caller whose authorization can be revoked while its warning is open.
|
||||
fn retained_gate(id: &str, _: &Value) -> photocraft_engine::Result<()> {
|
||||
if id == "actions.replace" && DENIED.load(Ordering::SeqCst) { Err(EngineError::Other("replace denied".into())) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Stale input, revoked retained authority and retargeting all refuse without consuming other dialogs.
|
||||
#[test]
|
||||
fn stale_denied_and_retargeted_confirmations_preserve_the_library() {
|
||||
for mode in ["picker-stale", "warning-stale", "denied", "retargeted"] {
|
||||
DENIED.store(false, Ordering::SeqCst);
|
||||
let (mut h, picker) = harness();
|
||||
if mode == "denied" {
|
||||
h.state_mut().session.authorize = Some(retained_gate);
|
||||
}
|
||||
if mode == "picker-stale" {
|
||||
pick(&mut h, &picker);
|
||||
h.state_mut().run("actions.rename", json!({"action": "A", "name": "Changed"})).unwrap();
|
||||
answer(&mut h, &picker, Some(FileDialogAnswer::Contents("Chosen.atn".into(), input())));
|
||||
assert!(h.state().ui.dialogs.is_empty());
|
||||
} else {
|
||||
let dialog = stage(&mut h, &picker);
|
||||
match mode {
|
||||
"warning-stale" => {
|
||||
h.state_mut().run("actions.rename", json!({"action": "A", "name": "Changed"})).unwrap();
|
||||
}
|
||||
"denied" => {
|
||||
h.state_mut().session.authorize = None;
|
||||
DENIED.store(true, Ordering::SeqCst);
|
||||
}
|
||||
_ => {
|
||||
h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("__command".into(), json!("select.all"));
|
||||
}
|
||||
}
|
||||
let before = h.state().session.actions.list.clone();
|
||||
assert!(dialogs::confirm(h.state_mut(), dialog).is_err(), "{mode}");
|
||||
assert_eq!(h.state().session.actions.list, before, "{mode}");
|
||||
}
|
||||
assert_eq!(h.state().session.actions.list.len(), 2, "{mode}");
|
||||
assert_eq!(h.state().session.prefs().shortcuts.get("actions.play:New"), None);
|
||||
DENIED.store(false, Ordering::SeqCst);
|
||||
let retry = stage(&mut h, &picker);
|
||||
dialogs::cancel(h.state_mut(), retry).unwrap();
|
||||
h.run_steps(3);
|
||||
}
|
||||
}
|
||||
|
||||
/// A forged warning cannot confirm or cancel the real warning's privately held bytes.
|
||||
#[test]
|
||||
fn another_dialog_cannot_consume_the_pending_replacement() {
|
||||
let (mut h, picker) = harness();
|
||||
let original = stage(&mut h, &picker);
|
||||
let fields = h.state().ui.dialogs.last().unwrap().fields.clone();
|
||||
let impostor = h.state_mut().ui.open_dialog(DialogKind::Command, fields.clone());
|
||||
assert!(dialogs::confirm(h.state_mut(), impostor).is_err());
|
||||
let impostor = h.state_mut().ui.open_dialog(DialogKind::Command, fields);
|
||||
dialogs::cancel(h.state_mut(), impostor).unwrap();
|
||||
assert_eq!(h.state().session.actions.list.len(), 2);
|
||||
dialogs::confirm(h.state_mut(), original).unwrap();
|
||||
assert_eq!(h.state().session.actions.list[0].name, "New");
|
||||
assert_eq!(h.state().session.actions.list.len(), 1);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod actions_clear_all;
|
||||
mod actions_duplicate;
|
||||
mod actions_replace;
|
||||
mod adjust_preview_gpu;
|
||||
mod arbitrary_rotation_preview;
|
||||
mod atn_menu_item;
|
||||
|
||||
Reference in new issue
Block a user