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:
Brandon Thomas
2026-10-03 04:07:20 -04:00
co-authored by Claude Opus 5.5
parent ebcb8c95ce
commit 89c9b1b6ee
48 changed files with 4440 additions and 134 deletions
+14 -1
View File
@@ -30,6 +30,14 @@
//! * **Security**: scripts can import/open/save projects and render, but `File` reads are limited
//! to the project's folder and writes (and the network) are off unless Preferences ▸ Scripting
//! & Expressions ▸ Allow Scripts to Write Files and Access Network is on.
//! * **ScriptUI** (`scriptui.js`, `ui.rs`): `Window` (dialog / palette / window), `Panel`,
//! `Group`, `Button`, `StaticText`, `EditText`, `Checkbox`, `RadioButton`, `Slider`,
//! `Progressbar`, `DropDownList`, `ListBox`, `TabbedPanel`/`Tab`, with `add()`, `orientation`,
//! `alignChildren`, `alignment`, `margins`, `spacing`, `preferredSize`, `onClick` /
//! `onChange` / `onChanging` / `onClose`, `show()` / `close()` and `layout.layout()`. Windows
//! are published to [`Session::script_ui`](effectcraft_engine::Session::script_ui) for
//! frontends and agents (`scriptui.*` commands); modal dialogs block `show()` until they close.
//! Scripts in the ScriptUI Panels folder run with `this` = a dockable `Panel`.
//!
//! Entry points: [`install`] sets [`Session::script`](effectcraft_engine::Session::script), which
//! the `script.run` command, File ▸ Scripts ▸ Run Script File… (`.jsx`/`.js`), the Script Console
@@ -40,19 +48,22 @@
pub mod matchnames;
mod model;
mod runtime;
mod ui;
use effectcraft_engine::{ScriptRequest, Session};
pub use runtime::{Outcome, ScriptError, run};
pub use ui::dispatch_ui;
/// The [`effectcraft_engine::ScriptRunner`] this crate provides.
pub fn runner(s: &mut Session, req: &ScriptRequest) -> serde_json::Value {
run(s, req).to_json()
}
/// Enable scripting on a session.
/// Enable scripting (and ScriptUI) on a session.
pub fn install(s: &mut Session) {
s.script = Some(runner);
s.script_ui.dispatch = Some(dispatch_ui);
}
/// Run `code` as a one-off script named `name`.
@@ -62,3 +73,5 @@ pub fn run_code(s: &mut Session, code: &str, name: &str) -> Outcome {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_ui;
+2 -2
View File
@@ -59,8 +59,8 @@ pub fn query(s: &mut Session, kind: &str, a: &J) -> R {
}
"labels" => Ok(json!(Label::ALL.iter().map(|l| l.name()).collect::<Vec<_>>())),
"effects" => Ok(json!(
effectcraft_engine::effects::registry()
.iter()
effectcraft_engine::effects::all()
.into_iter()
.map(|e| json!({"id": e.id, "name": e.name, "matchName": matchnames::effect(e.id), "category": e.category}))
.collect::<Vec<_>>()
)),
+113 -57
View File
@@ -26,6 +26,9 @@ pub struct Outcome {
/// `writeLn` / `$.writeln` / `alert` output, one entry per line.
pub output: Vec<String>,
pub error: Option<ScriptError>,
/// The script is waiting in a modal ScriptUI dialog's `show()` (it goes on when the dialog
/// closes; see [`crate::dispatch_ui`]).
pub waiting: bool,
}
/// An uncaught script error.
@@ -42,36 +45,49 @@ impl Outcome {
self.error.is_none()
}
pub fn to_json(&self) -> J {
json!({
let mut j = json!({
"ok": self.ok(),
"result": self.result,
"output": self.output.join("\n"),
"error": self.error.as_ref().map(|e| json!({"message": e.message, "line": e.line, "column": e.column, "file": e.file})),
})
});
if self.waiting {
j["waiting"] = json!(true);
}
j
}
}
/// The session and per-run state while a script runs (the natives reach it here; nothing
/// borrowed ever enters the JS heap).
struct Active {
session: Session,
output: Vec<String>,
pub(crate) struct Active {
pub(crate) session: Session,
pub(crate) output: Vec<String>,
/// Open undo groups: (name, project snapshot when the outermost group began).
groups: Vec<(String, Arc<Project>)>,
pub(crate) groups: Vec<(String, Arc<Project>)>,
/// `app.scheduleTask` queue: (id, code, repeat).
tasks: Vec<(u32, String, bool)>,
next_task: u32,
name: String,
pub(crate) tasks: Vec<(u32, String, bool)>,
pub(crate) next_task: u32,
pub(crate) name: String,
/// Running on a script-host thread: modal dialogs hand the session back to the caller
/// through this link while they wait.
pub(crate) link: Option<crate::ui::Link>,
}
impl Active {
pub(crate) fn new(session: Session, name: &str) -> Active {
Active { session, output: vec![], groups: vec![], tasks: vec![], next_task: 0, name: name.to_string(), link: None }
}
}
thread_local! {
static ACTIVE: RefCell<Option<Active>> = const { RefCell::new(None) };
pub(crate) static ACTIVE: RefCell<Option<Active>> = const { RefCell::new(None) };
/// The Script Console's persistent context (never dropped, like the expression runtime: boa's
/// own thread-local heap may be torn down first at thread exit).
static CONSOLE: RefCell<Option<ManuallyDrop<Context>>> = const { RefCell::new(None) };
pub(crate) static CONSOLE: RefCell<Option<ManuallyDrop<Context>>> = const { RefCell::new(None) };
}
fn with_active<T>(f: impl FnOnce(&mut Active) -> Result<T, String>) -> Result<T, String> {
pub(crate) fn with_active<T>(f: impl FnOnce(&mut Active) -> Result<T, String>) -> Result<T, String> {
ACTIVE.with(|a| match a.try_borrow_mut() {
Ok(mut g) => match g.as_mut() {
Some(act) => f(act),
@@ -81,11 +97,11 @@ fn with_active<T>(f: impl FnOnce(&mut Active) -> Result<T, String>) -> Result<T,
})
}
fn throw(msg: impl Into<String>) -> boa_engine::JsError {
pub(crate) fn throw(msg: impl Into<String>) -> boa_engine::JsError {
JsNativeError::error().with_message(msg.into()).into()
}
fn arg_string(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<String> {
pub(crate) fn arg_string(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<String> {
Ok(args.get(i).cloned().unwrap_or_default().to_string(ctx)?.to_std_string_escaped())
}
@@ -97,7 +113,7 @@ fn arg_json(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<J> {
serde_json::from_str(&s).map_err(|e| throw(format!("bad parameters: {e}")))
}
fn js_str(s: &str) -> JsValue {
pub(crate) fn js_str(s: &str) -> JsValue {
JsValue::from(JsString::from(s))
}
@@ -205,7 +221,7 @@ fn native_undo(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsV
}
/// Fold the undo steps recorded since the project was `snap` into one step called `name`.
fn collapse(s: &mut Session, name: &str, snap: &Arc<Project>) {
pub(crate) fn collapse(s: &mut Session, name: &str, snap: &Arc<Project>) {
let h = &mut s.history;
let Some(start) = h.undo.iter().rposition(|(_, p)| Arc::ptr_eq(p, snap)) else {
// Nothing was recorded (or history was reset by New / Open Project).
@@ -349,28 +365,32 @@ fn native_file(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsV
}
}
fn new_context() -> Result<Context, String> {
pub(crate) fn new_context() -> Result<Context, String> {
let mut ctx = Context::default();
let limits = ctx.runtime_limits_mut();
limits.set_loop_iteration_limit(200_000_000);
limits.set_recursion_limit(2000);
let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>); 6] = [
let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>); 9] = [
(js_string!("__exec"), 2, native_exec),
(js_string!("__query"), 2, native_query),
(js_string!("__print"), 1, native_print),
(js_string!("__undo"), 2, native_undo),
(js_string!("__task"), 3, native_task),
(js_string!("__file"), 3, native_file),
(js_string!("__uiNewId"), 0, crate::ui::native_new_id),
(js_string!("__uiModal"), 1, crate::ui::native_modal),
(js_string!("__uiLayoutNative"), 1, crate::ui::native_layout),
];
for (name, len, f) in natives {
ctx.register_global_callable(name, len, NativeFunction::from_fn_ptr(f)).map_err(|e| e.to_string())?;
}
ctx.eval(Source::from_bytes(PRELUDE)).map_err(|e| format!("script prelude: {e}"))?;
ctx.eval(Source::from_bytes(crate::ui::SCRIPTUI)).map_err(|e| format!("ScriptUI prelude: {e}"))?;
Ok(ctx)
}
/// Turn a boa error into a message with line and column (`code` is the user's script).
fn script_error(e: &boa_engine::JsError, ctx: &mut Context, file: &str, code: &str) -> ScriptError {
pub(crate) fn script_error(e: &boa_engine::JsError, ctx: &mut Context, file: &str, code: &str) -> ScriptError {
// Thrown values: `throw new Error("x")`, `throw "x"`, native errors.
let display = e.to_string();
let message = match e.as_opaque() {
@@ -442,7 +462,7 @@ fn position(msg: &str, file: &str, code: &str) -> (Option<u32>, Option<u32>) {
}
/// Evaluate `code` in `ctx` and convert the result.
fn eval_in(ctx: &mut Context, code: &str, file: &str) -> Result<J, ScriptError> {
pub(crate) fn eval_in(ctx: &mut Context, code: &str, file: &str) -> Result<J, ScriptError> {
let src = Source::from_bytes(code.as_bytes()).with_path(std::path::Path::new(file));
let script = boa_engine::Script::parse(src, None, ctx).map_err(|e| script_error(&e, ctx, file, code))?;
let v = script.evaluate(ctx).map_err(|e| script_error(&e, ctx, file, code))?;
@@ -466,8 +486,8 @@ fn result_json(v: &JsValue, ctx: &mut Context) -> J {
}
/// Restores the caller's session when a run ends (on every exit path).
struct Restore<'a> {
target: &'a mut Session,
pub(crate) struct Restore<'a> {
pub(crate) target: &'a mut Session,
}
impl Drop for Restore<'_> {
@@ -478,8 +498,54 @@ impl Drop for Restore<'_> {
}
}
/// End of a script step: close undo groups left open, drop selections that no longer exist,
/// and take the output so far.
pub(crate) fn settle() -> Vec<String> {
with_active(|a| {
if let Some((name, snap)) = a.groups.first().cloned() {
collapse(&mut a.session, &name, &snap);
a.groups.clear();
}
a.session.sanitize_state();
Ok(std::mem::take(&mut a.output))
})
.unwrap_or_default()
}
/// Evaluate a script file's code, then the one-shot tasks it scheduled (`app.scheduleTask`).
pub(crate) fn eval_with_tasks(ctx: &mut Context, code: &str, file: &str) -> Result<J, ScriptError> {
let mut r = eval_in(ctx, code, file);
let tasks = with_active(|a| Ok(std::mem::take(&mut a.tasks))).unwrap_or_default();
for (_, code, repeat) in tasks {
if repeat {
continue;
}
if let Err(e) = eval_in(ctx, &code, "scheduled task")
&& r.is_ok()
{
r = Err(e);
}
}
r
}
pub(crate) fn outcome(output: Vec<String>, result: Result<J, ScriptError>) -> Outcome {
let mut out = Outcome { output, ..Default::default() };
match result {
Ok(v) => out.result = v,
Err(e) => out.error = Some(e),
}
out
}
/// Run a script against `session`: the object model sees and edits that session through engine
/// commands. Script errors come back in [`Outcome::error`].
///
/// On native builds a script file runs on its own script-host thread, so a ScriptUI dialog's
/// `show()` can wait for the user (the session comes back here meanwhile, and the dialog's
/// events reach the host through [`crate::dispatch_ui`]); palettes and panels keep their host
/// alive for their handlers. The Script Console (and the web build) run inline, where dialogs
/// don't block.
pub fn run(session: &mut Session, req: &ScriptRequest) -> Outcome {
let running = ACTIVE.with(|a| a.try_borrow().map(|g| g.is_some()).unwrap_or(true));
if running {
@@ -488,59 +554,49 @@ pub fn run(session: &mut Session, req: &ScriptRequest) -> Outcome {
..Default::default()
};
}
#[cfg(not(target_arch = "wasm32"))]
if !req.console {
return crate::ui::run_threaded(session, req);
}
run_inline(session, req)
}
/// Run on this thread (the Script Console's persistent context, or a fresh one).
pub(crate) fn run_inline(session: &mut Session, req: &ScriptRequest) -> Outcome {
let host = if req.console { crate::ui::CONSOLE_HOST } else { crate::ui::new_host_id() };
let s = std::mem::take(session);
ACTIVE.with(|a| *a.borrow_mut() = Some(Active { session: s, output: vec![], groups: vec![], tasks: vec![], next_task: 0, name: req.name.to_string() }));
ACTIVE.with(|a| *a.borrow_mut() = Some(Active::new(s, req.name)));
let guard = Restore { target: session };
let file = if req.name.is_empty() { "script" } else { req.name };
let mut result = if req.console {
let (result, windows) = if req.console {
CONSOLE.with(|c| {
let mut c = c.borrow_mut();
if c.is_none() {
match new_context() {
Ok(ctx) => *c = Some(ManuallyDrop::new(ctx)),
Err(e) => return Err(ScriptError { message: e, file: file.into(), ..Default::default() }),
Err(e) => return (Err(ScriptError { message: e, file: file.into(), ..Default::default() }), vec![]),
}
}
let ctx = c.as_mut().map(|m| &mut **m).expect("console context");
eval_in(ctx, req.code, file)
let r = eval_in(ctx, req.code, file);
(r, crate::ui::snapshot(ctx))
})
} else {
match new_context() {
Ok(mut ctx) => {
let r = eval_in(&mut ctx, req.code, file);
// app.scheduleTask: run the queued one-shot tasks after the script, in order.
let tasks = with_active(|a| Ok(std::mem::take(&mut a.tasks))).unwrap_or_default();
let mut r = r;
for (_, code, repeat) in tasks {
if repeat {
continue;
}
if let Err(e) = eval_in(&mut ctx, &code, "scheduled task")
&& r.is_ok()
{
r = Err(e);
}
let r = eval_with_tasks(&mut ctx, req.code, file);
let windows = crate::ui::snapshot(&mut ctx);
if windows.iter().any(|w| w.visible) {
// Palettes and panels outlive the run: keep their context for the handlers.
crate::ui::keep_inline(host, ctx);
}
r
(r, windows)
}
Err(e) => Err(ScriptError { message: e, file: file.into(), ..Default::default() }),
Err(e) => (Err(ScriptError { message: e, file: file.into(), ..Default::default() }), vec![]),
}
};
// Close undo groups left open; drop selections that no longer exist.
let output = with_active(|a| {
if let Some((name, snap)) = a.groups.first().cloned() {
collapse(&mut a.session, &name, &snap);
a.groups.clear();
}
a.session.sanitize_state();
Ok(std::mem::take(&mut a.output))
})
.unwrap_or_default();
let output = settle();
drop(guard);
let mut out = Outcome { output, ..Default::default() };
match result.as_mut() {
Ok(v) => out.result = std::mem::take(v),
Err(e) => out.error = Some(e.clone()),
}
out
crate::ui::publish(session, host, req.name, windows);
outcome(output, result)
}
+544
View File
@@ -0,0 +1,544 @@
// EffectCraft scripting: ScriptUI, the dialog / panel object model After Effects scripts use
// (`new Window("dialog", "Title")`, `win.add("button", undefined, "OK")`, `onClick`, `show()`…).
//
// Written from the behaviour Adobe's public JavaScript Tools Guide documents. Controls are plain
// JavaScript objects; after each script step the host reads `__uiSnapshot()` (a JSON
// description of the open windows) and lays them out, frontends draw them, and user actions come
// back through `__uiDispatch(window, control, kind, valueJson)`. Modal dialogs block in
// `show()` (`__uiModal`) until they close, as in After Effects.
var __uiWins = [];
// show() results of closed dialogs, by window id.
var __uiResults = {};
function __uiModalResult(id) {
var r = __uiResults[id];
if (r !== undefined) {
delete __uiResults[id];
return r;
}
return __uiWin(id) ? null : 2;
}
function __dim(w, h) {
var d = [w, h];
Object.defineProperty(d, "width", { get: function () { return this[0]; }, set: function (v) { this[0] = v; } });
Object.defineProperty(d, "height", { get: function () { return this[1]; }, set: function (v) { this[1] = v; } });
return d;
}
function __bounds4(l, t, r, b) {
var a = [l, t, r, b];
Object.defineProperty(a, "left", { get: function () { return this[0]; } });
Object.defineProperty(a, "top", { get: function () { return this[1]; } });
Object.defineProperty(a, "right", { get: function () { return this[2]; } });
Object.defineProperty(a, "bottom", { get: function () { return this[3]; } });
Object.defineProperty(a, "x", { get: function () { return this[0]; } });
Object.defineProperty(a, "y", { get: function () { return this[1]; } });
Object.defineProperty(a, "width", { get: function () { return this[2] - this[0]; } });
Object.defineProperty(a, "height", { get: function () { return this[3] - this[1]; } });
return a;
}
function __toBounds(b) {
if (b === undefined || b === null) return null;
if (b.length === 4) return [__num(b[0]), __num(b[1]), __num(b[2]), __num(b[3])];
if (b.width !== undefined) {
var x = b.x || b.left || 0, y = b.y || b.top || 0;
return [x, y, x + __num(b.width), y + __num(b.height)];
}
return null;
}
var __uiTypes = {
window: "Window", panel: "Panel", group: "Group", button: "Button", iconbutton: "IconButton",
statictext: "StaticText", edittext: "EditText", checkbox: "Checkbox", radiobutton: "RadioButton",
slider: "Slider", scrollbar: "Scrollbar", progressbar: "Progressbar", dropdownlist: "DropDownList",
listbox: "ListBox", tabbedpanel: "TabbedPanel", tab: "Tab", image: "ScriptUIImage"
};
var __uiContainers = { window: 1, panel: 1, group: 1, tabbedpanel: 1, tab: 1 };
function Window(type, title, bounds, props) {
if (!(this instanceof Window)) return new Window(type, title, bounds, props);
type = String(type === undefined ? "window" : type).toLowerCase();
if (type.indexOf("{") >= 0) throw __err("ScriptUI resource strings are not supported: build the window with add()");
if (type !== "dialog" && type !== "palette" && type !== "window") throw __err("Bad window type " + type);
__uiInit(this, "window", null, null, bounds, title, props);
this.__kind = type;
this.__root = true;
__uiWins.push(this);
}
Window.alert = function (s) { alert(s); };
Window.confirm = function (s) { return confirm(s); };
Window.prompt = function (m, d) { return prompt(m, d); };
Window.find = function (type, title) {
for (var i = 0; i < __uiWins.length; i++) if (__uiWins[i].text === title) return __uiWins[i];
return null;
};
function Panel() {}
function Group() {}
function Button() {}
function IconButton() {}
function StaticText() {}
function EditText() {}
function Checkbox() {}
function RadioButton() {}
function Slider() {}
function Scrollbar() {}
function Progressbar() {}
function DropDownList() {}
function ListBox() {}
function TabbedPanel() {}
function Tab() {}
function ScriptUIImage() {}
function ListItem() {}
var ScriptUI = {
version: "6.2.2",
frameworkName: "EffectCraft",
environment: { keyboardState: { shiftKey: false, ctrlKey: false, altKey: false, metaKey: false, keyName: "" } },
FontStyle: { REGULAR: 0, BOLD: 1, ITALIC: 2, BOLDITALIC: 3 },
BrushType: { SOLID_COLOR: 0, THEME_COLOR: 1 },
PenType: { SOLID_COLOR: 0, THEME_COLOR: 1 },
Alignment: { LEFT: "left", RIGHT: "right", TOP: "top", BOTTOM: "bottom", CENTER: "center", FILL: "fill" },
newFont: function (name, style, size) { return { name: name, style: style, size: size }; },
newImage: function () { return {}; },
getResourceText: function (t) { return t; },
events: { createEvent: function (t) { return { type: t }; } }
};
function __uiGraphics() {
return {
newBrush: function (t, c) { return { type: t, color: c }; },
newPen: function (t, c, w) { return { type: t, color: c, lineWidth: w }; },
newPath: function () {}, moveTo: function () {}, lineTo: function () {}, rectPath: function () {},
ellipsePath: function () {}, fillPath: function () {}, strokePath: function () {}, closePath: function () {},
drawString: function () {}, drawOSControl: function () {}, drawImage: function () {}, drawFocusRing: function () {},
measureString: function (s) { return __dim(String(s).length * 7, 16); },
font: null, foregroundColor: null, backgroundColor: null, disabledForegroundColor: null, disabledBackgroundColor: null
};
}
function __uiInit(o, type, win, parent, bounds, text, props) {
o.type = type;
o.window = win || o;
o.parent = parent || null;
o.__id = win ? win.__next++ : 0;
if (!win) {
o.__next = 1;
o.__wid = __uiNewId();
}
o.properties = props || {};
o.text = text === undefined || text === null ? "" : String(text);
o.enabled = true;
o.visible = true;
o.helpTip = "";
o.children = [];
o.__ub = __toBounds(bounds);
o.__lb = [0, 0, 0, 0];
o.preferredSize = __dim(-1, -1);
o.minimumSize = __dim(0, 0);
o.maximumSize = __dim(10000, 10000);
o.alignment = null;
o.graphics = __uiGraphics();
o.__listeners = {};
if (o.properties.name) o.name = o.properties.name;
if (__uiContainers[type]) {
o.orientation = type === "group" ? "row" : type === "tabbedpanel" ? "stack" : "column";
o.alignChildren = type === "group" ? ["center", "center"] : ["center", "top"];
o.spacing = 10;
o.margins = type === "window" ? [15, 15, 15, 15] : type === "panel" ? [10, 15, 10, 10] : type === "tab" ? [10, 10, 10, 10] : [0, 0, 0, 0];
var self = o;
o.layout = {
layout: function () { __uiLayout(self.window); },
resize: function () { __uiLayout(self.window); },
margins: o.margins,
spacing: o.spacing
};
}
if (type === "checkbox" || type === "radiobutton") o.value = !!o.properties.value;
if (type === "slider" || type === "scrollbar" || type === "progressbar") {
o.value = 0;
o.minvalue = 0;
o.maxvalue = 100;
}
if (type === "edittext") {
o.characters = 0;
o.textselection = "";
o.active = false;
}
if (type === "dropdownlist" || type === "listbox") {
o.items = [];
o.__sel = [];
var it = o.properties.items;
if (it) for (var i = 0; i < it.length; i++) o.add("item", it[i]);
}
if (type === "tabbedpanel") o.__sel = [];
return o;
}
function __uiProto() {
return {
add: function (type, bounds, text, props) {
var t = String(type).toLowerCase();
if (t === "item" || t === "separator") return this.__addItem(t === "separator" ? "-" : bounds);
if (!__uiContainers[this.type]) throw __err("add(): a " + this.type + " can't contain controls");
var ctor = __uiTypes[t];
if (!ctor || t === "window") throw __err("add(): unknown control type " + type);
var c = Object.create(__ecGlobal[ctor].prototype);
// Value arguments after `text`: slider (value, min, max), progressbar (value, max), lists (items).
__uiInit(c, t, this.window, this, bounds, typeof text === "object" && text !== null && !(text instanceof Array) ? "" : text, props);
if ((t === "dropdownlist" || t === "listbox") && text instanceof Array) {
for (var i = 0; i < text.length; i++) c.add("item", text[i]);
c.text = "";
}
if (t === "slider" || t === "scrollbar") {
c.text = "";
c.value = text === undefined ? 0 : __num(text);
if (arguments.length > 3 && typeof props === "number") {
c.minvalue = props;
c.maxvalue = arguments[4] === undefined ? 100 : __num(arguments[4]);
c.properties = arguments[5] || {};
}
}
if (t === "progressbar") {
c.text = "";
c.value = text === undefined ? 0 : __num(text);
if (typeof props === "number") {
c.maxvalue = props;
c.properties = arguments[4] || {};
}
}
if (t === "checkbox" || t === "radiobutton") c.value = false;
if (t === "edittext" && c.properties.multiline) c.__multiline = true;
if (t === "edittext" && c.properties.readonly) c.__readonly = true;
if (c.properties && c.properties.name) c.name = c.properties.name;
this.children.push(c);
if (t === "tab" && this.type === "tabbedpanel" && this.__sel.length === 0) this.__sel = [this.children.length - 1];
return c;
},
remove: function (what) {
var list = this.items && this.type !== "tabbedpanel" ? this.items : this.children;
var i = typeof what === "number" ? what : list.indexOf(what);
if (i < 0 || i >= list.length) return;
list.splice(i, 1);
if (this.items) {
for (var k = 0; k < this.items.length; k++) this.items[k].index = k;
this.__sel = this.__sel.filter(function (s) { return s !== i; }).map(function (s) { return s > i ? s - 1 : s; });
}
},
removeAll: function () {
if (this.items) {
this.items = [];
this.__sel = [];
} else this.children = [];
},
find: function (text) {
var list = this.items || this.children;
for (var i = 0; i < list.length; i++) if (list[i].text === text) return list[i];
return null;
},
__addItem: function (text) {
if (!this.items) throw __err("add(\"item\"): only lists have items");
var it = Object.create(ListItem.prototype);
it.text = String(text === undefined ? "" : text);
it.type = text === "-" ? "separator" : "item";
it.index = this.items.length;
it.parent = this;
it.image = null;
it.checked = false;
this.items.push(it);
return it;
},
show: function () {
if (!this.__root) {
this.visible = true;
return;
}
this.__shown = true;
this.__closed = false;
this.__fire("onShow");
if (this.__kind === "dialog") {
this.__modal = true;
var r = __uiModal(this.__wid);
this.__modal = false;
return r === null ? undefined : r;
}
return undefined;
},
hide: function () {
if (this.__root) {
this.close(2);
} else this.visible = false;
},
close: function (result) {
if (!this.__root) return;
if (this.__fire("onClose") === false) return;
this.__closed = true;
this.__shown = false;
this.__result = result === undefined ? 0 : result;
if (this.__modal) __uiResults[this.__wid] = this.__result;
},
center: function () {},
notify: function (ev) {
var e = ev || (this.type === "edittext" || this.type === "slider" || this.type === "dropdownlist" || this.type === "listbox" ? "onChange" : "onClick");
if (e.indexOf("on") !== 0) e = "on" + e.charAt(0).toUpperCase() + e.slice(1);
this.__fire(e);
},
addEventListener: function (name, fn) {
var k = String(name).toLowerCase();
(this.__listeners[k] = this.__listeners[k] || []).push(fn);
},
removeEventListener: function (name, fn) {
var k = String(name).toLowerCase();
if (this.__listeners[k]) this.__listeners[k] = this.__listeners[k].filter(function (f) { return f !== fn; });
},
dispatchEvent: function (e) { this.__fire("on" + String(e.type || e).charAt(0).toUpperCase() + String(e.type || e).slice(1)); },
__fire: function (name) {
var r;
if (typeof this[name] === "function") r = this[name].call(this);
var l = this.__listeners[name.slice(2).toLowerCase()];
if (l) for (var i = 0; i < l.length; i++) l[i].call(this, { type: name.slice(2).toLowerCase(), target: this });
return r;
},
__handlers: function () {
var out = [];
var names = ["onClick", "onChange", "onChanging", "onDoubleClick", "onClose", "onShow", "onActivate", "onDeactivate", "onResize"];
for (var i = 0; i < names.length; i++) {
var n = names[i];
if (typeof this[n] === "function" || (this.__listeners[n.slice(2).toLowerCase()] || []).length) out.push(n);
}
return out;
},
toString: function () { return "[object " + (__uiTypes[this.type] || "Window") + "]"; }
};
}
(function () {
var all = ["Window", "Panel", "Group", "Button", "IconButton", "StaticText", "EditText", "Checkbox", "RadioButton", "Slider",
"Scrollbar", "Progressbar", "DropDownList", "ListBox", "TabbedPanel", "Tab", "ScriptUIImage"];
for (var i = 0; i < all.length; i++) {
var C = __ecGlobal[all[i]];
var p = __uiProto();
for (var k in p) C.prototype[k] = p[k];
Object.defineProperty(C.prototype, "bounds", {
get: function () { var b = this.__ub || this.__lb; return __bounds4(b[0], b[1], b[2], b[3]); },
set: function (v) { this.__ub = __toBounds(v); },
configurable: true
});
Object.defineProperty(C.prototype, "size", {
get: function () { var b = this.bounds; return __dim(b[2] - b[0], b[3] - b[1]); },
set: function (v) {
var b = this.bounds;
var w = v.width !== undefined ? v.width : v[0], h = v.height !== undefined ? v.height : v[1];
this.__ub = [b[0], b[1], b[0] + __num(w), b[1] + __num(h)];
},
configurable: true
});
Object.defineProperty(C.prototype, "location", {
get: function () { var b = this.bounds; return __dim(b[0], b[1]); },
set: function (v) {
var b = this.bounds;
var x = v.x !== undefined ? v.x : v[0], y = v.y !== undefined ? v.y : v[1];
this.__ub = [__num(x), __num(y), __num(x) + b[2] - b[0], __num(y) + b[3] - b[1]];
},
configurable: true
});
}
var sel = {
get: function () {
var self = this;
if (this.type === "tabbedpanel") return this.__sel.length ? this.children[this.__sel[0]] : null;
var items = this.__sel.map(function (i) { return self.items[i]; });
if (this.properties.multiselect) return items.length ? items : null;
return items.length ? items[0] : null;
},
set: function (v) {
var self = this;
var list = this.type === "tabbedpanel" ? this.children : this.items;
var idx = function (x) { return typeof x === "number" ? x : list.indexOf(x); };
if (v === null || v === undefined) this.__sel = [];
else if (v instanceof Array) this.__sel = v.map(idx).filter(function (i) { return i >= 0 && i < list.length; });
else {
var i = idx(v);
this.__sel = i >= 0 && i < list.length ? [i] : [];
}
if (this.items) for (var k = 0; k < this.items.length; k++) this.items[k].selected = this.__sel.indexOf(k) >= 0;
},
configurable: true
};
Object.defineProperty(DropDownList.prototype, "selection", sel);
Object.defineProperty(ListBox.prototype, "selection", sel);
Object.defineProperty(TabbedPanel.prototype, "selection", sel);
Object.defineProperty(ListItem.prototype, "toString", { value: function () { return this.text; } });
})();
// A dockable ScriptUI panel (scripts in the ScriptUI Panels folder run with `this` = it).
function __uiDockPanel(title) {
var p = Object.create(Panel.prototype);
__uiInit(p, "panel", null, null, undefined, title, {});
p.type = "panel";
p.__kind = "panel";
p.__root = true;
p.__shown = true;
p.margins = [10, 10, 10, 10];
__uiWins.push(p);
return p;
}
function __uiAlign(v) {
if (v === null || v === undefined) return [];
if (v instanceof Array) return v.map(function (x) { return String(x).toLowerCase(); });
return [String(v).toLowerCase()];
}
function __uiMargins(m) {
if (m === null || m === undefined) return null;
if (typeof m === "number") return [m, m, m, m];
if (m.length === 4) return [m[0], m[1], m[2], m[3]];
return null;
}
function __uiSize(d) {
if (!d) return null;
var w = d.width !== undefined ? d.width : d[0], h = d.height !== undefined ? d.height : d[1];
w = Number(w);
h = Number(h);
if (!(w > 0) && !(h > 0)) return null;
return [w > 0 ? w : 0, h > 0 ? h : 0];
}
function __uiJson(c) {
var ps = __uiSize(c.preferredSize);
if (c.type === "edittext" && c.characters > 0) ps = [c.characters * 7 + 12, ps ? ps[1] : 0];
var o = {
id: c.__id,
type: c.type,
name: String(c.name || c.properties.name || ""),
text: String(c.text === undefined || c.text === null ? "" : c.text),
enabled: c.enabled !== false,
visible: c.visible !== false,
helpTip: String(c.helpTip || ""),
handlers: c.__handlers(),
children: []
};
if (ps) o.preferredSize = ps;
if (c.__ub && !c.__root) o.fixedBounds = c.__ub;
if (c.__root && c.__ub) o.fixedBounds = [0, 0, c.__ub[2] - c.__ub[0], c.__ub[3] - c.__ub[1]];
if (__uiContainers[c.type]) {
o.orientation = String(c.orientation || "").toLowerCase();
o.alignChildren = __uiAlign(c.alignChildren);
var m = __uiMargins(c.margins);
if (m) o.margins = m;
if (typeof c.spacing === "number") o.spacing = c.spacing;
var kids = c.children;
for (var i = 0; i < kids.length; i++) o.children.push(__uiJson(kids[i]));
}
if (c.alignment !== null && c.alignment !== undefined) o.alignment = __uiAlign(c.alignment);
if (c.type === "checkbox" || c.type === "radiobutton") o.checked = !!c.value;
if (c.type === "slider" || c.type === "scrollbar" || c.type === "progressbar") {
o.value = Number(c.value) || 0;
o.min = Number(c.minvalue) || 0;
o.max = Number(c.maxvalue);
if (!(o.max === o.max)) o.max = 100;
}
if (c.items) {
o.items = c.items.map(function (it) { return String(it.text); });
o.selection = c.__sel.slice();
}
if (c.type === "tabbedpanel") o.activeTab = c.__sel.length ? c.__sel[0] : 0;
if (c.type === "edittext") {
o.multiline = !!c.__multiline;
o.readOnly = !!c.__readonly;
}
return o;
}
// The open windows of this script, for the host.
function __uiSnapshot() {
var out = [];
for (var i = 0; i < __uiWins.length; i++) {
var w = __uiWins[i];
out.push({ id: w.__wid, kind: w.__kind, title: String(w.text || ""), visible: !!w.__shown && !w.__closed, modal: !!w.__modal, root: __uiJson(w) });
}
// Closed windows are forgotten.
__uiWins = __uiWins.filter(function (w) { return !w.__closed; });
return JSON.stringify(out);
}
function __uiOpenCount() {
var n = 0;
for (var i = 0; i < __uiWins.length; i++) if (__uiWins[i].__shown && !__uiWins[i].__closed) n++;
return n;
}
function __uiWin(id) {
for (var i = 0; i < __uiWins.length; i++) if (__uiWins[i].__wid === id) return __uiWins[i];
return null;
}
function __uiFind(c, id) {
if (c.__id === id) return c;
for (var i = 0; i < (c.children || []).length; i++) {
var r = __uiFind(c.children[i], id);
if (r) return r;
}
return null;
}
// layout.layout(): lay the window out now (the host does it before drawing anyway) so scripts
// can read bounds and sizes.
function __uiLayout(win) {
var b = JSON.parse(__uiLayoutNative(JSON.stringify({ id: win.__wid, kind: win.__kind, title: String(win.text || ""), visible: true, root: __uiJson(win) })));
// Bounds are relative to the parent container, as in ScriptUI.
(function apply(c, ox, oy) {
var r = b[c.__id];
if (!r) return;
c.__lb = [r[0] - ox, r[1] - oy, r[0] - ox + r[2], r[1] - oy + r[3]];
for (var i = 0; i < (c.children || []).length; i++) apply(c.children[i], r[0], r[1]);
})(win, 0, 0);
}
// A user action from the frontend.
function __uiDispatch(winId, id, kind, valueJson) {
var w = __uiWin(winId);
if (!w) return;
var v = valueJson === undefined || valueJson === "" ? null : JSON.parse(valueJson);
if (kind === "close") {
w.close(v === null ? 2 : v);
return;
}
var c = __uiFind(w, id);
if (!c || c.enabled === false) return;
var radio = function () {
var sib = c.parent ? c.parent.children : [];
for (var i = 0; i < sib.length; i++) if (sib[i] !== c && sib[i].type === "radiobutton") sib[i].value = false;
c.value = true;
};
if (kind === "click") {
if (c.type === "checkbox") c.value = !c.value;
else if (c.type === "radiobutton") radio();
else if (c.type === "tab" && c.parent) {
c.parent.selection = c;
c.parent.__fire("onChange");
return;
}
var handled = c.__handlers().indexOf("onClick") >= 0;
c.__fire("onClick");
// Dialog buttons without handlers: OK closes with 1, Cancel with 2.
if (!handled && c.type === "button" && w.__kind === "dialog") {
var n = String(c.name || c.properties.name || c.text).toLowerCase();
if (c === w.defaultElement || n === "ok") w.close(1);
else if (c === w.cancelElement || n === "cancel") w.close(2);
}
return;
}
// change / changing
if (c.type === "edittext") c.text = v === null ? "" : String(v);
else if (c.type === "statictext") c.text = v === null ? "" : String(v);
else if (c.type === "slider" || c.type === "scrollbar" || c.type === "progressbar") c.value = Number(v);
else if (c.type === "checkbox") c.value = !!v;
else if (c.type === "radiobutton") { if (v) radio(); else c.value = false; }
else if (c.type === "dropdownlist" || c.type === "listbox" || c.type === "tabbedpanel") c.selection = v;
if (c.type === "edittext" || c.type === "slider" || c.type === "scrollbar") c.__fire("onChanging");
if (kind === "change") {
if (c.type === "checkbox" || c.type === "radiobutton") c.__fire("onClick");
else c.__fire("onChange");
}
}
+299
View File
@@ -0,0 +1,299 @@
//! ScriptUI: windows built by scripts are published to the session, drawn by frontends and
//! driven through the `scriptui.*` commands; dialogs block `show()` until they close; dockable
//! panels; File ▸ Scripts (installed and sample scripts).
use std::sync::Arc;
use effectcraft_engine::Session;
use effectcraft_engine::scriptui::{WidgetKind, WindowKind};
use serde_json::{Value, json};
use crate::run_code;
fn session() -> Session {
let mut s = Session { expr: Some(Arc::new(effectcraft_expr::Expressions)), ..Default::default() };
crate::install(&mut s);
s.config = Some(Arc::new(effectcraft_engine::config::MemoryConfig::default()));
s
}
fn comp_names(s: &Session) -> Vec<String> {
s.project.items.values().filter(|i| i.as_comp().is_some()).map(|i| i.name.clone()).collect()
}
fn layer_names(s: &Session) -> Vec<String> {
s.active_comp().map(|c| c.layers.iter().map(|l| l.name.clone()).collect()).unwrap_or_default()
}
const PALETTE: &str = r#"
var made = 0;
var w = new Window("palette", "Maker");
w.orientation = "column";
w.alignChildren = ["fill", "top"];
var name = w.add("edittext", undefined, "Box");
name.characters = 12;
var big = w.add("checkbox", undefined, "Big");
var row = w.add("group");
var make = row.add("button", undefined, "Make", { name: "make" });
var label = row.add("statictext", undefined, "none yet");
var size = w.add("slider", undefined, 50, 10, 200);
var kind = w.add("dropdownlist", undefined, ["Solid", "Null"]);
kind.selection = 0;
var echo = "";
name.onChange = function () { echo = name.text; };
make.onClick = function () {
var c = app.project.activeItem;
var s = big.value ? 200 : Math.round(size.value);
if (kind.selection.index === 0) c.layers.addSolid([1, 0, 0], name.text, s, s, 1);
else c.layers.addNull().name = name.text;
made++;
label.text = "made " + made;
writeLn("made " + name.text + " " + s);
};
w.show();
"palette up"
"#;
#[test]
fn palette_controls_run_their_handlers() {
let mut s = session();
s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "duration": 2})).unwrap();
let o = run_code(&mut s, PALETTE, "maker.jsx");
assert!(o.error.is_none(), "{:?}", o.error);
assert_eq!(o.result, json!("palette up"));
assert_eq!(s.script_ui.windows.len(), 1);
let w = s.script_ui.windows[0].clone();
assert_eq!((w.kind, w.title.as_str(), w.script.as_str()), (WindowKind::Palette, "Maker", "maker.jsx"));
let kinds: Vec<WidgetKind> = w.root.children.iter().map(|c| c.kind).collect();
assert_eq!(kinds, [WidgetKind::EditText, WidgetKind::Checkbox, WidgetKind::Group, WidgetKind::Slider, WidgetKind::DropDownList]);
// Laid out: the window has a size, the fill-aligned controls span its width.
assert!(w.root.bounds[2] > 100.0 && w.root.bounds[3] > 100.0, "{:?}", w.root.bounds);
let edit = &w.root.children[0];
assert_eq!(edit.bounds[2], w.root.bounds[2] - 30.0);
assert_eq!(w.root.children[3].value, 50.0);
assert_eq!((w.root.children[3].min, w.root.children[3].max), (10.0, 200.0));
assert_eq!(w.root.children[4].items, ["Solid", "Null"]);
assert_eq!(w.root.children[4].selection, [0]);
assert!(w.root.children[2].children[0].handlers.contains(&"onClick".to_string()));
// Agents: list, read, click.
let list = s.execute("scriptui.list", json!({})).unwrap();
assert_eq!(list[0]["title"], "Maker");
let tree = s.execute("scriptui.get", json!({"window": w.id})).unwrap();
assert_eq!(tree["root"]["children"][2]["children"][0]["name"], "make");
let r = s.execute("scriptui.click", json!({"widget": "make"})).unwrap();
assert_eq!(r["output"], "made Box 50", "{r}");
assert_eq!(layer_names(&s), ["Box"]);
// Handlers' edits are undoable engine commands.
assert!(s.undo());
assert!(layer_names(&s).is_empty());
// Set values like a user: text (onChange), checkbox, slider, list by item text.
s.execute("scriptui.set", json!({"widget": "#1", "value": "Crate"})).unwrap();
s.execute("scriptui.click", json!({"widget": "Big"})).unwrap();
s.execute("scriptui.set", json!({"window": "Maker", "widget": 7, "value": "Null"})).unwrap();
let r = s.execute("scriptui.click", json!({"widget": "make"})).unwrap();
assert_eq!(r["output"], "made Crate 200");
assert_eq!(layer_names(&s), ["Crate"]);
assert!(s.active_comp().unwrap().layers[0].source == effectcraft_engine::project::LayerSource::Null);
// The handler updated a label: the published tree follows.
let w = s.script_ui.windows[0].clone();
assert_eq!(w.root.children[2].children[1].text, "made 2");
assert!(w.root.children[1].checked);
assert_eq!(w.root.children[4].selection, [1]);
// Errors.
assert!(s.execute("scriptui.click", json!({"widget": "nope"})).is_err());
assert!(s.execute("scriptui.get", json!({"window": 999_999})).is_err());
// Closing the window ends the script host.
s.execute("scriptui.close", json!({})).unwrap();
assert!(s.script_ui.windows.is_empty());
assert!(s.execute("scriptui.list", json!({})).unwrap().as_array().unwrap().is_empty());
}
const DIALOG: &str = r#"
var d = new Window("dialog", "New Comp");
d.alignChildren = "left";
var e = d.add("edittext", undefined, "Untitled");
var fps = d.add("radiobutton", undefined, "24 fps");
var fps30 = d.add("radiobutton", undefined, "30 fps");
fps.value = true;
var g = d.add("group");
g.add("button", undefined, "Cancel", { name: "cancel" });
var ok = g.add("button", undefined, "OK", { name: "ok" });
writeLn("before");
var r = d.show();
writeLn("result " + r + " " + e.text + " " + (fps30.value ? 30 : 24));
if (r === 1) app.project.items.addComp(e.text, 100, 100, 1, 1, fps30.value ? 30 : 24);
r
"#;
#[test]
fn dialogs_block_show_until_they_close() {
let mut s = session();
let o = run_code(&mut s, DIALOG, "dialog.jsx");
// The script waits in show(); the session is back here meanwhile.
assert!(o.waiting, "{o:?}");
assert_eq!(o.output, ["before"]);
assert_eq!(s.script_ui.windows.len(), 1);
let w = s.script_ui.windows[0].clone();
assert!(w.modal && w.kind == WindowKind::Dialog);
// The app keeps working while the dialog is up.
s.execute("comp.new", json!({"name": "Other", "width": 64, "height": 64, "duration": 1})).unwrap();
s.execute("scriptui.set", json!({"widget": "#1", "value": "Shot 010"})).unwrap();
s.execute("scriptui.click", json!({"widget": "30 fps"})).unwrap();
let w = s.script_ui.windows[0].clone();
assert!(!w.root.children[1].checked && w.root.children[2].checked, "radio buttons are exclusive");
// OK closes the dialog with 1: the script runs on.
let r = s.execute("scriptui.click", json!({"widget": "ok"})).unwrap();
assert_eq!(r["output"], "result 1 Shot 010 30", "{r}");
assert_eq!(r["result"], 1);
assert!(r.get("waiting").is_none());
assert!(s.script_ui.windows.is_empty());
let names = comp_names(&s);
assert!(names.contains(&"Shot 010".to_string()) && names.contains(&"Other".to_string()), "{names:?}");
// Cancel (or closing the window) returns 2.
let o = run_code(&mut s, DIALOG, "dialog.jsx");
assert!(o.waiting);
let r = s.execute("scriptui.close", json!({})).unwrap();
assert_eq!(r["output"], "result 2 Untitled 24");
assert_eq!(comp_names(&s).len(), 2);
}
#[test]
fn layout_and_handler_errors() {
let mut s = session();
let code = r#"
var w = new Window("palette", "L");
var g = w.add("group");
g.orientation = "row";
var a = g.add("button", undefined, "A");
var b = g.add("button", undefined, "B");
b.preferredSize = [120, 30];
var p = w.add("panel", undefined, "Options");
p.add("checkbox", undefined, "One");
var bad = w.add("button", undefined, "Bad");
bad.onClick = function () { nope(); };
w.layout.layout(true);
w.show();
[a.bounds.width, b.size.width, b.size.height, b.bounds[0] - a.bounds[0], w.bounds.width > 200, p.bounds.top > a.bounds.bottom]
"#;
let o = run_code(&mut s, code, "layout.jsx");
assert!(o.error.is_none(), "{:?}", o.error);
assert_eq!(o.result, json!([80, 120, 30, 90, true, true]));
// An error in a handler is reported, the window stays.
let r = s.execute("scriptui.click", json!({"widget": "Bad"})).unwrap();
assert_eq!(r["ok"], false);
assert!(r["error"]["message"].as_str().unwrap().contains("nope"), "{r}");
assert_eq!(s.script_ui.windows.len(), 1);
// Resource strings aren't supported (a clear error).
let o = run_code(&mut s, "new Window(\"dialog { text: 'x' }\")", "res.jsx");
assert!(o.error.unwrap().message.contains("resource"));
s.execute("scriptui.close", json!({})).unwrap();
}
#[test]
fn console_windows_run_inline() {
let mut s = session();
let req = effectcraft_engine::ScriptRequest {
code: "var cw = new Window('palette', 'Console UI'); var cb = cw.add('button', undefined, 'Hi'); var hits = 0; cb.onClick = function () { hits++; writeLn('hit ' + hits); }; cw.show(); 1",
name: "Script Console",
console: true,
};
let o = crate::run(&mut s, &req);
assert!(o.error.is_none(), "{:?}", o.error);
assert_eq!(s.script_ui.windows.len(), 1);
let r = s.execute("scriptui.click", json!({"widget": "Hi"})).unwrap();
assert_eq!(r["output"], "hit 1");
// The console context sees the handler's state.
let o = crate::run(&mut s, &effectcraft_engine::ScriptRequest { code: "hits", name: "Script Console", console: true });
assert_eq!(o.result, json!(1));
// Dialogs don't block in the console.
let o = crate::run(
&mut s,
&effectcraft_engine::ScriptRequest { code: "var dd = new Window('dialog', 'D'); dd.show(); 'went on'", name: "Script Console", console: true },
);
assert_eq!(o.result, json!("went on"));
assert_eq!(s.script_ui.windows.len(), 2);
s.execute("scriptui.close", json!({"window": "D"})).unwrap();
s.execute("scriptui.close", json!({"window": "Console UI"})).unwrap();
assert!(s.script_ui.windows.is_empty());
}
fn solid(s: &mut Session, name: &str, at: f64) -> u64 {
let id = s.execute("layer.newSolid", json!({"name": name, "color": "#808080", "width": 20, "height": 20})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.timing", json!({"layers": [id], "in": at})).unwrap();
id
}
#[test]
fn sample_scripts_and_installing() {
let mut s = session();
s.execute("comp.new", json!({"name": "Main", "width": 400, "height": 200, "duration": 10})).unwrap();
for (n, at) in [("C", 2.0), ("A", 0.0), ("B", 1.0)] {
solid(&mut s, n, at);
}
// File ▸ Scripts lists the samples.
let list = s.execute("file.scripts.list", json!({})).unwrap();
let names: Vec<&str> = list.as_array().unwrap().iter().map(|e| e["name"].as_str().unwrap()).collect();
for want in ["Rename Layers.jsx", "Sort Layers by In Point.jsx", "Create Null at Selected Layers.jsx", "Render Queue Batch.jsx", "Layer Tools.jsx"] {
assert!(names.contains(&want), "{names:?}");
}
// Sort Layers by In Point (all layers when none are selected).
s.execute("edit.deselectAll", json!({})).unwrap();
s.execute("file.runScript", json!({"name": "Sort Layers by In Point.jsx"})).unwrap();
assert_eq!(layer_names(&s), ["A", "B", "C"]);
assert!(s.undo());
assert_eq!(layer_names(&s), ["B", "A", "C"]);
// Create Null at Selected Layers.
let ids: Vec<u64> = s.active_comp().unwrap().layers.iter().take(2).map(|l| l.id.0).collect();
s.execute("layer.select", json!({"layers": ids})).unwrap();
s.execute("file.runScript", json!({"name": "Create Null at Selected Layers.jsx"})).unwrap();
let c = s.active_comp().unwrap();
let null = c.layers.iter().find(|l| l.name == "Centroid").unwrap();
assert!(c.layers.iter().filter(|l| ids.contains(&l.id.0)).all(|l| l.parent == Some(null.id)));
// Rename Layers: a dialog; fill it in and press OK.
s.execute("layer.select", json!({"layers": ids})).unwrap();
let r = s.execute("file.runScript", json!({"name": "Rename Layers.jsx"})).unwrap();
assert_eq!(r["waiting"], true);
s.execute("scriptui.set", json!({"widget": "#11", "value": "Shot_"})).unwrap();
s.execute("scriptui.click", json!({"widget": "Number the layers"})).unwrap();
s.execute("scriptui.click", json!({"widget": "ok"})).unwrap();
let names = layer_names(&s);
assert!(names.contains(&"Shot_B 1".to_string()) && names.contains(&"Shot_A 2".to_string()), "{names:?}");
// Install a script and a ScriptUI panel (they live in the settings store).
let dir = std::env::temp_dir().join(format!("ec-scripts-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Hello.jsx");
std::fs::write(&file, "writeLn('hello from ' + $.fileName); 42").unwrap();
s.execute("file.installScript", json!({"path": file.to_string_lossy()})).unwrap();
let panel = dir.join("Mini Panel.jsx");
std::fs::write(&panel, "var p = this; p.add('button', undefined, 'Go').onClick = function () { writeLn('go'); }; p.layout.layout(true);").unwrap();
s.execute("file.installScriptUIPanel", json!({"path": panel.to_string_lossy()})).unwrap();
let list = s.execute("file.scripts.list", json!({})).unwrap();
assert!(list.as_array().unwrap().iter().any(|e| e["name"] == "Hello.jsx" && e["source"] == "installed" && e["panel"] == false));
assert!(list.as_array().unwrap().iter().any(|e| e["name"] == "Mini Panel.jsx" && e["panel"] == true));
let r = s.execute("file.runScript", json!({"name": "Hello.jsx"})).unwrap();
assert_eq!(r["result"], 42);
// Window ▸ Mini Panel.jsx: a dockable panel; `this` is the panel.
let r = s.execute("window.scriptPanel", json!({"name": "Mini Panel.jsx"})).unwrap();
let wid = r["window"].as_u64().unwrap();
let w = s.script_ui.window(wid as u32).unwrap().clone();
assert_eq!((w.kind, w.title.as_str()), (WindowKind::Panel, "Mini Panel"));
let r = s.execute("scriptui.click", json!({"window": wid, "widget": "Go"})).unwrap();
assert_eq!(r["output"], "go");
// Opening it again brings the same panel forward.
let r = s.execute("window.scriptPanel", json!({"name": "Mini Panel.jsx"})).unwrap();
assert_eq!(r["window"], wid);
// The sample panel docks too, and works.
let r = s.execute("window.scriptPanel", json!({"name": "Layer Tools.jsx"})).unwrap();
let tools = r["window"].as_u64().unwrap();
let before = s.active_comp().unwrap().layers.len();
s.execute("layer.select", json!({"layers": ids})).unwrap();
s.execute("scriptui.click", json!({"window": tools, "widget": "Null at Centroid"})).unwrap();
assert_eq!(s.active_comp().unwrap().layers.len(), before + 1);
s.execute("scriptui.close", json!({"window": tools})).unwrap();
s.execute("scriptui.close", json!({"window": wid})).unwrap();
assert!(s.execute("file.installScript", json!({"path": "/nope/x.txt"})).is_err());
s.execute("file.uninstallScript", json!({"name": "Hello.jsx"})).unwrap();
assert!(s.execute("file.runScript", json!({"name": "Hello.jsx"})).is_err());
let _ = std::fs::remove_dir_all(&dir);
let _: Value = json!(null);
}
+339
View File
@@ -0,0 +1,339 @@
//! ScriptUI hosts: who owns a script window's JavaScript objects, and how user actions reach
//! its handlers.
//!
//! * **Script files** (native builds) run on a *script-host thread*. The caller's session moves
//! to that thread while JavaScript runs and comes back whenever the script stops: at the end,
//! or while a modal dialog waits in `show()`. Each [`ScriptUiEvent`] moves the session there
//! again, runs the handler, and brings it back with the windows' new state. The host ends
//! when its last window closes. Only one side holds the session at a time, so nothing runs
//! concurrently and every edit is still an ordinary undoable engine command.
//! * **The Script Console** (and every run on the web) runs inline: its windows' handlers run in
//! the console's (or a kept) context on the caller's thread, and dialogs don't block.
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::mem::ManuallyDrop;
use std::sync::atomic::{AtomicU32, Ordering};
use boa_engine::{Context, JsResult, JsValue, js_string};
use effectcraft_engine::Session;
use effectcraft_engine::scriptui::{ScriptUiEvent, ScriptWindow, layout};
use serde_json::{Value as J, json};
use crate::runtime::{ACTIVE, Active, CONSOLE, Restore, ScriptError, arg_string, js_str, outcome, script_error, settle, throw, with_active};
pub(crate) const SCRIPTUI: &str = include_str!("scriptui.js");
/// The Script Console's host id.
pub(crate) const CONSOLE_HOST: u32 = u32::MAX;
static NEXT_WINDOW: AtomicU32 = AtomicU32::new(1);
static NEXT_HOST: AtomicU32 = AtomicU32::new(1);
pub(crate) fn new_host_id() -> u32 {
NEXT_HOST.fetch_add(1, Ordering::Relaxed)
}
thread_local! {
/// Contexts of inline runs whose palettes / panels are still open (dropped when they close).
static INLINE: RefCell<BTreeMap<u32, ManuallyDrop<Context>>> = const { RefCell::new(BTreeMap::new()) };
}
pub(crate) fn keep_inline(host: u32, ctx: Context) {
INLINE.with(|m| m.borrow_mut().insert(host, ManuallyDrop::new(ctx)));
}
fn drop_inline(host: u32) {
if let Some(ctx) = INLINE.with(|m| m.borrow_mut().remove(&host)) {
drop(ManuallyDrop::into_inner(ctx));
}
}
// ---------------------------------------------------------------- JavaScript side
fn call_global(ctx: &mut Context, name: &str, args: &[JsValue]) -> JsResult<JsValue> {
let f = ctx.global_object().get(js_string!(name), ctx)?;
let f = f.as_object().ok_or_else(|| throw(format!("{name} is not defined")))?;
f.call(&JsValue::undefined(), args, ctx)
}
/// The open windows of a context (closed ones are reported once, invisible, then forgotten).
pub(crate) fn snapshot(ctx: &mut Context) -> Vec<ScriptWindow> {
let Ok(v) = call_global(ctx, "__uiSnapshot", &[]) else { return vec![] };
let s = v.to_string(ctx).map(|s| s.to_std_string_escaped()).unwrap_or_default();
serde_json::from_str(&s).unwrap_or_default()
}
/// Run a window event's handlers in `ctx`.
fn dispatch_js(ctx: &mut Context, ev: &ScriptUiEvent) -> Result<J, ScriptError> {
let args = [JsValue::from(ev.window), JsValue::from(ev.widget), js_str(&ev.kind), js_str(&ev.value.to_string())];
match call_global(ctx, "__uiDispatch", &args) {
Ok(_) => Ok(J::Null),
Err(e) => {
let mut err = script_error(&e, ctx, "ScriptUI handler", "");
err.message = format!("{} handler: {}", ev.kind, err.message);
Err(err)
}
}
}
/// `__uiNewId()`: a window id unique in the process.
pub(crate) fn native_new_id(_: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
Ok(JsValue::from(NEXT_WINDOW.fetch_add(1, Ordering::Relaxed)))
}
/// `__uiLayoutNative(windowJson)` → `{controlId: [x, y, width, height]}`: ScriptUI's automatic
/// layout ([`effectcraft_engine::scriptui::layout`]) for `layout.layout()`.
pub(crate) fn native_layout(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let s = arg_string(args, 0, ctx)?;
let mut w: ScriptWindow = serde_json::from_str(&s).map_err(|e| throw(format!("layout: {e}")))?;
layout(&mut w);
let mut all = vec![];
w.root.walk(&mut all);
let map: serde_json::Map<String, J> = all.iter().map(|c| (c.id.to_string(), json!(c.bounds))).collect();
Ok(js_str(&J::Object(map).to_string()))
}
/// `__uiModal(windowId)`: a dialog's `show()`. On a script-host thread it hands the session back
/// to the caller and waits for the dialog's events until it closes, returning its result. Inline
/// (Script Console, web) it returns `null` at once: the dialog stays open like a palette.
pub(crate) fn native_modal(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let id = args.first().cloned().unwrap_or_default().to_number(ctx)? as u32;
let linked = with_active(|a| Ok(a.link.is_some())).unwrap_or(false);
if !linked {
return Ok(JsValue::null());
}
loop {
let r = call_global(ctx, "__uiModalResult", &[JsValue::from(id)])?;
if !r.is_null() && !r.is_undefined() {
return Ok(r);
}
let windows = snapshot(ctx);
let out = crate::Outcome { output: settle(), waiting: true, ..Default::default() };
let Some(ev) = yield_wait(out, windows, false) else {
// The caller went away: cancel the dialog.
return Ok(JsValue::from(2));
};
if let Err(e) = dispatch_js(ctx, &ev) {
let line = e.line.map(|l| format!(" (line {l})")).unwrap_or_default();
let _ = with_active(|a| {
a.output.push(format!("Error{line}: {}", e.message));
Ok(())
});
}
}
}
// ---------------------------------------------------------------- script-host threads
pub(crate) enum ToHost {
Start(Session),
Event(Session, ScriptUiEvent),
}
pub(crate) struct FromHost {
session: Session,
outcome: crate::Outcome,
windows: Vec<ScriptWindow>,
name: String,
/// The host thread has ended (no windows left).
done: bool,
}
/// The host thread's end of the hand-off.
pub(crate) struct Link {
rx: std::sync::mpsc::Receiver<ToHost>,
tx: std::sync::mpsc::Sender<FromHost>,
}
/// The caller's end.
struct HostEnd {
tx: std::sync::mpsc::Sender<ToHost>,
rx: std::sync::mpsc::Receiver<FromHost>,
}
fn hosts() -> &'static std::sync::Mutex<BTreeMap<u32, HostEnd>> {
static H: std::sync::OnceLock<std::sync::Mutex<BTreeMap<u32, HostEnd>>> = std::sync::OnceLock::new();
H.get_or_init(Default::default)
}
// The session crosses to script-host threads and back.
const _: fn() = || {
fn send<T: Send>() {}
send::<Session>();
};
/// On the host thread: hand the session (with the windows' state and what the script printed)
/// back to the caller, and wait for the next event. `None` when the caller has gone.
fn yield_wait(outcome: crate::Outcome, windows: Vec<ScriptWindow>, done: bool) -> Option<ScriptUiEvent> {
let (session, link, name) = ACTIVE.with(|a| {
let mut a = a.borrow_mut();
let a = a.as_mut()?;
Some((std::mem::take(&mut a.session), a.link.take()?, a.name.clone()))
})?;
if link.tx.send(FromHost { session, outcome, windows, name, done }).is_err() {
return None;
}
if done {
return None;
}
match link.rx.recv() {
Ok(ToHost::Event(s, ev)) => {
ACTIVE.with(|a| {
if let Some(a) = a.borrow_mut().as_mut() {
a.session = s;
a.link = Some(link);
}
});
Some(ev)
}
_ => None,
}
}
fn host_main(name: String, code: String, link: Link) {
let Ok(ToHost::Start(session)) = link.rx.recv() else { return };
let mut a = Active::new(session, &name);
a.link = Some(link);
ACTIVE.with(|c| *c.borrow_mut() = Some(a));
let file = if name.is_empty() { "script".to_string() } else { name.clone() };
let body = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut ctx = match crate::runtime::new_context() {
Ok(c) => c,
Err(e) => {
yield_wait(outcome(settle(), Err(ScriptError { message: e, file: file.clone(), ..Default::default() })), vec![], true);
return;
}
};
let r = crate::runtime::eval_with_tasks(&mut ctx, &code, &file);
let mut out = outcome(settle(), r);
loop {
let windows = snapshot(&mut ctx);
let open = windows.iter().any(|w| w.visible);
match yield_wait(out, windows, !open) {
Some(ev) => {
let r = dispatch_js(&mut ctx, &ev);
out = outcome(settle(), r);
}
None => return,
}
}
}));
// A panic: give the session back all the same.
let left = ACTIVE.with(|c| c.borrow_mut().take());
if let Some(mut a) = left
&& let Some(link) = a.link.take()
{
let message = if body.is_err() { "the script engine stopped unexpectedly" } else { "the script ended" };
let out = crate::Outcome { error: Some(ScriptError { message: message.into(), file, ..Default::default() }), ..Default::default() };
let _ = link.tx.send(FromHost { session: std::mem::take(&mut a.session), outcome: out, windows: vec![], name, done: true });
}
}
/// Wait for the host to hand the session back; keep its link while it has windows open.
fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome {
match end.rx.recv() {
Ok(FromHost { session: s, outcome, windows, name, done }) => {
*session = s;
publish(session, host, &name, windows);
if done {
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
} else if let Ok(mut h) = hosts().lock() {
h.insert(host, end);
}
outcome
}
Err(_) => crate::Outcome { error: Some(ScriptError { message: "the script host stopped".into(), ..Default::default() }), ..Default::default() },
}
}
/// Run a script file on a new script-host thread (see the module docs).
pub(crate) fn run_threaded(session: &mut Session, req: &effectcraft_engine::ScriptRequest) -> crate::Outcome {
let host = new_host_id();
let (to_tx, to_rx) = std::sync::mpsc::channel();
let (from_tx, from_rx) = std::sync::mpsc::channel();
let (name, code) = (req.name.to_string(), req.code.to_string());
let spawned =
std::thread::Builder::new().name(format!("script-{host}")).stack_size(64 << 20).spawn(move || host_main(name, code, Link { rx: to_rx, tx: from_tx }));
if spawned.is_err() {
return crate::runtime::run_inline(session, req);
}
if let Err(std::sync::mpsc::SendError(ToHost::Start(s) | ToHost::Event(s, _))) = to_tx.send(ToHost::Start(std::mem::take(session))) {
*session = s;
return crate::Outcome { error: Some(ScriptError { message: "the script host did not start".into(), ..Default::default() }), ..Default::default() };
}
receive(session, host, HostEnd { tx: to_tx, rx: from_rx })
}
/// Record the windows a host published (named after the script that made them).
pub(crate) fn publish(session: &mut Session, host: u32, name: &str, mut windows: Vec<ScriptWindow>) {
for w in &mut windows {
if w.script.is_empty() {
w.script = name.to_string();
}
}
let had = session.script_ui.windows.iter().any(|w| w.host == host);
if windows.is_empty() && !had {
return;
}
session.script_ui.publish(host, windows);
if host != CONSOLE_HOST && !session.script_ui.windows.iter().any(|w| w.host == host) {
drop_inline(host);
}
}
/// The [`effectcraft_engine::scriptui::ScriptUiDispatch`] this crate provides: run a window
/// event's handlers in the script that made the window, then publish its windows' new state.
/// Returns the handler run's `{ok, output, error, waiting?}`.
pub fn dispatch_ui(session: &mut Session, ev: &ScriptUiEvent) -> Result<J, String> {
if ACTIVE.with(|a| a.try_borrow().map(|g| g.is_some()).unwrap_or(true)) {
return Err("scripts can't drive script windows".into());
}
let w = session.script_ui.window(ev.window).ok_or_else(|| format!("no script window {}", ev.window))?;
let (host, name) = (w.host, w.script.clone());
let inline = host == CONSOLE_HOST || INLINE.with(|m| m.borrow().contains_key(&host));
if inline {
return Ok(dispatch_inline(session, host, &name, ev).to_json());
}
let end = hosts().lock().ok().and_then(|mut h| h.remove(&host));
let Some(end) = end else {
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
return Err("the script that made this window has ended".into());
};
if let Err(std::sync::mpsc::SendError(ToHost::Event(s, _) | ToHost::Start(s))) = end.tx.send(ToHost::Event(std::mem::take(session), ev.clone())) {
*session = s;
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
return Err("the script that made this window has ended".into());
}
Ok(receive(session, host, end).to_json())
}
fn dispatch_inline(session: &mut Session, host: u32, name: &str, ev: &ScriptUiEvent) -> crate::Outcome {
let s = std::mem::take(session);
ACTIVE.with(|a| *a.borrow_mut() = Some(Active::new(s, name)));
let guard = Restore { target: session };
let (r, windows) = if host == CONSOLE_HOST {
CONSOLE.with(|c| match c.borrow_mut().as_mut() {
Some(ctx) => {
let r = dispatch_js(ctx, ev);
(r, snapshot(ctx))
}
None => (Ok(J::Null), vec![]),
})
} else {
INLINE.with(|m| match m.borrow_mut().get_mut(&host) {
Some(ctx) => {
let r = dispatch_js(ctx, ev);
(r, snapshot(ctx))
}
None => (Ok(J::Null), vec![]),
})
};
let output = settle();
drop(guard);
publish(session, host, name, windows);
outcome(output, r)
}