From f167ebe3daba0709c0206f94dc8dbcf2573a9b2a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 00:56:16 -0700 Subject: [PATCH] feat(engine): command macros: history records each step's commands, macro.* commands (M6) Every undo step keeps the commands it ran; Save As Command rewrites ids of this document to act on the selection or active layer, or names the step it can't keep. macro.run is one transactional undo step; macros call only what a plug-in may, and plug-ins can't call macro.*. anicraft-cli run reads saved command files. ADR 0097. --- crates/cli/src/lib.rs | 30 +- crates/engine/src/cmds_macro.rs | 516 +++++++++++++++++++++++++++++ crates/engine/src/cmds_plugin.rs | 3 + crates/engine/src/cmds_template.rs | 2 +- crates/engine/src/confirm.rs | 19 ++ crates/engine/src/history.rs | 93 +++++- crates/engine/src/lib.rs | 70 +++- crates/engine/src/macro_tests.rs | 353 ++++++++++++++++++++ crates/engine/src/plugin_tests.rs | 2 +- 9 files changed, 1075 insertions(+), 13 deletions(-) create mode 100644 crates/engine/src/cmds_macro.rs create mode 100644 crates/engine/src/macro_tests.rs diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index d44b3c18..d9f21d60 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -30,6 +30,8 @@ USAGE: anicraft-cli formats lists every export format, plug-ins included (JSON) anicraft-cli commands anicraft-cli run [--save ] + a JSON array of {cmd, params}, or a saved command + (one undo step; nothing changes if a step fails) anicraft-cli exec [] [--save ] anicraft-cli new --out [--width W] [--height H] [--fps F] anicraft-cli guide --out writes the user guide as HTML pages (open index.html) @@ -239,7 +241,16 @@ pub fn run(argv: &[String]) -> Result { let script = a.positional.get(1).ok_or("run needs a script.json")?; let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?; // Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it. - let steps: Vec = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}}: {e}"))?; + let parsed: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}} or a saved command: {e}"))?; + // A saved command (ADR 0097) runs as one transactional step, as in the app. + if parsed.is_object() { + let v = exec(&mut s, "macro.run", &json!({"path": script}))?; + if let Some(out) = a.flag("save") { + exec(&mut s, "file.save", &json!({"path": out}))?; + } + return serde_json::to_string_pretty(&v).map_err(|e| e.to_string()); + } + let steps: Vec = serde_json::from_value(parsed).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}}: {e}"))?; let mut results = Vec::new(); for (i, step) in steps.iter().enumerate() { let id = step.get("cmd").and_then(Value::as_str).ok_or_else(|| format!("step {}: missing \"cmd\"", i + 1))?; @@ -699,6 +710,23 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn run_takes_a_saved_command_file() { + let dir = std::env::temp_dir().join(format!("anicraft-cli-macro-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Spin.json"); + std::fs::write(&file, r#"{"format": "anicraft-command", "version": 1, "steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}]}"#).unwrap(); + let out = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap(); + let v: Value = serde_json::from_str(&out).unwrap(); + assert_eq!((v["name"].as_str(), v["steps"].as_u64()), (Some("Spin"), Some(2)), "{out}"); + // A failing step names itself and leaves nothing behind. + std::fs::write(&file, r#"{"steps": [{"cmd": "modify.rotate_cw"}, {"cmd": "layer.set_height", "params": {"height": 7}}]}"#).unwrap(); + let e = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap_err(); + assert!(e.contains("stopped at step 2 of 2"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn usage_and_errors() { assert!(run(&[]).unwrap().contains("USAGE")); diff --git a/crates/engine/src/cmds_macro.rs b/crates/engine/src/cmds_macro.rs new file mode 100644 index 00000000..dce54ad7 --- /dev/null +++ b/crates/engine/src/cmds_macro.rs @@ -0,0 +1,516 @@ +//! Saved commands (command macros, ADR 0097): steps picked in the History panel, kept as a +//! small JSON file and run again as one undo step. +//! +//! Every undo step remembers the commands it ran (`history::Recorded`). Save As Command turns +//! the picked steps into a saved command, rewriting what only makes sense in this document +//! (an element's or layer's id) to act on the current selection or active layer where the +//! command allows it, and refusing, with the step named, what can't be kept. A saved command +//! may call what a plug-in may (`plugin_may_call`) and never the `macro.*` commands, so it +//! can't recurse, touch files or the clipboard. +//! +//! A saved command is a file `/.json`: `{"format": "anicraft-command", +//! "version": 1, "steps": [{"cmd", "params", "label"}]}`. The file's name is the command's +//! name, so a shared file keeps whatever name it is given. `anicraft-cli run` scripts (a bare +//! JSON array of `{cmd, params}`) run the same way. Their order in the Commands menu is kept +//! in `/.order.json`. The shell passes the folder (its settings folder's `Commands`); +//! the engine never looks for it, as with templates. + +use crate::history::Recorded; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session, vfs}; +use serde_json::{Map, Value, json}; +use std::path::{Path, PathBuf}; + +/// The `format` a saved command's file declares. +pub const FORMAT: &str = "anicraft-command"; +/// The newest file version this build reads and the one it writes. +pub const VERSION: u64 = 1; +/// Most steps in one saved command. +pub const MAX_STEPS: usize = 1000; +/// Largest saved command file read. +pub const MAX_FILE_BYTES: u64 = 1 << 20; +/// Most saved commands listed from one folder. +pub const MAX_LISTED: usize = 500; +/// The file that keeps the order of the saved commands (a dot-name: no command is called that). +pub const ORDER_FILE: &str = ".order.json"; +/// Longest command id and step label kept from a file. +const MAX_CMD_CHARS: usize = 128; +const MAX_LABEL_CHARS: usize = 200; + +pub fn specs() -> Vec { + let c = |id, label, menu, params, mutates, run| CommandSpec { id, label, menu, shortcut: None, params, mutates, run }; + vec![ + c("macro.run", "Run Command…", "Commands", "{name + folder (a saved command) | path (a saved command's file, or a JSON array of {cmd, params}) | steps: [{cmd, params?, label?}], name? (for steps)} → {name, steps, results}: runs the steps in order as one undo step named after it. At the first step that fails nothing is changed and the error names the step. Steps may call what a plug-in may, never macro.*", true, run as crate::RunFn), + c("macro.list", "Manage Saved Commands…", "Commands", "{folder} → {commands: [{name, path, steps}], problems: [{file, error}]}: the saved commands in the folder, in their order (the app shows them in a window)", false, list), + c("macro.history", "List History Steps", "", "{} → {steps: [{index, label, undone, keep, commands?, why?, rewritten?}]}: every undo-history step as Save As Command keeps it: `keep` false says `why` it can't be kept; `rewritten` names params dropped so the step acts on the selection or active layer", false, history), + c("macro.save", "Save As Command…", "", "{folder, name, history: [index, ..] (as macro.history lists them) | steps: [{cmd, params?, label?}], confirm? (to replace a saved command of that name)} → {name, path, steps, rewritten}: keeps the steps as /.json, last in the list", false, save), + c("macro.rename", "Rename Saved Command", "", "{folder, name, to} → {name, from, path}: renames a saved command (its file); its place in the list stays", false, rename), + c("macro.delete", "Delete Saved Command", "", "{folder, name, confirm}: deletes a saved command's file (cannot be undone)", false, delete), + c("macro.move", "Move Saved Command", "", "{folder, name, index (its new place in the list, 0-based)}", false, move_to), + c("macro.import", "Add Saved Command from File", "", "{folder, path (a saved command's file), name? (default: the file's), confirm? (to replace one of that name)} → {name, path, steps}: checks it and copies it in, last in the list", false, import), + ] +} + +/// Whether a saved command may run command `id`, and if not, why: what a plug-in may, and +/// never a `macro.*` command (a saved command doesn't run, save or change saved commands). +pub fn macro_may_call(id: &str) -> std::result::Result<(), String> { + if id.split('.').next() == Some("macro") { + return Err("a saved command can't run, save or change saved commands".into()); + } + crate::cmds_plugin::plugin_may_call(id).map_err(|why| format!("{why} (a saved command may do only what a plug-in may)")) +} + +/// One step of a saved command. +#[derive(Clone, Debug, PartialEq)] +pub struct Step { + pub cmd: String, + /// Always an object. + pub params: Value, + /// What the History panel called it (may be empty: then the command's label). + pub label: String, +} + +impl Step { + /// The step's name in messages. + pub fn name(&self) -> String { + if !self.label.is_empty() { + return self.label.clone(); + } + crate::find_command(&self.cmd).map_or_else(|| self.cmd.clone(), |c| c.label.trim_end_matches('…').to_string()) + } +} + +/// A saved command: its name and steps. +#[derive(Clone, Debug, PartialEq)] +pub struct Macro { + pub name: String, + pub steps: Vec, +} + +impl Macro { + /// The file's content. + pub fn to_json(&self) -> Value { + let steps: Vec = self.steps.iter().map(|s| json!({"cmd": s.cmd, "params": s.params, "label": s.label})).collect(); + json!({"format": FORMAT, "version": VERSION, "steps": steps}) + } + + /// Reads a saved command named `name`: a file's object, or a bare array of steps (an + /// `anicraft-cli run` script). Every step is checked: a known command a saved command may + /// call, with object params. + pub fn from_json(v: &Value, name: &str) -> Result { + let steps = match v { + Value::Array(a) => a, + Value::Object(o) => { + if let Some(f) = o.get("format") + && f.as_str() != Some(FORMAT) + { + return Err(EngineError::Format(format!("not a saved command (its format is {f}, not \"{FORMAT}\")"))); + } + if let Some(v) = o.get("version") { + let v = v.as_u64().ok_or_else(|| EngineError::Format("a saved command's version is a whole number".into()))?; + if v > VERSION { + return Err(EngineError::Format(format!("this saved command was made by a newer AniCraft (version {v}); update AniCraft to run it"))); + } + } + o.get("steps").and_then(Value::as_array).ok_or_else(|| EngineError::Format("a saved command has a \"steps\" list".into()))? + } + _ => return Err(EngineError::Format("a saved command is a JSON object with \"steps\", or a list of {cmd, params}".into())), + }; + if steps.len() > MAX_STEPS { + return Err(EngineError::Format(format!("a saved command has at most {MAX_STEPS} steps (this one has {})", steps.len()))); + } + let mut out = Vec::with_capacity(steps.len()); + for (i, st) in steps.iter().enumerate() { + let n = i + 1; + let o = st.as_object().ok_or_else(|| EngineError::Format(format!("step {n} is not an object {{cmd, params}}")))?; + let cmd = o.get("cmd").or_else(|| o.get("command")).and_then(Value::as_str).ok_or_else(|| EngineError::Format(format!("step {n} has no \"cmd\"")))?; + if cmd.chars().count() > MAX_CMD_CHARS || crate::find_command(cmd).is_none() { + let shown: String = cmd.chars().take(40).collect(); + return Err(EngineError::Format(format!("step {n}: unknown command '{shown}'"))); + } + macro_may_call(cmd).map_err(|why| EngineError::Format(format!("step {n} ({cmd}) can't be in a saved command: {why}")))?; + let params = match o.get("params") { + None | Some(Value::Null) => Value::Object(Map::new()), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err(EngineError::Format(format!("step {n} ({cmd}): params are an object"))), + }; + let label: String = o.get("label").and_then(Value::as_str).unwrap_or("").chars().filter(|c| !c.is_control()).take(MAX_LABEL_CHARS).collect(); + out.push(Step { cmd: cmd.to_string(), params, label }); + } + Ok(Macro { name: name.to_string(), steps: out }) + } +} + +/// The file of the saved command called `name` in `folder`. +pub fn command_path(folder: &Path, name: &str) -> Result { + let name = crate::cmds_template::clean_name(name, "command")?; + Ok(folder.join(format!("{name}.json"))) +} + +/// Reads a saved command's file (its name is the file's). +pub fn load(path: &Path) -> Result { + let len = vfs::len(path).map_err(|e| EngineError::Io(std::io::Error::new(e.kind(), format!("{}: {e}", path.display()))))?; + if len > MAX_FILE_BYTES { + return Err(EngineError::Format(format!("{} is larger than a saved command can be ({} KiB at most)", path.display(), MAX_FILE_BYTES / 1024))); + } + let text = vfs::read_to_string(path)?; + // Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it. + let v: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| EngineError::Format(format!("{}: not JSON ({e})", path.display())))?; + let name = path.file_stem().map_or_else(|| "Command".to_string(), |n| n.to_string_lossy().into_owned()); + Macro::from_json(&v, &name) +} + +/// A saved command found in the folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Saved { + pub name: String, + pub path: PathBuf, + pub steps: usize, +} + +fn read_order(folder: &Path) -> Vec { + let path = folder.join(ORDER_FILE); + if vfs::len(&path).map_or(true, |n| n > MAX_FILE_BYTES) { + return Vec::new(); + } + let v: Value = vfs::read_to_string(&path).ok().and_then(|t| serde_json::from_str(t.trim_start_matches('\u{feff}')).ok()).unwrap_or(Value::Null); + v.as_array().into_iter().flatten().filter_map(Value::as_str).take(MAX_LISTED).map(str::to_string).collect() +} + +fn write_order(folder: &Path, names: &[String]) -> Result<()> { + let text = serde_json::to_string_pretty(names).map_err(|e| EngineError::Format(e.to_string()))?; + vfs::write(&folder.join(ORDER_FILE), text)?; + Ok(()) +} + +/// The saved commands in `folder`, in their order (then by name), and the files that aren't +/// saved commands with why: `(file name, error)`. +pub fn saved_commands(folder: &Path) -> (Vec, Vec<(String, String)>) { + let order: Vec = read_order(folder).into_iter().map(|n| n.to_lowercase()).collect(); + let mut found = Vec::new(); + let mut problems = Vec::new(); + for f in vfs::list(folder, MAX_LISTED * 2) { + let Some(stem) = f.file_stem().map(|n| n.to_string_lossy().into_owned()) else { continue }; + if stem.starts_with('.') || !f.extension().is_some_and(|e| e.eq_ignore_ascii_case("json")) || !vfs::is_file(&f) { + continue; + } + let file = f.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + match load(&f) { + Ok(m) if found.len() < MAX_LISTED => found.push(Saved { name: m.name, path: f, steps: m.steps.len() }), + Ok(_) => {} + Err(e) => problems.push((file, e.to_string())), + } + } + found.sort_by_key(|s| (order.iter().position(|o| *o == s.name.to_lowercase()).unwrap_or(usize::MAX), s.name.to_lowercase())); + problems.sort(); + (found, problems) +} + +fn folder(p: &Value) -> Result { + let f = str_req(p, "folder")?; + if f.trim().is_empty() { + return Err(EngineError::Param("name the saved commands' folder".into())); + } + Ok(PathBuf::from(f)) +} + +/// The saved command file the params name (`folder` and `name`). +pub(crate) fn target(p: &Value) -> Result { + command_path(&folder(p)?, str_req(p, "name")?) +} + +/// Where `macro.import` copies its file to. +pub(crate) fn import_target(p: &Value) -> Result { + let from = PathBuf::from(str_req(p, "path")?); + let name = match opt_str(p, "name")? { + Some(n) => n.to_string(), + None => from.file_stem().map(|n| n.to_string_lossy().into_owned()).ok_or_else(|| EngineError::Param("the file has no name".into()))?, + }; + command_path(&folder(p)?, &name) +} + +fn name_of(path: &Path) -> String { + path.file_stem().map_or_else(String::new, |n| n.to_string_lossy().into_owned()) +} + +/// The saved command the params name: by `name` in `folder`, a file's `path`, or `steps`. +fn resolve(p: &Value) -> Result { + if let Some(steps) = p.get("steps") { + let name = opt_str(p, "name")?.map_or_else(|| "Saved command".to_string(), |n| n.chars().filter(|c| !c.is_control()).take(crate::cmds_template::MAX_NAME_CHARS).collect()); + return Macro::from_json(steps, &name); + } + if let Some(path) = opt_str(p, "path")? { + return load(Path::new(path)); + } + let path = target(p).map_err(|e| EngineError::Param(format!("name a saved command (name and folder), a file (path) or steps: {e}")))?; + if !vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no saved command “{}”", name_of(&path)))); + } + load(&path) +} + +fn run(s: &mut Session, p: &Value) -> Result { + let m = resolve(p)?; + if m.steps.is_empty() { + return Err(EngineError::State(format!("“{}” has no steps to run", m.name))); + } + let n = m.steps.len(); + let mut results = Vec::with_capacity(n); + for (i, st) in m.steps.iter().enumerate() { + // (Checked when it was read; the rule is the run's, so it is checked here too.) + let r = macro_may_call(&st.cmd).map_err(EngineError::State).and_then(|()| s.execute_nested(&st.cmd, &st.params)); + match r { + Ok(v) => results.push(v), + // The session puts the document back as it was before the run. + Err(e) => return Err(EngineError::State(format!("“{}” stopped at step {} of {n} ({}): {e}. Nothing was changed.", m.name, i + 1, st.name()))), + } + } + s.step_label = Some(m.name.clone()); + // History keeps the steps, so a run can itself be saved again with other steps. + s.record_as = Some(m.steps.iter().map(|st| Recorded::new(&st.cmd, &st.params)).collect()); + Ok(json!({"name": m.name, "steps": n, "results": results})) +} + +fn list(_: &mut Session, p: &Value) -> Result { + let (found, problems) = saved_commands(&folder(p)?); + let commands: Vec = found.iter().map(|c| json!({"name": c.name, "path": c.path.display().to_string(), "steps": c.steps})).collect(); + let problems: Vec = problems.iter().map(|(f, e)| json!({"file": f, "error": e})).collect(); + Ok(json!({"commands": commands, "problems": problems})) +} + +/// Params naming who a step acts on: dropped, where the command then acts on the selection +/// (or, for layers, the active layer), so the step replays elsewhere. +const TARGETS: &[&str] = &["layer", "layers", "element", "elements", "id", "ids", "shape", "path", "symbol"]; +/// Params naming things that exist only in this document: Library items, folders and bones. +const FIXED: &[&str] = &["bitmap", "sound", "folder", "bone", "parent", "items"]; + +/// What a param names, in a sentence. +fn noun(key: &str) -> &'static str { + match key { + "layer" | "layers" => "particular layers", + "symbol" | "bitmap" | "sound" | "folder" | "items" => "particular Library items", + "bone" | "parent" | "from" | "to" => "particular bones", + _ => "particular objects", + } +} + +/// Whether the command's params doc makes `key` optional (`key?`), and, but for layers, says +/// it defaults to what is selected. +fn defaults_to_selection(doc: &str, key: &str) -> bool { + let pat = format!("{key}?"); + doc.match_indices(&pat).any(|(i, _)| { + let whole = doc.get(..i).and_then(|b| b.chars().next_back()).is_none_or(|c| !c.is_alphanumeric() && c != '_'); + let after: String = doc.get(i + pat.len()..).unwrap_or("").chars().take(90).collect(); + whole && (key.starts_with("layer") || after.contains("select")) + }) +} + +/// A recorded command as a saved command keeps it: its params without what names this +/// document's layers and objects (and which of those went), or why it can't be kept. +pub fn portable(cmd: &str, params: &Value) -> std::result::Result<(Value, Vec), String> { + macro_may_call(cmd)?; + let spec = crate::find_command(cmd).ok_or_else(|| format!("'{cmd}' is not a command any more"))?; + let Some(o) = params.as_object() else { return Ok((Value::Object(Map::new()), Vec::new())) }; + let mut out = Map::new(); + let mut dropped = Vec::new(); + for (k, v) in o { + let fixed = FIXED.contains(&k.as_str()) || (cmd.starts_with("bone.") && matches!(k.as_str(), "from" | "to")) || (cmd == "library.move" && k == "to"); + if v.is_null() || !(fixed || TARGETS.contains(&k.as_str())) { + out.insert(k.clone(), v.clone()); + } else if !fixed && defaults_to_selection(spec.params, k) { + dropped.push(k.clone()); + } else { + return Err(format!("it works on {} of this document", noun(k))); + } + } + Ok((Value::Object(out), dropped)) +} + +/// An undo step as a saved command keeps it: its steps and the params dropped, or why not. +fn keep_step(label: &str, cmds: Option<&[Recorded]>) -> std::result::Result<(Vec, Vec), String> { + let cmds = cmds.ok_or("it ran too many commands to keep (a very long drag?)")?; + if cmds.is_empty() { + return Err("it has nothing to run again".into()); + } + let mut steps = Vec::with_capacity(cmds.len()); + let mut dropped = Vec::new(); + for r in cmds { + let (params, gone) = portable(&r.cmd, &r.params)?; + for g in gone { + if !dropped.contains(&g) { + dropped.push(g); + } + } + steps.push(Step { cmd: r.cmd.clone(), params, label: label.to_string() }); + } + Ok((steps, dropped)) +} + +/// What dropped params mean for the step, in a sentence. +fn rewritten_note(dropped: &[String]) -> Option { + let layers = dropped.iter().any(|d| d.starts_with("layer")); + let objects = dropped.iter().any(|d| !d.starts_with("layer")); + match (objects, layers) { + (true, true) => Some("acts on the selection and the active layer".into()), + (true, false) => Some("acts on the selection".into()), + (false, true) => Some("acts on the active layer".into()), + (false, false) => None, + } +} + +fn history(s: &mut Session, _: &Value) -> Result { + let done = s.history().undo_len(); + let steps: Vec = s + .history() + .steps() + .enumerate() + .map(|(i, (label, cmds))| { + let mut v = json!({"index": i, "label": label, "undone": i >= done}); + match keep_step(label, cmds) { + Ok((steps, dropped)) => { + v["keep"] = json!(true); + v["commands"] = json!(steps.len()); + if let Some(note) = rewritten_note(&dropped) { + v["rewritten"] = json!(note); + } + } + Err(why) => { + v["keep"] = json!(false); + v["why"] = json!(why); + } + } + v + }) + .collect(); + Ok(json!({"steps": steps})) +} + +/// The steps the params ask to save: history steps by index, or steps given outright; and +/// what was rewritten, a sentence per step. +fn steps_to_save(s: &Session, p: &Value) -> Result<(Vec, Vec)> { + if let Some(v) = p.get("steps") { + return Ok((Macro::from_json(v, "")?.steps, Vec::new())); + } + let mut picked = opt_u64_list(p, "history")?.ok_or_else(|| EngineError::Param("pick the steps to keep: history (as macro.history lists them) or steps".into()))?; + picked.sort_unstable(); + picked.dedup(); + if picked.is_empty() { + return Err(EngineError::Param("pick at least one step to keep".into())); + } + let all: Vec<(&str, Option<&[Recorded]>)> = s.history().steps().collect(); + let mut steps = Vec::new(); + let mut notes = Vec::new(); + for i in picked { + let (label, cmds) = usize::try_from(i).ok().and_then(|i| all.get(i).copied()).ok_or_else(|| EngineError::Param(format!("there is no history step {i} (macro.history lists them)")))?; + let (kept, dropped) = keep_step(label, cmds).map_err(|why| EngineError::State(format!("step {} “{label}” can't be kept: {why}", i + 1)))?; + if let Some(note) = rewritten_note(&dropped) { + notes.push(json!({"index": i, "label": label, "note": note})); + } + steps.extend(kept); + if steps.len() > MAX_STEPS { + return Err(EngineError::State(format!("a saved command has at most {MAX_STEPS} steps"))); + } + } + Ok((steps, notes)) +} + +/// Adds `name` to the end of the folder's order (or leaves it where it is). +fn order_add(folder: &Path, name: &str) -> Result<()> { + let mut order = read_order(folder); + if !order.iter().any(|o| o.to_lowercase() == name.to_lowercase()) { + // The order holds every listed command, so a new one goes after all of them. + let (found, _) = saved_commands(folder); + let mut names: Vec = found.into_iter().map(|c| c.name).filter(|n| n.to_lowercase() != name.to_lowercase()).collect(); + names.push(name.to_string()); + order = names; + } + write_order(folder, &order) +} + +fn write_macro(path: &Path, m: &Macro) -> Result<()> { + if let Some(dir) = path.parent() { + vfs::create_dir_all(dir)?; + } + let text = serde_json::to_string_pretty(&m.to_json()).map_err(|e| EngineError::Format(e.to_string()))?; + vfs::write(path, text)?; + Ok(()) +} + +fn save(s: &mut Session, p: &Value) -> Result { + let path = target(p)?; + let (steps, rewritten) = steps_to_save(s, p)?; + if steps.is_empty() { + return Err(EngineError::Param("a saved command needs at least one step".into())); + } + let m = Macro { name: name_of(&path), steps }; + write_macro(&path, &m)?; + if let Some(dir) = path.parent() { + order_add(dir, &m.name)?; + } + Ok(json!({"name": m.name, "path": path.display().to_string(), "steps": m.steps.len(), "rewritten": rewritten})) +} + +fn import(_: &mut Session, p: &Value) -> Result { + let to = import_target(p)?; + let from = PathBuf::from(str_req(p, "path")?); + let m = Macro { name: name_of(&to), ..load(&from)? }; + write_macro(&to, &m)?; + if let Some(dir) = to.parent() { + order_add(dir, &m.name)?; + } + Ok(json!({"name": m.name, "path": to.display().to_string(), "steps": m.steps.len()})) +} + +fn existing(p: &Value) -> Result { + let path = target(p)?; + if !vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no saved command “{}”", name_of(&path)))); + } + Ok(path) +} + +fn rename(_: &mut Session, p: &Value) -> Result { + let from = existing(p)?; + let dir = folder(p)?; + let to = command_path(&dir, str_req(p, "to")?)?; + let (old, new) = (name_of(&from), name_of(&to)); + if old == new { + return Ok(json!({"name": new, "from": old})); + } + // A change of case only is the same file on Windows and macOS. + if old.to_lowercase() != new.to_lowercase() && vfs::exists(&to) { + return Err(EngineError::State(format!("there is already a saved command “{new}”"))); + } + vfs::rename(&from, &to)?; + let mut order = read_order(&dir); + for o in &mut order { + if o.to_lowercase() == old.to_lowercase() { + o.clone_from(&new); + } + } + write_order(&dir, &order)?; + Ok(json!({"name": new, "from": old, "path": to.display().to_string()})) +} + +fn delete(_: &mut Session, p: &Value) -> Result { + let path = existing(p)?; + let dir = folder(p)?; + let name = name_of(&path); + vfs::remove_file(&path)?; + let order: Vec = read_order(&dir).into_iter().filter(|o| o.to_lowercase() != name.to_lowercase()).collect(); + write_order(&dir, &order)?; + Ok(json!({"deleted": name})) +} + +fn move_to(_: &mut Session, p: &Value) -> Result { + let path = existing(p)?; + let dir = folder(p)?; + let name = name_of(&path); + let index = opt_u64(p, "index")?.ok_or_else(|| EngineError::Param("give the new place: index (0-based)".into()))?; + let (found, _) = saved_commands(&dir); + let mut names: Vec = found.into_iter().map(|c| c.name).filter(|n| n.to_lowercase() != name.to_lowercase()).collect(); + let at = usize::try_from(index).unwrap_or(usize::MAX).min(names.len()); + names.insert(at, name.clone()); + write_order(&dir, &names)?; + Ok(json!({"name": name, "index": at})) +} diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 5fa3167c..4b00ff27 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -56,6 +56,9 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { "swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"), "swatch" => Ok(()), "plugin" => Err("plug-ins can't install, run or remove plug-ins"), + // Saved commands are files in your preferences (ADR 0097), and running one from a + // plug-in would let the two call each other. + "macro" => Err("plug-ins can't run, save or change saved commands"), "desktop" => Err("plug-ins can't change your applications menu or which app opens your files"), "control" => Err("plug-ins can't play the movie"), // A scene's guides are the document's (ADR 0076); whether rulers, grid and guides diff --git a/crates/engine/src/cmds_template.rs b/crates/engine/src/cmds_template.rs index 881eb2ba..17c0e2c8 100644 --- a/crates/engine/src/cmds_template.rs +++ b/crates/engine/src/cmds_template.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { } /// A name usable as a file or folder name on every system, or why not. -fn clean_name(raw: &str, what: &str) -> Result { +pub(crate) fn clean_name(raw: &str, what: &str) -> Result { let name = raw.trim(); if name.is_empty() { return Err(EngineError::Param(format!("give the {what} a name"))); diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 064a752b..f39c0c73 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -116,6 +116,25 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: true, }) } + // Saved commands are files in your preferences (ADR 0097). + "macro.save" => { + let path = crate::cmds_macro::target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Saving the command")) + } + "macro.import" => { + let path = crate::cmds_macro::import_target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Adding the command")) + } + "macro.delete" => { + let path = crate::cmds_macro::target(p).ok()?; + let name = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + crate::vfs::is_file(&path).then(|| Confirmation { + title: "Delete saved command?".into(), + message: format!("The saved command “{name}” will be deleted from your commands. This cannot be undone."), + action: "Delete Command".into(), + irreversible: true, + }) + } // Brushes of your own live in your preferences, outside undo (ADR 0068). "brush.preset_delete" => { let name = p.get("name").and_then(Value::as_str)?; diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index a621124a..e62ab2e1 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -35,6 +35,89 @@ pub struct Snapshot { pub selection: crate::Selection, /// Estimated bytes this snapshot keeps alive that the neighbouring state does not share. pub bytes: usize, + /// The commands the step from this state ran, in order, as a saved command would run them + /// again (ADR 0097). `None`: they weren't kept (too many, or the step came from elsewhere). + pub commands: Option>, +} + +/// A command a history step ran: its id and params (ADR 0097). +#[derive(Clone, Debug, PartialEq)] +pub struct Recorded { + pub cmd: String, + pub params: serde_json::Value, + /// Roughly how much memory the params hold (their JSON's length). + pub bytes: usize, +} + +impl Recorded { + pub fn new(cmd: &str, params: &serde_json::Value) -> Recorded { + Recorded { cmd: cmd.to_string(), params: params.clone(), bytes: cmd.len() + params.to_string().len() } + } +} + +/// Most commands one step keeps: a longer step (a very long drag) can't be saved as a command. +pub const MAX_RECORDED: usize = 4096; +/// Most bytes of params one step keeps. +pub const MAX_RECORDED_BYTES: usize = 1 << 20; + +/// The commands run since the last step was recorded (ADR 0097). +#[derive(Clone, Debug, Default)] +pub(crate) struct Recording { + pub cmds: Vec, + pub bytes: usize, + /// More than [`MAX_RECORDED`] commands or [`MAX_RECORDED_BYTES`] bytes: none are kept. + pub overflow: bool, +} + +impl Recording { + /// Adds a command that changed the document. Moves in a row (a drag) add up into one. + pub fn push(&mut self, r: Recorded) { + if self.overflow { + return; + } + if let Some(last) = self.cmds.last_mut() + && let Some(sum) = merged_translate(last, &r) + { + *last = sum; + return; + } + self.bytes += r.bytes; + self.cmds.push(r); + if self.cmds.len() > MAX_RECORDED || self.bytes > MAX_RECORDED_BYTES { + self.overflow = true; + self.cmds = Vec::new(); + self.bytes = 0; + } + } + + pub fn truncate(&mut self, len: usize) { + if !self.overflow && len < self.cmds.len() { + self.cmds.truncate(len); + self.bytes = self.cmds.iter().map(|r| r.bytes).sum(); + } + } + + pub fn clear(&mut self) { + *self = Recording::default(); + } + + /// The commands for a step being recorded, leaving this empty. + pub fn take(&mut self) -> Option> { + let r = std::mem::take(self); + (!r.overflow).then(|| r.cmds.into()) + } +} + +/// Two `element.translate {dx, dy}` in a row as one, or `None`. +fn merged_translate(a: &Recorded, b: &Recorded) -> Option { + let plain = |r: &Recorded| { + let o = r.params.as_object()?; + (r.cmd == "element.translate" && o.len() == 2).then_some(())?; + Some((o.get("dx")?.as_f64()?, o.get("dy")?.as_f64()?)) + }; + let ((ax, ay), (bx, by)) = (plain(a)?, plain(b)?); + let (dx, dy) = (ax + bx, ay + by); + (dx.is_finite() && dy.is_finite()).then(|| Recorded::new("element.translate", &serde_json::json!({"dx": dx, "dy": dy}))) } /// Default memory budget for undo history. @@ -62,7 +145,7 @@ impl Default for History { impl History { /// Records `before` as an undo step leading to `current`, and clears redo. pub fn record(&mut self, mut before: Snapshot, current: &Document) { - before.bytes = unique_bytes(&before.doc, current); + before.bytes = unique_bytes(&before.doc, current) + before.commands.as_ref().map_or(0, |c| c.iter().map(|r| r.bytes).sum()); self.undo_bytes += before.bytes; self.undo.push_back(before); self.redo.clear(); @@ -85,6 +168,7 @@ impl History { self.undo_bytes = self.undo_bytes.saturating_sub(s.bytes); current.bytes = unique_bytes(¤t.doc, &s.doc); current.label = s.label.clone(); + current.commands = s.commands.clone(); self.redo_bytes += current.bytes; self.redo.push(current); Some(s) @@ -96,6 +180,7 @@ impl History { self.redo_bytes = self.redo_bytes.saturating_sub(s.bytes); current.bytes = unique_bytes(¤t.doc, &s.doc); current.label = s.label.clone(); + current.commands = s.commands.clone(); self.undo_bytes += current.bytes; self.undo.push_back(current); self.enforce_budget(); @@ -128,6 +213,12 @@ impl History { pub fn redo_labels(&self) -> impl Iterator { self.redo.iter().rev().map(|s| s.label.as_str()) } + /// Every step as the History panel lists it, oldest first: the steps that can be undone, + /// then the ones that can be redone (next to redo first), each with its label and the + /// commands it ran (ADR 0097). + pub fn steps(&self) -> impl Iterator)> { + self.undo.iter().chain(self.redo.iter().rev()).map(|s| (s.label.as_str(), s.commands.as_deref())) + } /// Estimated memory held by history. pub fn bytes(&self) -> usize { self.undo_bytes + self.redo_bytes diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ce55f0aa..748bdaa8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ mod cmds_retime; mod cmds_hints; mod cmds_layer; pub mod cmds_library; +pub mod cmds_macro; pub mod cmds_paint; mod cmds_path; pub mod cmds_raw; @@ -180,6 +181,7 @@ pub fn commands() -> Vec { v.extend(cmds_sound::specs()); v.extend(cmds_actions::specs()); v.extend(cmds_script::specs()); + v.extend(cmds_macro::specs()); v } @@ -198,7 +200,7 @@ pub fn find_command(id: &str) -> Option { commands().into_iter().find(|c| c.id == id) } -pub use history::{Snapshot, StateId}; +pub use history::{Recorded, Snapshot, StateId}; pub use selection::Selection; pub use snap::{Accuracy, SnapTo, ViewAids}; pub use cmds_layer::LAYER_COLORS; @@ -380,6 +382,13 @@ pub struct Session { pub filter_clipboard: Option>, /// The open envelope (ADR 0080): view state over the shapes it bends, like a gesture. pub(crate) envelope: Option, + /// The commands run since the last undo step was recorded, which the next step keeps so it + /// can be saved as a command (ADR 0097). + rec: history::Recording, + /// How many commands were recorded when the open gesture began (a revert goes back there). + gesture_rec: usize, + /// What the running command records instead of itself (`macro.run` records its steps). + pub(crate) record_as: Option>, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -455,6 +464,9 @@ impl Session { filter_presets: filter_library::FilterLibrary::default(), filter_clipboard: None, envelope: None, + rec: history::Recording::default(), + gesture_rec: 0, + record_as: None, } } @@ -497,6 +509,7 @@ impl Session { } // On a marquee's cut, the step (if the gesture makes one) starts from before the cut. let cut = self.live_cut().map(|p| (history::Snapshot { label: label.to_string(), ..p.before.clone() }, p.cut.clone())); + self.gesture_rec = self.rec.cmds.len(); match cut { Some((before, doc)) => { self.gesture_cut = Some(doc); @@ -520,8 +533,17 @@ impl Session { } self.provisional = None; } + self.record(before); + } + + /// Records `before` as the undo step to the current document, with the commands run since + /// the last step; an unchanged document records nothing and forgets them. + fn record(&mut self, mut before: Snapshot) { if self.doc != before.doc { + before.commands = self.rec.take(); self.history.record(before, &self.doc); + } else { + self.rec.clear(); } } @@ -565,10 +587,7 @@ impl Session { { return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message))); } - // A group open for editing is one layer and one frame (ADR 0073). - if spec.mutates && self.editing_group() && GROUP_REFUSES.iter().any(|ns| if ns.ends_with('.') { id.starts_with(ns) } else { id == *ns }) { - return Err(EngineError::State("a group has one layer and one frame: close it (Edit › Edit Document) to change the timeline, or convert it to a symbol (F8) to animate inside it".into())); - } + self.group_allows(&spec)?; self.settle_cut(id, params); if !spec.mutates { let r = (spec.run)(self, params); @@ -588,7 +607,9 @@ impl Session { self.pending_cut = None; self.motion_edit = None; self.step_label = None; + self.record_as = None; let result = (spec.run)(self, params); + let record_as = self.record_as.take(); // Edits to a motion tween's target become property keys (auto-key). if let Some(edit) = self.motion_edit.take() && result.is_ok() @@ -610,6 +631,10 @@ impl Session { if changed { self.state = history::fresh_state(); self.revision += 1; + match record_as { + Some(steps) => steps.into_iter().for_each(|r| self.rec.push(r)), + None => self.rec.push(Recorded::new(id, params)), + } match pending.filter(|_| self.gesture.is_none()) { // A marquee's cut: provisional, no step (yet). Some((origin, inside)) => self.begin_cut(before, cut.is_some(), origin, inside), @@ -617,8 +642,8 @@ impl Session { if cut.is_some() { self.provisional = None; } - if self.gesture.is_none() && self.doc != before.doc { - self.history.record(before, &self.doc); + if self.gesture.is_none() { + self.record(before); } } } @@ -635,6 +660,16 @@ impl Session { } } + /// A group open for editing is one layer and one frame (ADR 0073): commands that change + /// the timeline are refused inside it. + fn group_allows(&self, spec: &CommandSpec) -> Result<()> { + let id = spec.id; + if spec.mutates && self.editing_group() && GROUP_REFUSES.iter().any(|ns| if ns.ends_with('.') { id.starts_with(ns) } else { id == *ns }) { + return Err(EngineError::State("a group has one layer and one frame: close it (Edit › Edit Document) to change the timeline, or convert it to a symbol (F8) to animate inside it".into())); + } + Ok(()) + } + /// Inside a group (ADR 0073) the playhead stays on its only frame. fn hold_group_frame(&mut self) { if self.frame != 0 && self.editing_group() { @@ -699,6 +734,8 @@ impl Session { if self.saved_state == Some(p.state) { self.saved_state = Some(p.before.state); } + // The cut's commands went with it. + self.rec.clear(); self.doc = p.before.doc; self.state = p.before.state; self.selection = sel; @@ -720,9 +757,19 @@ impl Session { if !spec.mutates { return (spec.run)(self, params); } + self.group_allows(&spec)?; let before = self.snapshot(""); self.dl_cache.replace(None); + // Each command's edits to a motion tween's target become its keys, as when it runs on + // its own (the next one may work at another frame). + let outer = self.motion_edit.take(); let result = (spec.run)(self, params); + if let Some(edit) = self.motion_edit.take() + && result.is_ok() + { + cmds_motion::finish_edit(self, edit); + } + self.motion_edit = outer; self.dl_cache.replace(None); self.pending_cut = None; match result { @@ -752,14 +799,15 @@ impl Session { if g.doc == self.doc && g.selection == self.selection { return; } - let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 }; + let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0, commands: None }; + self.rec.truncate(self.gesture_rec); self.restore(back); self.revision += 1; self.fix_selection(); } fn snapshot(&self, label: &str) -> Snapshot { - Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } + Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0, commands: None } } fn restore(&mut self, s: Snapshot) { @@ -790,6 +838,7 @@ impl Session { pub fn undo(&mut self) -> Result { self.end_gesture(); self.heal_cut(); + self.rec.clear(); let cur = self.snapshot(""); let s = self.history.undo(cur).ok_or_else(|| EngineError::State("nothing to undo".into()))?; let label = s.label.clone(); @@ -802,6 +851,7 @@ impl Session { pub fn redo(&mut self) -> Result { self.end_gesture(); self.heal_cut(); + self.rec.clear(); let cur = self.snapshot(""); let s = self.history.redo(cur).ok_or_else(|| EngineError::State("nothing to redo".into()))?; let label = s.label.clone(); @@ -1128,6 +1178,8 @@ mod motion_pin_tests; #[cfg(test)] mod plugin_tests; #[cfg(test)] +mod macro_tests; +#[cfg(test)] mod plugin_kinds_tests; #[cfg(test)] mod tests_sound; diff --git a/crates/engine/src/macro_tests.rs b/crates/engine/src/macro_tests.rs new file mode 100644 index 00000000..e41ca157 --- /dev/null +++ b/crates/engine/src/macro_tests.rs @@ -0,0 +1,353 @@ +//! Saved commands (ADR 0097): what history records, Save As Command from history steps, a run +//! as one transactional undo step, the folder's order, the policy, and hostile files. + +use super::*; +use crate::cmds_macro::{self, Macro, macro_may_call}; +use serde_json::json; +use std::path::PathBuf; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-macros-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The elements on the active layer at the playhead, without their ids (which differ between +/// documents), as JSON. +fn looks(s: &Session) -> Vec { + s.visible_elements() + .iter() + .map(|e| { + let mut v = serde_json::to_value(&**e).unwrap(); + v.as_object_mut().unwrap().remove("id"); + v + }) + .collect() +} + +/// A rectangle, selected. +fn with_rect(x: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": x, "y": 20, "w": 80, "h": 40})); + run(&mut s, "edit.select_all", json!({})); + s +} + +/// Three edits on the selection: a drag (many moves in one step), a quarter turn and a fade. +fn edit(s: &mut Session) { + s.begin_gesture("Move"); + for _ in 0..30 { + run(s, "element.translate", json!({"dx": 2, "dy": -1})); + } + s.end_gesture(); + run(s, "modify.rotate_cw", json!({})); + run(s, "element.set_color_effect", json!({"style": "alpha", "alpha": 40})); +} + +#[test] +fn history_keeps_each_steps_commands_and_a_drag_as_one_move() { + let mut s = with_rect(10.0); + edit(&mut s); + let steps: Vec<(String, Option>)> = s.history().steps().map(|(l, c)| (l.to_string(), c.map(<[Recorded]>::to_vec))).collect(); + assert_eq!(steps.len(), 4, "{:?}", steps.iter().map(|s| &s.0).collect::>()); + let cmds = |i: usize| steps[i].1.clone().unwrap(); + assert_eq!(cmds(0)[0].cmd, "draw.rect"); + // Thirty moves in a drag add up to one. + assert_eq!(cmds(1).len(), 1); + assert_eq!(cmds(1)[0].params, json!({"dx": 60.0, "dy": -30.0})); + assert_eq!(cmds(2)[0].cmd, "modify.rotate_cw"); + assert_eq!(cmds(3)[0].params, json!({"style": "alpha", "alpha": 40})); + // Undo and redo carry them along. + s.undo().unwrap(); + s.redo().unwrap(); + assert_eq!(s.history().steps().nth(3).and_then(|(_, c)| c).map(<[Recorded]>::len), Some(1)); +} + +#[test] +fn a_live_preview_records_only_what_it_ended_on() { + let mut s = with_rect(10.0); + s.begin_gesture("Nudge"); + run(&mut s, "modify.rotate_cw", json!({})); + s.revert_gesture(); + run(&mut s, "element.translate", json!({"dx": 5, "dy": 0})); + s.end_gesture(); + let last = s.history().steps().last().and_then(|(_, c)| c.map(<[Recorded]>::to_vec)).unwrap(); + assert_eq!(last.iter().map(|r| r.cmd.as_str()).collect::>(), ["element.translate"]); +} + +#[test] +fn record_and_replay_equals_the_original_edits_on_a_fresh_selection() { + let dir = temp_dir("replay"); + let folder = dir.display().to_string(); + let mut original = with_rect(10.0); + edit(&mut original); + let listed = run(&mut original, "macro.history", json!({})); + let keep: Vec = listed["steps"].as_array().unwrap().iter().map(|v| v["keep"].as_bool().unwrap()).collect(); + assert_eq!(keep, [true, true, true, true], "{listed}"); + let saved = run(&mut original, "macro.save", json!({"folder": folder, "name": "Turn and Fade", "history": [1, 2, 3]})); + assert_eq!(saved["steps"], 3); + assert!(dir.join("Turn and Fade.json").is_file()); + + // Elsewhere: another document, another rectangle drawn the same way but with other ids. + let mut other = Session::default(); + run(&mut other, "draw.ellipse", json!({"x": 300, "y": 300, "w": 10, "h": 10})); + run(&mut other, "edit.deselect", json!({})); + run(&mut other, "draw.rect", json!({"x": 10, "y": 20, "w": 80, "h": 40})); + let rect = other.visible_elements().last().unwrap().id; + run(&mut other, "element.select", json!({"ids": [rect.0]})); + let steps = other.history_len(); + let before_run = looks(&other); + let oval = before_run.first().cloned(); + let v = run(&mut other, "macro.run", json!({"folder": folder, "name": "Turn and Fade"})); + assert_eq!(v["steps"], 3); + assert_eq!(other.history_len(), steps + 1, "one undo step"); + assert_eq!(other.undo_label(), Some("Turn and Fade")); + let mine = looks(&other); + assert_eq!(mine.last(), looks(&original).last(), "the rectangle ends up as in the original"); + // The oval, not selected, is untouched. + assert_eq!(mine.first().cloned(), oval); + // One undo takes the whole run back. + other.undo().unwrap(); + assert_eq!(looks(&other), before_run); + // And the run's step can itself be saved again: history keeps its steps, not macro.run. + other.redo().unwrap(); + let again = run(&mut other, "macro.history", json!({})); + let last = again["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!((last["keep"].as_bool(), last["commands"].as_u64()), (Some(true), Some(3)), "{last}"); +} + +#[test] +fn a_failing_step_changes_nothing_and_is_named() { + let mut s = with_rect(10.0); + let (doc, state, steps) = (s.doc.clone(), s.state, s.history_len()); + let steps_json = json!([ + {"cmd": "element.translate", "params": {"dx": 10, "dy": 0}}, + {"cmd": "modify.rotate_cw"}, + {"cmd": "layer.set_height", "params": {"height": 7}, "label": "Taller row"}, + ]); + let e = s.execute("macro.run", &json!({"name": "Broken", "steps": steps_json})).unwrap_err().to_string(); + assert!(e.contains("“Broken” stopped at step 3 of 3 (Taller row)") && e.contains("Nothing was changed"), "{e}"); + assert!(s.doc == doc, "the document is as it was"); + assert_eq!((s.state, s.history_len()), (state, steps)); + assert_eq!(s.selection.len(), 1, "the selection too"); +} + +#[test] +fn steps_tied_to_this_document_act_on_the_selection_or_say_why_they_cant_be_kept() { + let mut s = with_rect(10.0); + let layer = s.layer.0; + let id = s.selection.id_list()[0]; + // A layer named by id: the step acts on the active layer instead. + run(&mut s, "layer.set_color", json!({"color": "#ff0000", "layer": layer})); + // An element named by id where the command can take the selection instead. + run(&mut s, "stroke.set_profile", json!({"profile": "taper_both", "id": id})); + // An element named by id where the command can't do without it. + run(&mut s, "path.move_points", json!({"id": id, "points": [[0, 0]], "dx": 3, "dy": 0})); + let v = run(&mut s, "macro.history", json!({})); + let steps = v["steps"].as_array().unwrap(); + assert_eq!(steps[1]["rewritten"], "acts on the active layer", "{v}"); + assert_eq!(steps[2]["rewritten"], "acts on the selection", "{v}"); + assert_eq!(steps[3]["keep"], false); + assert!(steps[3]["why"].as_str().unwrap().contains("particular objects"), "{v}"); + let dir = temp_dir("rewrite"); + let folder = dir.display().to_string(); + let e = s.execute("macro.save", &json!({"folder": folder, "name": "Mixed", "history": [1, 2, 3]})).unwrap_err().to_string(); + assert!(e.starts_with("step 4 “") && e.contains("can't be kept"), "{e}"); + assert!(!dir.join("Mixed.json").exists(), "nothing saved"); + let saved = run(&mut s, "macro.save", json!({"folder": folder, "name": "Mixed", "history": [2, 1]})); + assert_eq!(saved["rewritten"].as_array().map(Vec::len), Some(2)); + let m = cmds_macro::load(&dir.join("Mixed.json")).unwrap(); + assert_eq!(m.steps[0].params, json!({"color": "#ff0000"}), "in history order, the layer's id gone"); + assert_eq!(m.steps[1].params, json!({"profile": "taper_both"})); +} + +#[test] +fn saved_commands_call_only_what_a_plug_in_may() { + assert!(macro_may_call("element.translate").is_ok()); + for id in ["file.save", "edit.paste", "edit.undo", "plugin.run", "macro.run", "macro.delete", "prefs.set", "view.rulers"] { + assert!(macro_may_call(id).is_err(), "{id}"); + } + // Plug-ins can't reach saved commands either, so the two never call each other. + for c in commands().iter().filter(|c| c.id.starts_with("macro.")) { + assert!(crate::cmds_plugin::plugin_may_call(c.id).is_err(), "{}", c.id); + } + for (step, why) in [(json!({"cmd": "file.save", "params": {"path": "x.anicraft"}}), "files"), (json!({"cmd": "macro.run", "params": {"path": "x.json"}}), "saved commands"), (json!({"cmd": "no.such"}), "unknown command")] { + let e = Macro::from_json(&json!([step]), "x").unwrap_err().to_string(); + assert!(e.contains("step 1") && e.contains(why), "{e}"); + } + // A history step that used the clipboard can't be kept. + let mut s = with_rect(10.0); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "edit.paste", json!({})); + let v = run(&mut s, "macro.history", json!({})); + let last = v["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last["keep"], false); + assert!(last["why"].as_str().unwrap().contains("clipboard"), "{last}"); +} + +#[test] +fn the_folder_keeps_order_renames_and_deletes_only_when_confirmed() { + let dir = temp_dir("manage"); + let folder = dir.display().to_string(); + let mut s = with_rect(10.0); + run(&mut s, "modify.rotate_cw", json!({})); + for name in ["Alpha", "Bravo", "Charlie"] { + run(&mut s, "macro.save", json!({"folder": folder, "name": name, "history": [1]})); + } + let names = |s: &mut Session| -> Vec { run(s, "macro.list", json!({"folder": folder}))["commands"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap().to_string()).collect() }; + assert_eq!(names(&mut s), ["Alpha", "Bravo", "Charlie"], "in the order saved"); + run(&mut s, "macro.move", json!({"folder": folder, "name": "Charlie", "index": 0})); + assert_eq!(names(&mut s), ["Charlie", "Alpha", "Bravo"]); + run(&mut s, "macro.rename", json!({"folder": folder, "name": "Alpha", "to": "Delta"})); + assert_eq!(names(&mut s), ["Charlie", "Delta", "Bravo"], "a rename keeps its place"); + assert!(s.execute("macro.rename", &json!({"folder": folder, "name": "Delta", "to": "Bravo"})).unwrap_err().to_string().contains("already")); + assert!(s.execute("macro.rename", &json!({"folder": folder, "name": "Delta", "to": "a/b"})).is_err()); + // Saving over one asks first; deleting always does (a file: undo can't bring it back). + assert!(matches!(s.execute("macro.save", &json!({"folder": folder, "name": "Bravo", "history": [1]})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "macro.save", json!({"folder": folder, "name": "Bravo", "history": [0, 1], "confirm": true})); + assert_eq!(names(&mut s), ["Charlie", "Delta", "Bravo"], "a replaced command keeps its place"); + assert!(matches!(s.execute("macro.delete", &json!({"folder": folder, "name": "Charlie"})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "macro.delete", json!({"folder": folder, "name": "Charlie", "confirm": true})); + assert_eq!(names(&mut s), ["Delta", "Bravo"]); + // A shared file comes in under its own name, checked. + let shared = dir.join("shared"); + std::fs::create_dir_all(&shared).unwrap(); + std::fs::write(shared.join("Spin.json"), r#"[{"cmd": "modify.rotate_cw"}, {"command": "modify.rotate_cw"}]"#).unwrap(); + let v = run(&mut s, "macro.import", json!({"folder": folder, "path": shared.join("Spin.json").display().to_string()})); + assert_eq!(v["steps"], 2); + assert_eq!(names(&mut s), ["Delta", "Bravo", "Spin"]); + // ...and runs straight from where it is (Run Command…). + let before = s.visible_elements()[0].transform; + run(&mut s, "macro.run", json!({"path": shared.join("Spin.json").display().to_string()})); + assert_eq!(s.undo_label(), Some("Spin")); + assert_ne!(s.visible_elements()[0].transform, before); + // Files that aren't saved commands are listed as problems, never as commands. + std::fs::write(dir.join("junk.json"), "{nope").unwrap(); + let v = run(&mut s, "macro.list", json!({"folder": folder})); + assert_eq!(v["problems"][0]["file"], "junk.json"); + assert_eq!(names(&mut s).len(), 3); +} + +#[test] +fn hostile_saved_command_files_never_panic() { + let dir = temp_dir("hostile"); + let deep = format!("{}{}", "[".repeat(5000), "]".repeat(5000)); + let many = serde_json::to_string(&vec![json!({"cmd": "modify.rotate_cw"}); cmds_macro::MAX_STEPS + 1]).unwrap(); + let mut bodies: Vec> = vec![ + Vec::new(), + b"\xef\xbb\xbf".to_vec(), + b"\xff\xfe\x00\x01garbage".to_vec(), + deep.into_bytes(), + many.into_bytes(), + "x".repeat((cmds_macro::MAX_FILE_BYTES + 10) as usize).into_bytes(), + ]; + for text in [ + "null", + "7", + "\"steps\"", + "{}", + r#"{"format": "something-else", "steps": []}"#, + r#"{"format": "anicraft-command", "version": 99, "steps": []}"#, + r#"{"format": "anicraft-command", "version": -1, "steps": []}"#, + r#"{"steps": "no"}"#, + r#"{"steps": [7, null, "x"]}"#, + r#"{"steps": [{"cmd": 7}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": [1, 2]}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": {"dx": 1e308, "dy": -1e308}}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": {"dx": "a"}}]}"#, + r#"{"steps": [{"cmd": "draw.rect", "params": {"x": 0, "y": 0, "w": 1e30, "h": -1}, "label": 5}]}"#, + r#"{"steps": [{"cmd": "layer.delete"}, {"cmd": "layer.delete"}, {"cmd": "layer.delete"}]}"#, + r#"{"steps": [{"cmd": "edit.undo"}]}"#, + r#"{"steps": [{"cmd": "file.export_png", "params": {"path": "/tmp/x.png"}}]}"#, + r#"{"steps": [{"cmd": "macro.run", "params": {"path": "self.json"}}]}"#, + r#"{"steps": [{"cmd": "plugin.run", "params": {"id": "x"}}]}"#, + ] { + bodies.push(text.as_bytes().to_vec()); + } + bodies.push(json!({"steps": [{"cmd": "modify.rotate_cw", "label": "\u{0}\u{202e} evil"}]}).to_string().into_bytes()); + // Truncations of a good file at every byte, and a few flipped bytes. + let good = serde_json::to_vec(&Macro { name: String::new(), steps: vec![cmds_macro::Step { cmd: "element.translate".into(), params: json!({"dx": 3, "dy": 4}), label: "Move".into() }] }.to_json()).unwrap(); + for i in 0..good.len() { + bodies.push(good[..i].to_vec()); + let mut flipped = good.clone(); + flipped[i] ^= 0x5a; + bodies.push(flipped); + } + let mut s = with_rect(10.0); + for (i, body) in bodies.iter().enumerate() { + let path = dir.join(format!("h{i}.json")); + std::fs::write(&path, body).unwrap(); + let (doc, steps) = (s.doc.clone(), s.history_len()); + match s.execute("macro.run", &json!({"path": path.display().to_string()})) { + Ok(_) => assert!(s.history_len() <= steps + 1), + Err(_) => assert!(s.doc == doc && s.history_len() == steps, "a refused file changed the document"), + } + let _ = s.execute("macro.import", &json!({"folder": dir.join("in").display().to_string(), "path": path.display().to_string(), "confirm": true})); + } + // Listing a folder full of them never panics either. + let v = run(&mut s, "macro.list", json!({"folder": dir.display().to_string()})); + assert!(!v["problems"].as_array().unwrap().is_empty()); + // Hostile params, with every folder inside the temporary one. + let folder = dir.display().to_string(); + for p in [ + Value::Null, + json!({"folder": folder}), + json!({"folder": folder, "name": "", "history": [u64::MAX]}), + json!({"folder": folder, "name": "x", "history": "all"}), + json!({"folder": folder, "name": "x", "history": []}), + json!({"folder": folder, "name": "..", "history": [0]}), + json!({"folder": folder, "name": "CON", "history": [0]}), + json!({"folder": folder, "name": "a", "to": "", "index": u64::MAX}), + json!({"folder": "", "name": "a"}), + json!({"steps": {"steps": []}, "name": "\u{0}".repeat(500)}), + json!({"steps": []}), + json!({"path": folder}), + ] { + for c in commands().iter().filter(|c| c.id.starts_with("macro.")) { + let _ = s.execute(c.id, &p); + } + } +} + +#[test] +fn a_step_too_long_to_keep_says_so() { + let mut s = with_rect(10.0); + s.begin_gesture("Scribble"); + for i in 0..(history::MAX_RECORDED + 2) { + // Alternating commands, so they don't add up into one. + let id = if i % 2 == 0 { "element.translate" } else { "modify.rotate_cw" }; + run(&mut s, id, json!({"dx": 1, "dy": 0, "snap": 0})); + } + s.end_gesture(); + let v = run(&mut s, "macro.history", json!({})); + let last = v["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last["keep"], false); + assert!(last["why"].as_str().unwrap().contains("too many"), "{last}"); +} + +#[test] +fn steps_run_inside_a_motion_tween_key_it_as_on_their_own() { + // Each step's edit becomes the tween's keys at the frame it ran at. + let tweened = || { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s + }; + let (mut a, mut b) = (tweened(), tweened()); + a.set_frame(5); + run(&mut a, "edit.select_all", json!({})); + run(&mut a, "element.translate", json!({"dx": 40, "dy": 0})); + b.set_frame(5); + run(&mut b, "edit.select_all", json!({})); + run(&mut b, "macro.run", json!({"steps": [{"cmd": "element.translate", "params": {"dx": 40, "dy": 0}}]})); + assert!(a.doc == b.doc, "a step in a saved command keys the tween as the command does alone"); +} diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index 73944b76..454a95a6 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -179,7 +179,7 @@ fn every_command_namespace_has_a_plugin_policy() { let ns = c.id.split('.').next().unwrap_or(""); let verdict = plugin_may_call(c.id); match ns { - "file" | "plugin" | "control" | "prefs" | "desktop" => assert!(verdict.is_err(), "{} must be refused", c.id), + "file" | "plugin" | "control" | "prefs" | "desktop" | "macro" => assert!(verdict.is_err(), "{} must be refused", c.id), // Publish Settings (ADR 0060): read yes, change no (it says what Publish writes). "publish" => assert_eq!(verdict.is_ok(), c.id == "publish.settings_get", "{}", c.id), // Brushes (ADR 0068): list yes; your own brushes and brush set files no.