M13.1: branching history, puppet pin recording, WebAssembly plug-in API, ScriptUI model and hosts, File ▸ Scripts, deterministic render test
- engine: History keeps undone lines as branches; edit.history.list/goto; History panel tree; MCP history tool - puppet.recordPin / puppet.recordOptions; viewer Cmd-drag records; Record Options form - effects::plugin (EffectPlugin trait, register_plugin, API v1); effectcraft-plugin (wasmi, sandboxed, fuel-limited); effect.plugins.load/list - ScriptUI: engine scriptui model + layout + scriptui.* commands; script crate scriptui.js and script-host threads (dialogs block show()) - File ▸ Scripts: install script / ScriptUI panel, sample scripts, window.scriptPanel - host test: bit-identical renders across runs and thread counts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ebcb8c95ce
commit
89c9b1b6ee
@@ -584,8 +584,7 @@ fn edit_original(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn purge(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.history.undo.clear();
|
||||
s.history.redo.clear();
|
||||
s.history.clear();
|
||||
s.toast("Purged undo history");
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -630,9 +629,60 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("edit.purge", "Purge", [], None, "{what?: all|memoryAndDisk|memory|disk|3d|image|snapshot}", always_ok, purge_caches),
|
||||
crate::query!("cache.diskStats", "Disk Cache Statistics", "{}", disk_stats),
|
||||
cmd!("edit.editOriginal", "Edit Original...", ["Edit"], Some("Cmd+E"), "{}", has_selected_footage, edit_original),
|
||||
crate::query!(
|
||||
"edit.history.list",
|
||||
"History",
|
||||
"{} → {states: [{index, id, label, parent, depth, current, line, future}], current, branches}",
|
||||
history_list
|
||||
),
|
||||
cmd!(
|
||||
"edit.history.goto",
|
||||
"Go to History State",
|
||||
[],
|
||||
None,
|
||||
"{index? (from edit.history.list) | id? | steps? (negative = back along the line)}",
|
||||
always_ok,
|
||||
history_goto
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- History panel
|
||||
|
||||
/// `edit.history.list`: every state of the (branching) undo history.
|
||||
fn history_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let nodes = s.history_tree();
|
||||
let current = nodes.iter().position(|n| n.current);
|
||||
Ok(json!({"states": nodes, "current": current, "branches": s.history.branches.len()}))
|
||||
}
|
||||
|
||||
/// `edit.history.goto`: jump to a state by `index` (from `edit.history.list`), `id`, or
|
||||
/// `steps` along the working line (negative = back, like Undo).
|
||||
fn history_goto(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "edit.history.goto";
|
||||
if let Some(n) = p.get("steps").and_then(Value::as_i64) {
|
||||
for _ in 0..n.unsigned_abs() {
|
||||
let moved = if n < 0 { s.undo() } else { s.redo() };
|
||||
if !moved {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let nodes = s.history_tree();
|
||||
let id = match (p.get("id").and_then(Value::as_str), p.get("index").and_then(Value::as_u64)) {
|
||||
(Some(id), _) => id.to_string(),
|
||||
(None, Some(i)) => nodes.get(i as usize).map(|n| n.id.clone()).ok_or_else(|| super::bad(c, format!("no state {i} (0..{})", nodes.len())))?,
|
||||
_ => return Err(super::bad(c, "give `index`, `id` or `steps`")),
|
||||
};
|
||||
if !s.goto_history(&id) {
|
||||
return Err(super::bad(c, format!("no history state `{id}`")));
|
||||
}
|
||||
}
|
||||
let nodes = s.history_tree();
|
||||
let cur = nodes.iter().find(|n| n.current).cloned();
|
||||
Ok(json!({"current": cur.as_ref().map(|n| n.index), "label": cur.map(|n| n.label)}))
|
||||
}
|
||||
|
||||
fn layers_or_keys(s: &Session) -> std::result::Result<(), String> {
|
||||
if !s.state.selected_keys.is_empty() || !s.state.selected_vertices.is_empty() { super::has_comp(s) } else { has_layers(s) }
|
||||
}
|
||||
|
||||
@@ -7,6 +7,68 @@ use serde_json::{Value, json};
|
||||
use super::{CommandSpec, b_p, bad, has_layers, layer_mut, layers_p, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// `effect.plugins.list`: the registered plug-in effects (WebAssembly or Rust).
|
||||
fn plugins_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
use effectcraft_effects::plugin;
|
||||
let list: Vec<Value> = plugin::plugins()
|
||||
.into_iter()
|
||||
.map(|spec| {
|
||||
let p = plugin::plugin(spec.id);
|
||||
let m = p.as_ref().map(|p| p.manifest().clone());
|
||||
json!({
|
||||
"id": spec.id,
|
||||
"name": spec.name,
|
||||
"category": spec.category,
|
||||
"version": m.as_ref().map(|m| m.version.clone()),
|
||||
"author": m.as_ref().map(|m| m.author.clone()),
|
||||
"description": m.as_ref().map(|m| m.description.clone()),
|
||||
"source": p.map(|p| p.source()),
|
||||
"params": spec.params.iter().map(|p| p.id).collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"api": plugin::PLUGIN_API_VERSION, "wasm": s.plugin_loader.is_some(), "plugins": list}))
|
||||
}
|
||||
|
||||
/// `effect.plugins.load`: load WebAssembly effect plug-ins (a file, or every `.wasm` in a
|
||||
/// folder) through the host's loader ([`Session::plugin_loader`]).
|
||||
fn plugins_load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "effect.plugins.load";
|
||||
let loader = s.plugin_loader.ok_or_else(|| EngineError::Other("WebAssembly effect plug-ins are not available in this build".into()))?;
|
||||
let files: Vec<String> = match (str_p(p, "path"), str_p(p, "folder")) {
|
||||
(Some(path), _) => vec![path.to_string()],
|
||||
(None, Some(dir)) => {
|
||||
let mut v: Vec<String> = std::fs::read_dir(dir)
|
||||
.map_err(|e| bad(c, format!("cannot list {dir}: {e}")))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")))
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
_ => return Err(bad(c, "give `path` or `folder`")),
|
||||
};
|
||||
let (mut loaded, mut errors) = (vec![], vec![]);
|
||||
for f in &files {
|
||||
let r = s.services.read_file(f).map_err(|e| format!("cannot read {f}: {e}")).and_then(|bytes| loader(&bytes, f));
|
||||
match r {
|
||||
Ok(v) => loaded.push(v),
|
||||
Err(e) => errors.push(json!({"path": f, "error": e})),
|
||||
}
|
||||
}
|
||||
if str_p(p, "path").is_some()
|
||||
&& let Some(e) = errors.first()
|
||||
{
|
||||
return Err(EngineError::Other(format!("{}: {}", files[0], e["error"].as_str().unwrap_or("failed"))));
|
||||
}
|
||||
if !loaded.is_empty() {
|
||||
s.toast(format!("Loaded {} effect plug-in(s)", loaded.len()));
|
||||
}
|
||||
Ok(json!({"loaded": loaded, "errors": errors}))
|
||||
}
|
||||
|
||||
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_p(p, "effect").ok_or_else(|| bad("effect.apply", "missing `effect` (id or name)"))?;
|
||||
let spec = effectcraft_effects::lookup(name).ok_or_else(|| bad("effect.apply", format!("unknown effect `{name}`")))?;
|
||||
@@ -284,8 +346,8 @@ fn last(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let filter = str_p(p, "filter").map(str::to_ascii_lowercase);
|
||||
let v: Vec<Value> = effectcraft_effects::registry()
|
||||
.iter()
|
||||
let v: Vec<Value> = effectcraft_effects::all()
|
||||
.into_iter()
|
||||
.filter(|e| filter.as_ref().is_none_or(|f| e.name.to_ascii_lowercase().contains(f) || e.id.contains(f.as_str())))
|
||||
.map(|e| json!({"id": e.id, "name": e.name, "category": e.category, "params": e.params.iter().map(|p| json!({"id": p.id, "name": p.name, "default": p.default.to_json()})).collect::<Vec<_>>()}))
|
||||
.collect();
|
||||
@@ -305,5 +367,20 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("effect.paste", "Paste Effects", [], None, "{layers?} — adds the copied effects to the layers", has_layers, paste),
|
||||
cmd!("effect.reset", "Reset Effect", [], None, "{layer?, effect}", has_layers, reset),
|
||||
crate::query!("effect.list", "List Effects", "{filter?}", list),
|
||||
crate::query!(
|
||||
"effect.plugins.list",
|
||||
"List Effect Plug-ins",
|
||||
"{} → {api, wasm, plugins: [{id, name, category, version, author, source, params}]}",
|
||||
plugins_list
|
||||
),
|
||||
cmd!(
|
||||
"effect.plugins.load",
|
||||
"Load Effect Plug-in...",
|
||||
[],
|
||||
None,
|
||||
"{path (.wasm / .wat plug-in, API v1) | folder (loads every .wasm in it)}",
|
||||
super::always,
|
||||
plugins_load
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -364,6 +364,14 @@ fn collect_files(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// array or JSON lines of `{"command": id, "params": {…}}` (also accepts the control channel's
|
||||
/// `{"method": "engine.execute", "params": {"id", "params"}}`).
|
||||
fn run_script(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// File ▸ Scripts ▸ <installed or sample script>.
|
||||
if let Some(name) = str_p(p, "name")
|
||||
&& p.get("path").is_none()
|
||||
&& p.get("steps").is_none()
|
||||
{
|
||||
let name = name.to_string();
|
||||
return super::scripts::run_named(s, &name);
|
||||
}
|
||||
if let Some(path) = str_p(p, "path")
|
||||
&& p.get("steps").is_none()
|
||||
&& is_js_script(path)
|
||||
@@ -375,13 +383,7 @@ fn run_script(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let code = String::from_utf8_lossy(&bytes).to_string();
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
|
||||
let out = run_js(s, &code, path, false)?;
|
||||
if let Some(e) = out.get("error").filter(|e| !e.is_null()) {
|
||||
let line = e.get("line").and_then(Value::as_u64).map(|l| format!(" (line {l})")).unwrap_or_default();
|
||||
let msg = e.get("message").and_then(Value::as_str).unwrap_or("script error");
|
||||
s.events.push(crate::Event::Toast { message: format!("{name}{line}: {msg}"), error: true });
|
||||
return Err(EngineError::Other(format!("{name}{line}: {msg}")));
|
||||
}
|
||||
return Ok(out);
|
||||
return report_js(s, &name, out);
|
||||
}
|
||||
let steps: Vec<Value> = match (p.get("steps"), str_p(p, "path")) {
|
||||
(Some(Value::Array(a)), _) => a.clone(),
|
||||
@@ -426,6 +428,23 @@ fn is_js_script(path: &str) -> bool {
|
||||
l.ends_with(".jsx") || l.ends_with(".js") || l.ends_with(".jsxbin")
|
||||
}
|
||||
|
||||
/// A script error becomes a toast and a command error.
|
||||
fn report_js(s: &mut Session, name: &str, out: Value) -> Result<Value> {
|
||||
if let Some(e) = out.get("error").filter(|e| !e.is_null()) {
|
||||
let line = e.get("line").and_then(Value::as_u64).map(|l| format!(" (line {l})")).unwrap_or_default();
|
||||
let msg = e.get("message").and_then(Value::as_str).unwrap_or("script error");
|
||||
s.events.push(crate::Event::Toast { message: format!("{name}{line}: {msg}"), error: true });
|
||||
return Err(EngineError::Other(format!("{name}{line}: {msg}")));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Run a script's code under its file name (installed / sample scripts, ScriptUI panels).
|
||||
pub(crate) fn run_js_named(s: &mut Session, code: &str, name: &str) -> Result<Value> {
|
||||
let out = run_js(s, code, name, false)?;
|
||||
report_js(s, name, out)
|
||||
}
|
||||
|
||||
/// Run JavaScript through the session's scripting engine.
|
||||
fn run_js(s: &mut Session, code: &str, name: &str, console: bool) -> Result<Value> {
|
||||
let runner = s.script.ok_or_else(|| EngineError::Other("JavaScript scripting is not available in this build".into()))?;
|
||||
@@ -809,7 +828,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script File...",
|
||||
["File", "Scripts"],
|
||||
None,
|
||||
"{path (.jsx/.js JavaScript, or a .jsonl/.json command script) | steps: [{command, params}]}",
|
||||
"{path (.jsx/.js JavaScript, or a .jsonl/.json command script) | steps: [{command, params}] | name (an installed or sample script, see file.scripts.list)}",
|
||||
always,
|
||||
run_script
|
||||
),
|
||||
|
||||
@@ -40,6 +40,7 @@ mod query;
|
||||
mod render_queue;
|
||||
pub(crate) mod rig3d;
|
||||
pub mod roto_cmds;
|
||||
pub mod scripts;
|
||||
mod settings;
|
||||
mod shape_stroke;
|
||||
mod stubs;
|
||||
@@ -158,6 +159,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(essential::specs());
|
||||
v.extend(expr_tools::specs());
|
||||
v.extend(proxy::specs());
|
||||
v.extend(scripts::specs());
|
||||
v.extend(stubs::specs());
|
||||
v
|
||||
})
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
use effectcraft_effects::puppet::{self, MeshOpts, PinKind};
|
||||
use effectcraft_effects::{Buf, Params};
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_keyframe::{Keyframe, Value as KV};
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{ItemId, LayerId, Node, PropGroup, Uid};
|
||||
use effectcraft_render::{EvalCtx, RenderOpts, Renderer};
|
||||
@@ -309,6 +309,122 @@ fn mesh_opts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Parse recorded samples `[[t, x, y]…]` (t = seconds since the drag began, layer space).
|
||||
fn samples(p: &Value, cmd: &str) -> Result<Vec<(f64, [f64; 2])>> {
|
||||
let arr = p
|
||||
.get("samples")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| bad(cmd, "missing `samples`: [[t, x, y]…] (t = seconds since the drag began, layer space)"))?;
|
||||
let mut rec = Vec::with_capacity(arr.len());
|
||||
for (i, v) in arr.iter().enumerate() {
|
||||
let a: Vec<f64> = v.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
|
||||
if a.len() < 3 || a.iter().any(|x| !x.is_finite()) {
|
||||
return Err(bad(cmd, format!("sample {i}: expected [t, x, y]")));
|
||||
}
|
||||
rec.push((a[0], [a[1], a[2]]));
|
||||
}
|
||||
if rec.is_empty() {
|
||||
return Err(bad(cmd, "need at least one sample"));
|
||||
}
|
||||
rec.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
Ok(rec)
|
||||
}
|
||||
|
||||
/// Puppet tool Record mode (⌘/Ctrl-drag a pin): the pin's drag, sampled in real time, becomes
|
||||
/// Position keyframes at the comp frame rate from the current time on, replacing the keys in
|
||||
/// the recorded span. Record Options: `speed` (%: 100 plays back at the speed of the drag,
|
||||
/// 200 twice as slow) and `smoothing` (removes extraneous keys like the Smoother; 0 = a key
|
||||
/// on every frame). The current time stays where recording began.
|
||||
fn record_pin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "puppet.recordPin";
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
let key = p.get("pin").cloned().ok_or_else(|| bad(cmd, "missing `pin` (uid or name)"))?;
|
||||
let uid = pin_uid(s, cid, lid, &key, cmd)?;
|
||||
let rec = samples(p, cmd)?;
|
||||
let opts = &s.state.puppet;
|
||||
let speed = f_p(p, "speed").unwrap_or(opts.record_speed).clamp(1.0, 10_000.0) / 100.0;
|
||||
// Smoothing 10 (the default) keeps the path within 1 layer pixel of the drag.
|
||||
let smoothing = f_p(p, "smoothing").unwrap_or(opts.record_smoothing).max(0.0) / 10.0;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let fr = comp.frame_rate;
|
||||
let fd = fr.frame_duration().seconds();
|
||||
let start = match p.get("start").and_then(Value::as_f64) {
|
||||
Some(t) => fr.snap_nearest(Tick::from_seconds_f64(t)),
|
||||
None => s.time_of(cid),
|
||||
};
|
||||
let f0 = fr.frame_at(start);
|
||||
let end_frame = fr.frame_at(comp.duration - comp.frame_duration());
|
||||
let t_rec0 = rec[0].0;
|
||||
let span = (rec[rec.len() - 1].0 - t_rec0) * speed;
|
||||
let nframes = (span / fd).round().max(0.0) as i64;
|
||||
let at = |secs: f64| {
|
||||
let i = rec.partition_point(|r| r.0 <= secs).clamp(1, rec.len().max(2) - 1);
|
||||
if rec.len() == 1 {
|
||||
return rec[0].1;
|
||||
}
|
||||
let (a, b) = (rec[i - 1], rec[i]);
|
||||
let f = if b.0 > a.0 { ((secs - a.0) / (b.0 - a.0)).clamp(0.0, 1.0) } else { 1.0 };
|
||||
[a.1[0] + (b.1[0] - a.1[0]) * f, a.1[1] + (b.1[1] - a.1[1]) * f]
|
||||
};
|
||||
let n = s.edit("Record Puppet Pin", None, |proj, st| {
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let lc = l.clone();
|
||||
let g = l.props.find_group_mut(uid).ok_or_else(|| bad(cmd, "pin gone"))?;
|
||||
let kind = PinKind::from_index(g.get("kind").map(|k| k.value.as_enum()).unwrap_or(0));
|
||||
if !kind.moves() {
|
||||
return Err(bad(cmd, "only Position and Advanced pins record motion"));
|
||||
}
|
||||
let pos = g.get_mut("position").ok_or_else(|| bad(cmd, "the pin has no Position"))?;
|
||||
let mut new: Vec<Keyframe> = vec![];
|
||||
for k in 0..=nframes {
|
||||
let f = f0 + k;
|
||||
if f > end_frame {
|
||||
break;
|
||||
}
|
||||
let q = at(t_rec0 + k as f64 * fd / speed);
|
||||
new.push(Keyframe::new(lc.layer_time(fr.tick_of(f)), KV::Vec2(q)));
|
||||
}
|
||||
let (Some(t0), Some(t1)) = (new.first().map(|k| k.time), new.last().map(|k| k.time)) else { return Ok(0) };
|
||||
let mut keys: Vec<Keyframe> = pos.keys.iter().filter(|k| k.time < t0 || k.time > t1).cloned().collect();
|
||||
keys.extend(new);
|
||||
keys.sort_by_key(|k| k.time);
|
||||
let (a, b) = (keys.iter().position(|k| k.time == t0).unwrap_or(0), keys.iter().position(|k| k.time == t1).unwrap_or(0));
|
||||
if smoothing > 0.0 && b > a + 1 {
|
||||
let samples: Vec<(Tick, Vec<f64>)> = keys[a..=b].iter().map(|k| (k.time, k.value.components())).collect();
|
||||
keys = super::anim_tools::smooth_keys(&keys, a, b, &samples, smoothing, true);
|
||||
}
|
||||
pos.keys = keys;
|
||||
pos.value = KV::Vec2(rec[0].1);
|
||||
let puid = pos.uid;
|
||||
st.selected_props = vec![(lid, uid)];
|
||||
st.selected_keys = pos.keys.iter().filter(|k| k.time >= t0 && k.time <= t1).map(|k| crate::KeyRef { layer: lid, prop: puid, time: k.time }).collect();
|
||||
Ok(st.selected_keys.len())
|
||||
})?;
|
||||
// The current time returns to where recording began.
|
||||
s.state.times.insert(cid, start);
|
||||
let end = fr.tick_of((f0 + nframes).min(end_frame));
|
||||
Ok(json!({"keys": n, "start": start.seconds(), "end": end.seconds(), "frames": nframes + 1}))
|
||||
}
|
||||
|
||||
/// Record Options (the Puppet tool's Record Options… dialog): `speed`, `smoothing`,
|
||||
/// `useDraftDeformation`, `showMesh`. Returns the options.
|
||||
fn record_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let o = &mut s.state.puppet;
|
||||
if let Some(v) = f_p(p, "speed") {
|
||||
o.record_speed = v.clamp(1.0, 10_000.0);
|
||||
}
|
||||
if let Some(v) = f_p(p, "smoothing") {
|
||||
o.record_smoothing = v.clamp(0.0, 100.0);
|
||||
}
|
||||
if let Some(v) = p.get("useDraftDeformation").and_then(Value::as_bool) {
|
||||
o.record_draft = v;
|
||||
}
|
||||
if let Some(v) = p.get("showMesh").and_then(Value::as_bool) {
|
||||
o.record_show_mesh = v;
|
||||
}
|
||||
Ok(json!({"speed": o.record_speed, "smoothing": o.record_smoothing, "useDraftDeformation": o.record_draft, "showMesh": o.record_show_mesh}))
|
||||
}
|
||||
|
||||
/// Meshes, pins and the deformed mesh at the current time (layer space).
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid) = layer_p(s, p, "puppet.info")?;
|
||||
@@ -364,6 +480,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
mesh_opts
|
||||
),
|
||||
crate::query!("puppet.info", "Puppet Mesh Info", "{layer?, time? | frame?}", info),
|
||||
cmd!(
|
||||
"puppet.recordPin",
|
||||
"Record Puppet Pin",
|
||||
[],
|
||||
None,
|
||||
"{layer?, pin: uid | name, samples: [[t, x, y]…] (t = seconds since the drag began, layer space), start? (s, default current time), speed? (%, Record Options), smoothing? (Record Options)}",
|
||||
has_comp,
|
||||
record_pin
|
||||
),
|
||||
cmd!(
|
||||
"puppet.recordOptions",
|
||||
"Record Options...",
|
||||
[],
|
||||
None,
|
||||
"{speed? (%, 100), smoothing? (0-100), useDraftDeformation?, showMesh?}",
|
||||
super::always,
|
||||
record_options
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -376,11 +510,30 @@ pub struct PuppetOptions {
|
||||
pub triangles: f64,
|
||||
/// Show the mesh in the viewer.
|
||||
pub show_mesh: bool,
|
||||
/// Record Options ▸ Speed (%): 100 plays a recording back at the speed of the drag.
|
||||
pub record_speed: f64,
|
||||
/// Record Options ▸ Smoothing: removes extraneous keys from recorded motion (0 = a key per
|
||||
/// frame).
|
||||
pub record_smoothing: f64,
|
||||
/// Record Options ▸ Use Draft Deformation: the viewer shows the draft (unexpanded) mesh
|
||||
/// while recording.
|
||||
pub record_draft: bool,
|
||||
/// Record Options ▸ Show Mesh while recording.
|
||||
pub record_show_mesh: bool,
|
||||
}
|
||||
|
||||
impl Default for PuppetOptions {
|
||||
fn default() -> Self {
|
||||
let d = MeshOpts::default();
|
||||
PuppetOptions { density: d.density, expansion: d.expansion, triangles: d.triangles, show_mesh: false }
|
||||
PuppetOptions {
|
||||
density: d.density,
|
||||
expansion: d.expansion,
|
||||
triangles: d.triangles,
|
||||
show_mesh: false,
|
||||
record_speed: 100.0,
|
||||
record_smoothing: 10.0,
|
||||
record_draft: false,
|
||||
record_show_mesh: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
//! File ▸ Scripts and ScriptUI.
|
||||
//!
|
||||
//! * **Installed scripts** live in the settings store under `Scripts/` (File ▸ Scripts ▸ Install
|
||||
//! Script File…) and `Scripts/ScriptUI Panels/` (Install ScriptUI Panel…), next to the
|
||||
//! settings on the desktop, so dropping `.jsx` files in those folders works too. File ▸ Scripts
|
||||
//! lists them with the bundled sample scripts ([`SAMPLES`]) and runs them by name; ScriptUI
|
||||
//! panels appear at the bottom of the Window menu and open as dockable panels
|
||||
//! (`window.scriptPanel`), running with `this` = the panel as in After Effects.
|
||||
//! * **ScriptUI windows** (`scriptui.*`): list the open script windows, read their control
|
||||
//! trees, click buttons and set values like a user, close them (see [`crate::scriptui`]).
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, bad, str_p};
|
||||
use crate::{EngineError, Event, Result, Session, cmd, scriptui};
|
||||
|
||||
/// The settings-store folders of installed scripts.
|
||||
pub const SCRIPTS_DIR: &str = "Scripts";
|
||||
pub const PANELS_DIR: &str = "Scripts/ScriptUI Panels";
|
||||
|
||||
/// Sample scripts that ship with EffectCraft (original work): (file name, ScriptUI panel, code).
|
||||
pub const SAMPLES: &[(&str, bool, &str)] = &[
|
||||
("Create Null at Selected Layers.jsx", false, include_str!("../../scripts/Create Null at Selected Layers.jsx")),
|
||||
("Rename Layers.jsx", false, include_str!("../../scripts/Rename Layers.jsx")),
|
||||
("Render Queue Batch.jsx", false, include_str!("../../scripts/Render Queue Batch.jsx")),
|
||||
("Sort Layers by In Point.jsx", false, include_str!("../../scripts/Sort Layers by In Point.jsx")),
|
||||
("Layer Tools.jsx", true, include_str!("../../scripts/ScriptUI Panels/Layer Tools.jsx")),
|
||||
];
|
||||
|
||||
/// A script File ▸ Scripts (or the Window menu, for panels) offers.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct ScriptEntry {
|
||||
/// File name (`Rename Layers.jsx`): what the menus show and commands take.
|
||||
pub name: String,
|
||||
/// In the ScriptUI Panels folder: opens as a dockable panel.
|
||||
pub panel: bool,
|
||||
/// `installed` or `sample`.
|
||||
pub source: &'static str,
|
||||
}
|
||||
|
||||
fn is_script(name: &str) -> bool {
|
||||
let l = name.to_ascii_lowercase();
|
||||
l.ends_with(".jsx") || l.ends_with(".js")
|
||||
}
|
||||
|
||||
/// Installed scripts and panels, then the samples not shadowed by an installed one, by name.
|
||||
pub fn scripts(s: &Session) -> Vec<ScriptEntry> {
|
||||
let mut v: Vec<ScriptEntry> = vec![];
|
||||
if let Some(cfg) = &s.config {
|
||||
for (dir, panel) in [(SCRIPTS_DIR, false), (PANELS_DIR, true)] {
|
||||
for n in cfg.list(dir).into_iter().filter(|n| is_script(n)) {
|
||||
v.push(ScriptEntry { name: n, panel, source: "installed" });
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, panel, _) in SAMPLES {
|
||||
if !v.iter().any(|e| e.name == *name && e.panel == *panel) {
|
||||
v.push(ScriptEntry { name: name.to_string(), panel: *panel, source: "sample" });
|
||||
}
|
||||
}
|
||||
v.sort_by(|a, b| a.panel.cmp(&b.panel).then(a.name.to_lowercase().cmp(&b.name.to_lowercase())));
|
||||
v
|
||||
}
|
||||
|
||||
/// The code of an installed or sample script / panel.
|
||||
pub fn script_code(s: &Session, name: &str, panel: Option<bool>) -> Option<(bool, String)> {
|
||||
if let Some(cfg) = &s.config {
|
||||
for (dir, is_panel) in [(SCRIPTS_DIR, false), (PANELS_DIR, true)] {
|
||||
if panel.is_some_and(|p| p != is_panel) {
|
||||
continue;
|
||||
}
|
||||
if let Some(code) = cfg.read(&format!("{dir}/{name}")) {
|
||||
return Some((is_panel, code));
|
||||
}
|
||||
}
|
||||
}
|
||||
SAMPLES.iter().find(|(n, p, _)| *n == name && panel.is_none_or(|w| w == *p)).map(|(_, p, c)| (*p, c.to_string()))
|
||||
}
|
||||
|
||||
fn install(s: &mut Session, p: &Value, panel: bool) -> Result<Value> {
|
||||
let c = if panel { "file.installScriptUIPanel" } else { "file.installScript" };
|
||||
let path = str_p(p, "path").ok_or_else(|| bad(c, "missing `path` (a .jsx / .js script)"))?;
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
if !is_script(&name) {
|
||||
return Err(bad(c, "scripts are .jsx or .js files (.jsxbin is not supported)"));
|
||||
}
|
||||
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
let code = String::from_utf8(bytes).map_err(|_| bad(c, "the script is not UTF-8 text"))?;
|
||||
let cfg = s.config.clone().ok_or_else(|| EngineError::Other("this session has no settings folder to install scripts into".into()))?;
|
||||
let dir = if panel { PANELS_DIR } else { SCRIPTS_DIR };
|
||||
cfg.write(&format!("{dir}/{name}"), &code).map_err(|e| EngineError::Other(format!("cannot install {name}: {e}")))?;
|
||||
// After Effects asks for a restart; our menus pick it up at once.
|
||||
s.toast(if panel {
|
||||
format!("Installed ScriptUI panel {name}: find it at the bottom of the Window menu")
|
||||
} else {
|
||||
format!("Installed script {name}: find it in File ▸ Scripts")
|
||||
});
|
||||
Ok(json!({"name": name, "panel": panel}))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!(scripts(s)))
|
||||
}
|
||||
|
||||
fn uninstall(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "file.uninstallScript";
|
||||
let name = str_p(p, "name").ok_or_else(|| bad(c, "missing `name`"))?;
|
||||
let cfg = s.config.clone().ok_or_else(|| bad(c, "no settings folder"))?;
|
||||
let mut removed = false;
|
||||
for dir in [SCRIPTS_DIR, PANELS_DIR] {
|
||||
let key = format!("{dir}/{name}");
|
||||
if cfg.read(&key).is_some() {
|
||||
cfg.remove(&key).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
removed = true;
|
||||
}
|
||||
}
|
||||
if removed { Ok(json!({"removed": name})) } else { Err(bad(c, format!("`{name}` is not installed"))) }
|
||||
}
|
||||
|
||||
/// Run an installed or sample script by name (File ▸ Scripts ▸ <name>). A ScriptUI panel run
|
||||
/// this way gets `this` = a floating palette-like panel window.
|
||||
pub(crate) fn run_named(s: &mut Session, name: &str) -> Result<Value> {
|
||||
let (panel, code) = script_code(s, name, None).ok_or_else(|| bad("file.runScript", format!("no installed or sample script `{name}`")))?;
|
||||
if panel {
|
||||
return open_panel(s, &json!({"name": name}));
|
||||
}
|
||||
super::file_more::run_js_named(s, &code, name)
|
||||
}
|
||||
|
||||
/// The code a ScriptUI panel runs with: `this` is a dockable Panel titled after the script.
|
||||
pub fn panel_wrapper(title: &str, code: &str) -> String {
|
||||
// On one line, so line numbers in errors stay those of the file.
|
||||
format!("(function () {{ {code}\n}}).call(__uiDockPanel({}));", Value::String(title.to_string()))
|
||||
}
|
||||
|
||||
/// Window ▸ <ScriptUI panel>: run the panel script (or bring its panel forward).
|
||||
fn open_panel(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "window.scriptPanel";
|
||||
let name = str_p(p, "name").ok_or_else(|| bad(c, "missing `name` (a script in the ScriptUI Panels folder)"))?.to_string();
|
||||
let title = name.trim_end_matches(".jsx").trim_end_matches(".js").to_string();
|
||||
if let Some(w) = s.script_ui.windows.iter().find(|w| w.kind == scriptui::WindowKind::Panel && w.script == name) {
|
||||
let id = w.id;
|
||||
s.events.push(Event::Frontend { command: c.into(), params: json!({"window": id}) });
|
||||
return Ok(json!({"window": id, "open": true}));
|
||||
}
|
||||
let (_, code) = script_code(s, &name, Some(true)).or_else(|| script_code(s, &name, None)).ok_or_else(|| bad(c, format!("no ScriptUI panel `{name}`")))?;
|
||||
let out = super::file_more::run_js_named(s, &panel_wrapper(&title, &code), &name)?;
|
||||
let id = s.script_ui.windows.iter().rev().find(|w| w.kind == scriptui::WindowKind::Panel && w.script == name).map(|w| w.id);
|
||||
if let Some(id) = id {
|
||||
s.events.push(Event::Frontend { command: c.into(), params: json!({"window": id}) });
|
||||
}
|
||||
Ok(json!({"window": id, "result": out}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"file.installScript",
|
||||
"Install Script File...",
|
||||
["File", "Scripts"],
|
||||
None,
|
||||
"{path (.jsx / .js)} → copies it to the Scripts folder; it appears in File ▸ Scripts",
|
||||
always,
|
||||
|s, p| install(s, p, false)
|
||||
),
|
||||
cmd!(
|
||||
"file.installScriptUIPanel",
|
||||
"Install ScriptUI Panel...",
|
||||
["File", "Scripts"],
|
||||
None,
|
||||
"{path (.jsx / .js)} → copies it to the ScriptUI Panels folder; it appears in the Window menu",
|
||||
always,
|
||||
|s, p| install(s, p, true)
|
||||
),
|
||||
cmd!("file.uninstallScript", "Uninstall Script", [], None, "{name}", always, uninstall),
|
||||
crate::query!("file.scripts.list", "List Scripts", "{} → [{name, panel, source: installed|sample}]", list),
|
||||
cmd!(
|
||||
"window.scriptPanel",
|
||||
"ScriptUI Panel",
|
||||
[],
|
||||
None,
|
||||
"{name (a script in the ScriptUI Panels folder, e.g. `Layer Tools.jsx`)} → opens it as a dockable panel",
|
||||
always,
|
||||
open_panel
|
||||
),
|
||||
crate::query!("scriptui.list", "List Script Windows", "{} → [{window, title, kind: dialog|palette|window|panel, script, modal, size}]", scriptui::list),
|
||||
crate::query!(
|
||||
"scriptui.get",
|
||||
"Script Window Controls",
|
||||
"{window?: id | title} → {id, title, kind, root: {id, type, name, text, value, checked, items, selection, bounds, enabled, children…}}",
|
||||
scriptui::get
|
||||
),
|
||||
cmd!(
|
||||
"scriptui.click",
|
||||
"Click Script Window Control",
|
||||
[],
|
||||
None,
|
||||
"{window?: id | title, widget: id | \"#id\" | properties.name | text} (buttons, checkboxes, radio buttons, tabs)",
|
||||
always,
|
||||
scriptui::click
|
||||
),
|
||||
cmd!(
|
||||
"scriptui.set",
|
||||
"Set Script Window Control",
|
||||
[],
|
||||
None,
|
||||
"{window?, widget, value: text | number | bool | item index | item text} (edit text, sliders, checkboxes, lists) → fires onChanging / onChange",
|
||||
always,
|
||||
scriptui::set
|
||||
),
|
||||
cmd!(
|
||||
"scriptui.close",
|
||||
"Close Script Window",
|
||||
[],
|
||||
None,
|
||||
"{window?, result? (a dialog's show() returns it; default 2 = Cancel)}",
|
||||
always,
|
||||
scriptui::close
|
||||
),
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user