feat(player): run ActionScript in the subset in Test Movie and the HTML export, with mouse listeners (M6)

This commit is contained in:
Tanish Manku committed 2026-11-10 16:34:25 -07:00
1 parent e0abdc6485
commit 13620efb8f
8 files changed
+588 -75

No files matched your search

+116 -25
View File
@@ -4,8 +4,9 @@
//! [`PlayerState`] holds what changes while a movie plays: the main timeline's scene, frame and
//! playing flag, each movie clip instance's playhead, the properties actions have set, and the
//! pointer. [`step`] advances it by one frame: every playing timeline moves on, the actions on
//! the keyframes they enter run, then that frame's pointer events go to the buttons under the
//! pointer and run their handlers. [`crate::evaluate_player`] draws a state.
//! the keyframes they enter run (and kept ActionScript in the subset that compiles, ADR 0013
//! tier 2, with the mouse listeners it adds), then that frame's pointer events go to the buttons
//! under the pointer and run their handlers. [`crate::evaluate_player`] draws a state.
//!
//! Nothing here changes the document, so the authoring stage and every export stay
//! script-free; and nothing reads a clock or a random source, so the same document, state and
@@ -13,12 +14,14 @@
//! frames entered, instances walked, output lines), so a `goto` loop ends in a message instead
//! of a hang.
use crate::actions::as3::{Listener, ScriptOp};
use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target};
use crate::eval::{Play, evaluate_guided, evaluate_symbol, guide_walk};
use crate::sound::Started;
use crate::{Document, Element, ElementId, ElementKind, LayerKind, MAX_SYMBOL_DEPTH, SymbolId, SymbolKind, Timeline};
use anicraft_geom::{Affine, Vec2};
use std::collections::{BTreeMap, VecDeque};
use std::sync::Arc;
/// An instance's place in the movie: the element ids from the main timeline down to it (empty
/// for the main timeline itself). Element ids stay the same across keyframes that hold the same
@@ -35,6 +38,8 @@ pub const MAX_NODES: usize = 10_000;
pub const MAX_OUTPUT_PER_STEP: usize = 1_000;
/// Most pointer events one step handles.
pub const MAX_EVENTS_PER_STEP: usize = 256;
/// Most listeners scripts add to one instance.
pub const MAX_LISTENERS_PER_INSTANCE: usize = 16;
/// A timeline's playhead.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -103,6 +108,18 @@ impl Overrides {
}
}
/// A mouse listener a script added to an instance (ADR 0013 tier 2): it lives while the
/// instance (and the script's timeline) stay on the stage.
#[derive(Clone, Debug, PartialEq)]
pub struct Listening {
pub event: ButtonEvent,
/// The timeline whose script added it: the actions run there.
pub owner: InstancePath,
/// The function's name: the same function for the same event is added once.
pub function: String,
pub actions: Arc<Vec<Action>>,
}
/// Everything that changes while a movie plays.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PlayerState {
@@ -113,6 +130,8 @@ pub struct PlayerState {
pub clips: BTreeMap<InstancePath, ClipState>,
/// Properties actions have set, per instance.
pub props: BTreeMap<InstancePath, Overrides>,
/// Mouse listeners scripts added, per instance, in the order added.
pub listeners: BTreeMap<InstancePath, Vec<Listening>>,
/// The pointer in stage space (`None` when it is outside the movie), and whether it is down.
pub pointer: Option<Vec2>,
pub down: bool,
@@ -350,7 +369,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2) -> Option<InstancePath> {
for n in nodes.iter().rev() {
let interactive = n.kind == NodeKind::Button || (n.kind == NodeKind::MovieClip && !n.events.is_empty());
let interactive = n.kind == NodeKind::Button || (n.kind == NodeKind::MovieClip && (!n.events.is_empty() || st.listeners.contains_key(&n.path)));
if !n.hittable || !interactive {
continue;
}
@@ -468,6 +487,11 @@ impl<'a, 'h> Run<'a, 'h> {
}
let all: std::collections::BTreeSet<&InstancePath> = self.nodes.iter().map(|n| &n.path).collect();
self.st.props.retain(|p, _| all.contains(p));
// A listener goes with its instance, and with the timeline whose script added it.
self.st.listeners.retain(|p, list| {
list.retain(|l| all.contains(&l.owner));
all.contains(p) && !list.is_empty()
});
for slot in [&mut self.st.hover, &mut self.st.pressed] {
if slot.as_ref().is_some_and(|p| !all.contains(p)) {
*slot = None;
@@ -559,7 +583,7 @@ impl<'a, 'h> Run<'a, 'h> {
let scripts: Vec<&'a FrameScript> = tl.layers.iter().enumerate().filter(|(ix, _)| plays(tl, *ix)).filter_map(|(_, l)| l.keyframe_starting_at(frame).and_then(|k| l.keyframes.get(k))).filter_map(|k| k.script.as_ref()).collect();
for script in scripts {
match script {
FrameScript::Actions(list) => self.run_list(path, list),
FrameScript::Actions(list) => self.run_list(path, list, false),
FrameScript::Plugin(p) => {
let Some(i) = self.index_of(path) else { return };
let label = label_at(tl, frame);
@@ -569,27 +593,80 @@ impl<'a, 'h> Run<'a, 'h> {
self.out(line);
}
let list: Vec<Action> = run.actions.into_iter().take(crate::actions::MAX_ACTIONS).collect();
self.run_list(path, &list);
self.run_list(path, &list, false);
}
// ActionScript in the subset runs, whole (ADR 0013 tier 2); a script outside it
// doesn't run at all. Test Movie lists which is which once, at the start, rather
// than a line every time the playhead passes.
FrameScript::Source(src) => {
if let Ok(c) = src.compiled() {
self.run_ops(path, &c.ops);
}
}
// Kept with the document, not run (ADR 0013 tier 1). The Test Movie window says
// so once, rather than a line every time the playhead passes.
FrameScript::Source(_) => {}
}
}
}
fn run_list(&mut self, owner: &[ElementId], list: &[Action]) {
for a in list {
if self.halted {
return;
}
self.actions += 1;
if self.actions > MAX_ACTIONS_PER_STEP {
self.halt(&format!("more than {MAX_ACTIONS_PER_STEP} actions"));
return;
}
self.exec(owner, a);
/// Counts one action against the step's budget; `false` when nothing more may run.
fn budget(&mut self) -> bool {
if self.halted {
return false;
}
self.actions += 1;
if self.actions > MAX_ACTIONS_PER_STEP {
self.halt(&format!("more than {MAX_ACTIONS_PER_STEP} actions"));
return false;
}
true
}
/// Runs a list of actions from timeline `owner`; `script`: they come from ActionScript.
fn run_list(&mut self, owner: &[ElementId], list: &[Action], script: bool) {
for a in list {
if !self.budget() {
return;
}
self.exec(owner, a, script);
}
}
/// Runs a compiled script's steps (ADR 0013 tier 2), each one action of the budget.
fn run_ops(&mut self, owner: &[ElementId], ops: &[ScriptOp]) {
for op in ops {
if !self.budget() {
return;
}
match op {
ScriptOp::Action(a) => self.exec(owner, a, true),
ScriptOp::Listen(l) => self.listen(owner, l),
}
}
}
/// `addEventListener`: the instance the listener's target names gets it (once per
/// function and event).
fn listen(&mut self, owner: &[ElementId], l: &Listener) {
self.refresh();
let Some(from) = self.index_of(owner) else { return };
let what = format!("Listen for {} ({})", l.event.key(), l.target);
let i = match self.resolve(from, &l.target) {
Ok(i) => i,
Err(e) => return self.out(format!("{what}: {e}")),
};
let Some(node) = self.nodes.get(i) else { return };
if !matches!(node.kind, NodeKind::Button | NodeKind::MovieClip) {
let why = if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is a graphic; only buttons and movie clips get pointer events", node.name) };
return self.out(format!("{what}: {why}"));
}
let (path, name) = (node.path.clone(), node.name.clone());
let list = self.st.listeners.entry(path).or_default();
if list.iter().any(|x| x.event == l.event && x.owner == owner && x.function == l.function) {
return;
}
if list.len() >= MAX_LISTENERS_PER_INSTANCE {
return self.out(format!("{what}: “{name}” already has {MAX_LISTENERS_PER_INSTANCE} listeners"));
}
list.push(Listening { event: l.event, owner: owner.to_vec(), function: l.function.clone(), actions: l.actions.clone() });
}
/// The node `target` names, seen from timeline node `from`.
@@ -608,11 +685,16 @@ impl<'a, 'h> Run<'a, 'h> {
Ok(cur)
}
fn exec(&mut self, owner: &[ElementId], a: &Action) {
/// Runs one action from timeline `owner`. `script`: it comes from ActionScript, where
/// `nextScene()` on a movie clip's timeline has no other scene to go to.
fn exec(&mut self, owner: &[ElementId], a: &Action, script: bool) {
self.refresh();
let Some(from) = self.index_of(owner) else { return };
match a {
Action::Trace { message } => self.out(message.clone()),
Action::NextScene | Action::PrevScene if script && !owner.is_empty() => {
self.out(format!("{}: a movie clip's timeline has one scene; call it in the main timeline's script", a.describe()));
}
Action::NextScene | Action::PrevScene => {
let next = if matches!(a, Action::NextScene) { self.st.scene.checked_add(1) } else { self.st.scene.checked_sub(1) };
if let Some(s) = next.filter(|s| *s < self.doc.scenes.len()) {
@@ -774,14 +856,23 @@ impl<'a, 'h> Run<'a, 'h> {
}
}
/// Runs an instance's handler for `event` (in the timeline the instance is on).
/// Runs an instance's handler for `event` (in the timeline the instance is on), then the
/// listeners scripts added for it (each in the timeline of its script), in the order added.
fn fire(&mut self, path: &[ElementId], event: ButtonEvent) {
self.refresh();
let Some(n) = self.index_of(path).and_then(|i| self.nodes.get(i)) else { return };
let Some(h) = n.events.iter().find(|h| h.event == event) else { return };
let (actions, owner) = (h.actions.clone(), n.owner);
let Some(owner_path) = self.nodes.get(owner).map(|o| o.path.clone()) else { return };
self.run_list(&owner_path, &actions);
let handler = n.events.iter().find(|h| h.event == event).map(|h| h.actions.clone());
let owner_path = self.nodes.get(n.owner).map(|o| o.path.clone());
let listeners: Vec<(InstancePath, Arc<Vec<Action>>)> = self.st.listeners.get(path).map(|l| l.iter().filter(|l| l.event == event).map(|l| (l.owner.clone(), l.actions.clone())).collect()).unwrap_or_default();
if handler.is_none() && listeners.is_empty() {
return;
}
if let (Some(actions), Some(owner)) = (handler, owner_path) {
self.run_list(&owner, &actions, false);
}
for (owner, actions) in listeners {
self.run_list(&owner, &actions, true);
}
self.settle();
}
+107
View File
@@ -341,3 +341,110 @@ fn entered_keyframes_start_their_sounds_in_clips_and_graphics_with_layer_volumes
Arc::make_mut(&mut m.timeline_mut(0).layers[1]).muted = true;
assert_eq!(started(&start(&m, &mut NoScripts)), vec![(1, 1.0), (3, 0.0)]);
}
// ----- ActionScript (ADR 0013 tier 2) -----------------------------------------------------------
/// `k` with a kept ActionScript 3.0 script in place of its actions.
fn as3(k: Arc<Keyframe>, src: &str) -> Arc<Keyframe> {
let mut k = (*k).clone();
k.script = Some(FrameScript::Source(Arc::new(crate::actions::SourceScript::new(crate::actions::Language::ActionScript3, src))));
Arc::new(k)
}
/// The state without the listeners scripts add (hand-made actions use handlers instead).
fn lean(st: &PlayerState) -> PlayerState {
PlayerState { listeners: BTreeMap::new(), ..st.clone() }
}
/// Plays both documents through the same pointer events and asserts the same movie: state and
/// output at every step.
fn same_movie(a: &Document, b: &Document, events: &[Vec<Event>]) {
let (mut x, mut y) = (start(a, &mut NoScripts), start(b, &mut NoScripts));
assert_eq!((lean(&x.state), &x.output), (lean(&y.state), &y.output), "start");
for (i, ev) in events.iter().enumerate() {
x = step(a, &x.state, ev, &mut NoScripts);
y = step(b, &y.state, ev, &mut NoScripts);
assert_eq!((lean(&x.state), &x.output), (lean(&y.state), &y.output), "step {}", i + 1);
}
}
#[test]
fn actionscript_and_hand_made_actions_play_the_same_movie() {
// Nested clips told what to do by instance-name path.
let hand = nested();
let mut script = nested();
{
let l = Arc::make_mut(&mut script.timeline_mut(0).layers[0]);
l.keyframes[0] = as3(l.keyframes[0].clone(), "hero.gotoAndStop(\"run\");\nthis.hero.arm.gotoAndStop(3);");
let arm = Arc::make_mut(&mut script.library[1]);
let al = Arc::make_mut(&mut arm.timeline.layers[0]);
al.keyframes[1] = as3(al.keyframes[1].clone(), "MovieClip(this.parent.parent).stop();");
}
same_movie(&hand, &script, &vec![vec![]; 6]);
// A button's handlers, and the same as listeners a frame script adds.
let hand = button_doc();
let mut script = button_doc();
{
let tl = script.timeline_mut(0);
let l0 = Arc::make_mut(&mut tl.layers[0]);
l0.keyframes[0] = as3(l0.keyframes[0].clone(), "import flash.events.MouseEvent;\nstop();\ngo.addEventListener(MouseEvent.CLICK, onGo);\ngo.addEventListener(MouseEvent.ROLL_OVER, function (e:MouseEvent):void { trace(\"over\"); });\ngo.addEventListener(MouseEvent.ROLL_OUT, function (e:MouseEvent):void { trace(\"o\" + \"ut\"); });\nfunction onGo(e:MouseEvent):void {\n gotoAndStop(5);\n}\n");
let l1 = Arc::make_mut(&mut tl.layers[1]);
let k = Arc::make_mut(&mut l1.keyframes[0]);
if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind {
events.clear();
}
}
let at = |x, y| Vec2::new(x, y);
let events = vec![vec![], vec![Event::Move(at(180.0, 180.0))], vec![Event::Down(at(180.0, 180.0))], vec![Event::Up(at(181.0, 181.0))], vec![Event::Move(at(300.0, 300.0))], vec![], vec![Event::Move(at(150.0, 150.0)), Event::Leave]];
same_movie(&hand, &script, &events);
let s = start(&script, &mut NoScripts);
assert_eq!(s.state.listeners.get(&vec![ElementId(3)]).map(Vec::len), Some(3), "three listeners on the button");
}
#[test]
fn a_script_outside_the_subset_does_not_run_at_all() {
let d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nif (true) { play(); }")])], vec![]);
let s = run(&d, 3);
assert!(s.state.root.playing && s.output.is_empty(), "nothing of it ran: {:?}", s.output);
assert_eq!(s.state.root.frame, 3);
// In ActionScript 1.0 & 2.0 nothing runs either.
let mut d2 = doc(vec![layer(1, vec![kf(0, 10, vec![], vec![], "")])], vec![]);
Arc::make_mut(&mut Arc::make_mut(&mut d2.timeline_mut(0).layers[0]).keyframes[0]).script = Some(FrameScript::Source(Arc::new(crate::actions::SourceScript::new(crate::actions::Language::ActionScript1or2, "stop();"))));
assert!(run(&d2, 2).state.root.playing);
}
#[test]
fn listeners_live_with_their_instance_and_are_added_once() {
// `pad` is a movie clip with no handlers: a listener makes it clickable. It is on the stage
// for frames 0-4; the main timeline loops round 8 frames, adding the listener again each
// time it enters frame 1.
let pad = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 1, vec![rect(12, 0.0, 0.0, 20.0, 20.0)], vec![], "")])]);
let script = "pad.addEventListener(MouseEvent.CLICK, hit);\nfunction hit(e:MouseEvent):void { trace(\"hit\"); }\nghost.addEventListener(MouseEvent.CLICK, hit);";
let d = doc(vec![layer(1, vec![as3(kf(0, 8, vec![], vec![], ""), script)]), layer(2, vec![kf(0, 5, vec![inst(3, 100, "pad", 10.0, 10.0, vec![])], vec![], ""), kf(5, 3, vec![], vec![], "")])], vec![pad]);
let path = vec![ElementId(3)];
let s = start(&d, &mut NoScripts);
assert_eq!(s.output, ["Listen for click (ghost): no instance named “ghost” here"]);
assert!(hit(&d, &s.state, Vec2::new(15.0, 15.0)).is_some(), "the listener makes the clip clickable");
let at = Vec2::new(15.0, 15.0);
let s = step(&d, &s.state, &[Event::Move(at), Event::Down(at), Event::Up(at)], &mut NoScripts);
assert!(s.output.iter().any(|l| l == "hit"), "{:?}", s.output);
let s = run(&d, 5);
assert!(s.state.listeners.is_empty(), "pad left the stage, and its listener with it");
// Round the loop: the frame-1 script adds the same function again, which changes nothing.
let s = run(&d, 8);
assert_eq!(s.state.listeners.get(&path).map(Vec::len), Some(1));
let s = run(&d, 16);
assert_eq!(s.state.listeners.get(&path).map(Vec::len), Some(1));
}
#[test]
fn next_scene_in_a_movie_clip_script_stays_in_its_clip() {
// A clip's own script calling nextScene(): in ActionScript the clip has one scene, so the
// main timeline stays (hand-made Next scene actions do move it, as before).
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![as3(kf(0, 2, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], ""), "nextScene();")])]);
let mut d = doc(vec![layer(1, vec![kf(0, 4, vec![inst(3, 100, "c", 0.0, 0.0, vec![])], vec![], "")])], vec![clip]);
d.scenes.push(Arc::new(crate::Scene::new("Two")));
let s = start(&d, &mut NoScripts);
assert_eq!(s.state.scene, 0);
assert_eq!(s.output, ["Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"]);
}
+42 -8
View File
@@ -1,16 +1,19 @@
//! Kept scripts (ADR 0013 tier 1): frame scripts written in another language (ActionScript, as
//! Kept scripts (ADR 0013): frame scripts written in another language (ActionScript, as
//! Animate documents bring them), symbol linkage classes and the document class, kept verbatim
//! with the document. Nothing runs them yet: Test Movie, rendering and every export skip them.
//! with the document. Scripts in the ActionScript 3.0 subset run in Test Movie and the HTML
//! canvas export (tier 2); the rest are kept and not run, with the problems that say why.
//! Rendering and the other exports never run scripts.
//!
//! `script.set / clear / list` edit and list a keyframe's kept script; `script.set_class`
//! sets a symbol's linkage class or the document class. A keyframe holds actions, a plug-in
//! `script.set / clear / list` edit and list a keyframe's kept script; `script.check` says
//! whether a text would run; `script.set_class` sets a symbol's linkage class or the document
//! class. A keyframe holds actions, a plug-in
//! frame script *or* a kept script (one `Keyframe.script`), so setting one replaces the other,
//! as one undo step.
use crate::cmds_actions::{Scope, keyframe_in};
use crate::params::*;
use crate::{CommandSpec, EngineError, Result, Session};
use anicraft_doc::actions::{self, FrameScript, Language, SourceScript};
use anicraft_doc::actions::{self, CompileResult, FrameScript, Language, SourceScript};
use anicraft_doc::{Linkage, SymbolId};
use serde_json::{Value, json};
use std::sync::Arc;
@@ -18,9 +21,10 @@ use std::sync::Arc;
pub fn specs() -> Vec<CommandSpec> {
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
vec![
c("script.set", "Set Frame Script", "", None, "{text?: the script, verbatim (\"\" clears; at most 1 MiB), language?: actionscript3|actionscript1or2|other (default: the script's, else actionscript3), symbol?: id, layer?, frame?} keeps a script on the keyframe at the frame (it replaces actions there); it is kept with the document and doesn't run", true, set as crate::RunFn),
c("script.set", "Set Frame Script", "", None, "{text?: the script, verbatim (\"\" clears; at most 1 MiB), language?: actionscript3|actionscript1or2|other (default: the script's, else actionscript3), symbol?: id, layer?, frame?} keeps a script on the keyframe at the frame (it replaces actions there); ActionScript 3.0 in the subset runs in Test Movie and the HTML export, the rest is kept and not run (`runs`, `problems` say which)", true, set as crate::RunFn),
c("script.clear", "Clear Frame Script", "", None, "{symbol?, layer?, frame?} removes the keyframe's kept script (actions are left alone: actions.clear)", true, clear),
c("script.list", "List Frame Scripts", "", None, "{text?: bool (default true)} every kept script in every scene and symbol, with its text, plus symbol linkage classes and the document class", false, list),
c("script.list", "List Frame Scripts", "", None, "{text?: bool (default true)} every kept script in every scene and symbol, with its text, whether it runs and its problems, plus symbol linkage classes and the document class", false, list),
c("script.check", "Check Frame Script", "", None, "{text: the script, language?: actionscript3|actionscript1or2|other (default actionscript3)} whether it would run (the ActionScript 3.0 subset, ADR 0013), its problems with line and column, what is ignored, and the steps it runs; changes nothing", false, check),
c("script.set_class", "Set Script Class", "", None, "{symbol?: id (default: the document), class: dotted class name (\"\" clears), base?: the class it extends} sets a symbol's linkage class, or the document class; kept as text, not run", true, set_class),
]
}
@@ -42,6 +46,30 @@ fn what(script: &Option<FrameScript>) -> Value {
}
}
/// Whether a script runs, its problems and notes (each `{line, column, message}`; line 0 is
/// the whole script).
fn status(c: &CompileResult) -> Value {
match c {
Ok(c) => json!({"runs": true, "problems": [], "notes": c.notes}),
Err(p) => json!({"runs": false, "problems": p, "notes": []}),
}
}
fn check(_: &mut Session, p: &Value) -> Result<Value> {
let text = str_req(p, "text")?;
if text.len() > actions::MAX_SOURCE_BYTES {
return Err(EngineError::Param(format!("a script is at most {} KiB", actions::MAX_SOURCE_BYTES / 1024)));
}
let script = SourceScript::new(language(p)?.unwrap_or_default(), text);
let c = script.compiled();
let mut v = status(c);
if let Ok(c) = c {
v["steps"] = json!(c.ops);
v["describe"] = json!(c.ops.iter().map(|o| o.describe()).collect::<Vec<_>>());
}
Ok(v)
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let lang = language(p)?;
let text = match p.get("text") {
@@ -74,7 +102,10 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
let script = SourceScript::new(lang.or(old.map(|o| o.language)).unwrap_or_default(), text);
script.check().map_err(EngineError::Param)?;
let out = json!({"layer": lid.0, "keyframe": k.start, "language": script.language.key(), "lines": script.lines(), "bytes": script.text.len(), "replaced": if before == json!("script") { Value::Null } else { before }});
let mut out = json!({"layer": lid.0, "keyframe": k.start, "language": script.language.key(), "lines": script.lines(), "bytes": script.text.len(), "replaced": if before == json!("script") { Value::Null } else { before }});
if let (Some(o), Value::Object(st)) = (out.as_object_mut(), status(script.compiled())) {
o.extend(st);
}
k.script = Some(FrameScript::Source(Arc::new(script)));
Ok(out)
}
@@ -97,6 +128,9 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
for k in &l.keyframes {
let Some(src) = k.script.as_ref().and_then(FrameScript::source) else { continue };
let mut v = json!({"timeline": name, "layer": l.id.0, "layer_name": l.name, "frame": k.start, "label": k.label, "language": src.language.key(), "lines": src.lines(), "bytes": src.text.len()});
if let (Some(o), Value::Object(st)) = (v.as_object_mut(), status(src.compiled())) {
o.extend(st);
}
if with_text {
v["text"] = json!(src.text);
}
+73 -2
View File
@@ -9,9 +9,9 @@
//! its scripts, so a script that loops forever costs one frame's budget, then stops with a
//! message.
use anicraft_doc::actions::{Action, MAX_ACTIONS, PluginScript, check_actions};
use anicraft_doc::actions::{Action, CompileResult, FrameScript, MAX_ACTIONS, PluginScript, check_actions};
use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step};
use anicraft_doc::{Document, player};
use anicraft_doc::{Document, LayerKind, SymbolKind, Timeline, player};
use anicraft_geom::Vec2;
use anicraft_plugins::{Host, Kind, Limits, Registry};
use serde_json::{Map, Value, json};
@@ -187,8 +187,12 @@ pub const MAX_MOVIE_OUTPUT: usize = 10_000;
pub const MAX_MOVIE_SOUNDS: usize = 4_096;
impl Movie {
/// The movie at its first frame. The Output starts with a line for each kept script: which
/// run and which are skipped and why (ADR 0013 tier 2), said once rather than each time the
/// playhead passes.
pub fn start(doc: &Document, scripts: &mut dyn ScriptHost) -> Movie {
let mut m = Movie { state: PlayerState::default(), output: Vec::new(), sounds: Vec::new() };
m.output.extend(script_summary(doc).into_iter().map(|l| (0, l)));
let s = player::start(doc, scripts);
m.take(s);
m
@@ -246,3 +250,70 @@ pub fn parse_events(v: &Value) -> Result<Vec<Event>, String> {
other => return Err(format!("unknown event type '{other}' (move, down, up, click or leave)")),
})
}
/// A kept script (ADR 0013) and where it is.
pub struct KeptScript<'a> {
/// "Scene 1 › Actions, frame 1" (frames 1-based, as the app shows them).
pub place: String,
/// The timeline runs frame scripts there (a scene or a movie clip, on a layer that plays).
pub plays: bool,
pub compiled: &'a CompileResult,
}
impl KeptScript<'_> {
/// It runs when the movie plays.
pub fn runs(&self) -> bool {
self.plays && self.compiled.is_ok()
}
}
/// Most kept scripts listed.
pub const MAX_LISTED_SCRIPTS: usize = 1_000;
fn layer_plays(tl: &Timeline, index: usize) -> bool {
tl.layers.get(index).is_some_and(|l| l.visible && !matches!(l.kind, LayerKind::Folder | LayerKind::Guide)) && !tl.hidden_by_folder(index)
}
/// Every kept script in the document: the scenes' first, then the symbols'.
pub fn kept_scripts(doc: &Document) -> Vec<KeptScript<'_>> {
let scenes = doc.scenes.iter().map(|s| (s.name.as_str(), &s.timeline, true));
let symbols = doc.library.iter().map(|s| (s.name.as_str(), &s.timeline, s.kind == SymbolKind::MovieClip));
let mut out = Vec::new();
for (name, tl, runs) in scenes.chain(symbols) {
for (index, layer) in tl.layers.iter().enumerate() {
for k in &layer.keyframes {
let Some(FrameScript::Source(src)) = &k.script else { continue };
if out.len() >= MAX_LISTED_SCRIPTS {
return out;
}
out.push(KeptScript { place: format!("{name} › {}, frame {}", layer.name, u64::from(k.start) + 1), plays: runs && layer_plays(tl, index), compiled: src.compiled() });
}
}
}
out
}
/// The Output's opening lines: each kept script that runs (and what in it is ignored), and
/// each that doesn't, with why.
pub fn script_summary(doc: &Document) -> Vec<String> {
let mut lines = Vec::new();
for k in kept_scripts(doc) {
match (k.plays, k.compiled) {
(false, _) => lines.push(format!("Frame script not run: {}: graphic and button timelines, guide layers and hidden layers don't run frame scripts", k.place)),
(true, Ok(c)) => {
lines.push(format!("Frame script runs: {}", k.place));
lines.extend(c.notes.iter().map(|n| format!("Frame script at {}: {n}", k.place)));
}
(true, Err(problems)) => {
let first = problems.first().map_or_else(String::new, ToString::to_string);
let more = match problems.len() {
0 | 1 => String::new(),
2 => " (and 1 more problem: see the Actions panel)".into(),
n => format!(" (and {} more problems: see the Actions panel)", n - 1),
};
lines.push(format!("Frame script not run: {}: {first}{more}", k.place));
}
}
}
lines
}
+39 -7
View File
@@ -132,21 +132,53 @@ fn kept_scripts_survive_the_file_and_hostile_ones_are_dropped_whole() {
}
#[test]
fn nothing_runs_a_kept_script() {
fn scripts_in_the_subset_run_and_the_rest_are_kept_and_said_so() {
let mut s = Session::new(sample::interactive());
let layer = s.doc.timeline(0).layers[0].id.0;
// A script that would stop the movie and trace, on the show keyframe instead of its actions.
s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "trace(\"xyzzy-kept\"); stop();"})).unwrap();
// A script that stops the movie and traces, on the show keyframe instead of its actions.
let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "trace(\"xyzzy-\" + 1); stop();"})).unwrap();
assert_eq!((v["runs"].as_bool(), v["problems"].as_array().map(Vec::len)), (Some(true), Some(0)), "{v}");
let v = s.execute("control.test_movie", &json!({"frames": 20, "events": [{"tick": 2, "type": "click", "x": 640, "y": 400}]})).unwrap();
let lines: Vec<&str> = v["output"].as_array().unwrap().iter().filter_map(|l| l["line"].as_str()).collect();
assert!(lines.is_empty(), "{lines:?}");
assert_eq!(lines.first().copied(), Some("Frame script runs: Scene 1 › Actions, frame 2"), "{lines:?}");
assert!(lines.contains(&"xyzzy-1"), "{lines:?}");
assert!(v["state"]["frame"].as_u64().unwrap() < 10 && v["state"]["playing"] == false, "it stopped: {}", v["state"]);
// The HTML export runs it too, as the same actions.
let out = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap();
assert!(out.html.contains("xyzzy-1") && !out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report);
// One outside the subset doesn't run at all, and Test Movie says where and why.
let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "stop();
var n:int = 1;"})).unwrap();
assert_eq!(v["runs"], false);
assert_eq!(v["problems"][0], json!({"line": 2, "column": 1, "message": "variables (`var`) aren't supported yet"}));
let v = s.execute("control.test_movie", &json!({"frames": 20, "events": [{"tick": 2, "type": "click", "x": 640, "y": 400}]})).unwrap();
assert_eq!(v["output"][0]["line"], "Frame script not run: Scene 1 › Actions, frame 2: line 2, column 1: variables (`var`) aren't supported yet");
assert!(v["state"]["frame"].as_u64().unwrap() > 10, "it played on: {}", v["state"]);
// The HTML export draws the movie and says the script isn't in it.
let out = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap();
assert!(out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report);
assert!(!out.html.contains("xyzzy-kept"), "the script's text isn't exported");
assert!(!out.html.contains("var n:int"), "a kept script's text isn't exported");
let list = s.execute("script.list", &json!({"text": false})).unwrap();
assert_eq!((list["frames"][0]["runs"].as_bool(), list["frames"][0]["problems"][0]["line"].as_u64()), (Some(false), Some(2)));
// Plug-ins may read and write kept scripts, as they may actions.
for id in ["script.set", "script.clear", "script.list", "script.set_class"] {
for id in ["script.set", "script.clear", "script.list", "script.set_class", "script.check"] {
assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}");
}
}
#[test]
fn script_check_says_what_a_text_would_do_and_changes_nothing() {
let mut s = Session::new(sample::interactive());
let before = s.doc.clone();
let v = s.execute("script.check", &json!({"text": "stop();
btn.addEventListener(MouseEvent.CLICK, go);
function go(e:MouseEvent):void { gotoAndPlay(\"run\"); }
navigateToURL(new URLRequest(\"x\"));"})).unwrap();
assert_eq!(v["runs"], true);
assert_eq!(v["describe"], json!(["Stop", "On click (btn): Go to “run” and play"]));
assert_eq!(v["steps"][1]["listen"]["target"], "btn");
assert_eq!(v["notes"][0]["line"], 4);
let v = s.execute("script.check", &json!({"text": "stop();", "language": "actionscript1or2"})).unwrap();
assert_eq!((v["runs"].as_bool(), v["problems"][0]["line"].as_u64()), (Some(false), Some(0)));
assert!(s.execute("script.check", &json!({})).is_err());
assert!(s.doc == before && s.undo_label().is_none());
}
+58 -13
View File
@@ -14,10 +14,13 @@
//! frames are stored once, so a still keyframe over many frames costs one entry.
//!
//! What doesn't carry across is counted in the report: filters, Subtract and Invert blending,
//! tints on bitmaps, and plug-in frame scripts (they need the plug-in host).
//! tints on bitmaps, plug-in frame scripts (they need the plug-in host) and kept scripts
//! outside the ActionScript subset. Scripts in the subset (ADR 0013 tier 2) come across as the
//! same actions and listeners the Rust player runs.
use crate::stroke::variable_outline;
use anicraft_doc::actions::{Action, FrameRef, Seg};
use anicraft_doc::actions::as3::ScriptOp;
use anicraft_doc::actions::{Action, FrameRef, Seg, Target};
use anicraft_doc::{BlendMode, ColorEffect, Document, Element, ElementKind, FrameScript, Layer, LayerKind, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start};
use anicraft_geom::{Affine, FillRule, Path, PathCmd};
use serde_json::{Map, Value, json};
@@ -90,7 +93,8 @@ const BLENDS: &str = "Subtract and Invert blending (drawn normally)";
const BITMAP_TINT: &str = "tints on bitmap fills (drawn untinted)";
const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)";
const BUTTON_SOUNDS: &str = "sounds on button frames (not played yet)";
const KEPT_SCRIPTS: &str = "kept frame scripts (not run; kept in the document only)";
const KEPT_SCRIPTS: &str = "kept frame scripts outside the ActionScript subset (not run; kept in the document only)";
const OUTSIDE_CALLS: &str = "script calls that reach outside the movie (ignored)";
/// A number rounded to `1/scale`, written as an integer when it is one.
fn num(v: f32, scale: f64) -> Value {
@@ -176,13 +180,10 @@ fn path_data(p: &Path) -> String {
if finite { s } else { String::new() }
}
/// An action as the player reads it: `op`, the target as steps (`^` the main timeline, `..` up
/// a level, else an instance name; `e` when it isn't a valid path), and `d`, its description
/// (for messages).
fn action(a: &Action) -> Value {
let mut o = Map::new();
o.insert("op".into(), json!(a.op()));
if let Some(t) = a.target() {
/// A target as the player reads it: `t`, its steps (`^` the main timeline, `..` up a level,
/// else an instance name), or `e` when it isn't a valid path.
fn target(o: &mut Map<String, Value>, t: &Target) {
{
match t.segments() {
Ok(segs) => {
if !segs.is_empty() {
@@ -202,6 +203,16 @@ fn action(a: &Action) -> Value {
}
}
}
}
/// An action as the player reads it: `op`, its target (see [`target`]), and `d`, its
/// description (for messages).
fn action(a: &Action) -> Value {
let mut o = Map::new();
o.insert("op".into(), json!(a.op()));
if let Some(t) = a.target() {
target(&mut o, t);
}
match a {
Action::Trace { message } => {
o.insert("msg".into(), json!(message));
@@ -232,6 +243,28 @@ fn actions(list: &[Action]) -> Value {
Value::Array(list.iter().map(action).collect())
}
/// A compiled script's steps (ADR 0013 tier 2): actions, and `listen` steps with the target,
/// the event `ev`, the function `k` and the actions `h` it runs.
fn script_ops(ops: &[ScriptOp]) -> Value {
Value::Array(
ops.iter()
.map(|op| match op {
ScriptOp::Action(a) => action(a),
ScriptOp::Listen(l) => {
let mut o = Map::new();
o.insert("op".into(), json!("listen"));
target(&mut o, &l.target);
o.insert("ev".into(), json!(l.event.key()));
o.insert("k".into(), json!(l.function));
o.insert("h".into(), actions(&l.actions));
o.insert("d".into(), json!(format!("Listen for {} ({})", l.event.key(), l.target)));
Value::Object(o)
}
})
.collect(),
)
}
/// Whether timeline layer `index` takes part in playback (what the player walks and draws):
/// shown, not a folder or guide, not in a hidden folder.
fn plays(tl: &Timeline, index: usize) -> bool {
@@ -515,9 +548,21 @@ impl<'a> Bake<'a> {
self.notes.entry(PLUGIN_SCRIPTS).or_default().insert(u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0));
a.push(json!({"plugin": format!("{} · {}", p.id, p.entry)}));
}
// Kept scripts don't run anywhere yet (ADR 0013 tier 1).
Some(FrameScript::Source(_)) => {
self.notes.entry(KEPT_SCRIPTS).or_default().insert(u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0));
// ActionScript in the subset runs as the player runs it; the rest is only
// kept (ADR 0013).
Some(FrameScript::Source(src)) => {
let key = u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0);
match src.compiled() {
Ok(c) => {
a.push(json!({"as": script_ops(&c.ops)}));
if !c.notes.is_empty() {
self.notes.entry(OUTSIDE_CALLS).or_default().insert(key);
}
}
Err(_) => {
self.notes.entry(KEPT_SCRIPTS).or_default().insert(key);
}
}
}
None => {}
}
+71 -20
View File
@@ -1,7 +1,8 @@
// AniCraft HTML canvas player: the core (ADR 0028). SPDX-License-Identifier: MIT OR Apache-2.0
//
// Plays a movie exported by File > Export > HTML Canvas: the instance tree, movie clip
// playheads, frame actions and button events. It is a line-by-line port of the Rust player
// playheads, frame actions, button events, and frame scripts in the ActionScript subset
// (compiled by AniCraft to the same actions, with the mouse listeners they add). It is a line-by-line port of the Rust player
// (crates/doc/src/player.rs, the reference) over the exported data, and the tests run it in a
// JavaScript engine against that player. Nothing here touches the page: canvas.js draws and
// listens to the pointer; this file only computes.
@@ -20,6 +21,7 @@ var AniCraft = (function () {
const MAX_EVENTS_PER_STEP = 256;
const MAX_SOUNDS_PER_STEP = 256;
const MAX_SYMBOL_DEPTH = 32;
const MAX_LISTENERS_PER_INSTANCE = 16;
const ROOT = 0, GRAPHIC = 1, CLIP = 2, BUTTON = 3;
const KINDS = { graphic: GRAPHIC, movieclip: CLIP, button: BUTTON };
const I = [1, 0, 0, 1, 0, 0];
@@ -141,9 +143,10 @@ var AniCraft = (function () {
// ----- the player state ------------------------------------------------------------------------
function newState() {
return { scene: 0, root: { frame: 0, playing: true }, clips: new Dict(), props: new Dict(), pointer: null, down: false, hover: null, pressed: null, tick: 0 };
return { scene: 0, root: { frame: 0, playing: true }, clips: new Dict(), props: new Dict(), listeners: new Dict(), pointer: null, down: false, hover: null, pressed: null, tick: 0 };
}
// Each clip entry: { path, frame, playing }; each props entry: { path, ...overrides }.
// Each clip entry: { path, frame, playing }; each props entry: { path, ...overrides }; each
// listeners entry: [{ ev, owner, k, h, path }] in the order added.
function clipFrame(st, key, len) {
const c = st.clips.get(key);
return Math.min(c ? c.frame : 0, Math.max(len, 1) - 1);
@@ -331,7 +334,7 @@ var AniCraft = (function () {
function hitIn(M, st, nodes, host, x, y) {
for (let i = nodes.length - 1; i >= 0; i--) {
const n = nodes[i];
const interactive = n.kind === BUTTON || (n.kind === CLIP && n.events);
const interactive = n.kind === BUTTON || (n.kind === CLIP && (n.events || st.listeners.has(n.key)));
if (!n.hittable || !interactive) continue;
const sym = M.symbols[n.sym];
if (!sym) continue;
@@ -408,7 +411,8 @@ var AniCraft = (function () {
for (const k of Object.keys(p)) if (k !== "path") o[k] = p[k];
return [p.path, o];
});
return { scene: st.scene, frame: st.root.frame, playing: st.root.playing, clips: clips, props: props, hover: st.hover, pressed: st.pressed, down: st.down };
const listeners = Array.from(st.listeners.values()).filter((l) => l.length > 0).sort((a, b) => comparePaths(a[0].path, b[0].path)).map((l) => [l[0].path, l.map((x) => [x.ev, x.owner, x.k])]);
return { scene: st.scene, frame: st.root.frame, playing: st.root.playing, clips: clips, props: props, listeners: listeners, hover: st.hover, pressed: st.pressed, down: st.down };
};
function Run(player) {
@@ -477,6 +481,12 @@ var AniCraft = (function () {
this.queue(path);
}
for (const k of Array.from(st.props.keys())) if (!all.has(k)) st.props.delete(k);
// A listener goes with its instance, and with the timeline whose script added it.
for (const [k, list] of st.listeners.entries()) {
const kept = list.filter((l) => all.has(keyOf(l.owner)));
if (!all.has(k) || kept.length === 0) st.listeners.delete(k);
else st.listeners.set(k, kept);
}
if (st.hover !== null && !all.has(keyOf(st.hover))) st.hover = null;
if (st.pressed !== null && !all.has(keyOf(st.pressed))) st.pressed = null;
};
@@ -559,20 +569,57 @@ var AniCraft = (function () {
const frame = this.nodes[i].frame;
this.soundsAt(tl, frame, this.nodes[i].gain);
for (const script of (tl.a && tl.a[frame]) || []) {
if (Array.isArray(script)) this.runList(path, script);
if (Array.isArray(script)) this.runList(path, script, false);
else if (script.as) this.runOps(path, script.as);
else this.out("Frame script " + script.plugin + " not run: frame scripts are not exported");
}
};
Run.prototype.runList = function (owner, list) {
for (const a of list) {
if (this.halted) return;
this.actions += 1;
if (this.actions > MAX_ACTIONS_PER_STEP) {
this.halt("more than " + MAX_ACTIONS_PER_STEP + " actions");
return;
}
this.exec(owner, a);
// Counts one action against the step's budget; false when nothing more may run.
Run.prototype.budget = function () {
if (this.halted) return false;
this.actions += 1;
if (this.actions > MAX_ACTIONS_PER_STEP) {
this.halt("more than " + MAX_ACTIONS_PER_STEP + " actions");
return false;
}
return true;
};
// `script`: the actions come from ActionScript.
Run.prototype.runList = function (owner, list, script) {
for (const a of list) {
if (!this.budget()) return;
this.exec(owner, a, script);
}
};
// A compiled script's steps: actions, and `listen` (addEventListener).
Run.prototype.runOps = function (owner, ops) {
for (const a of ops) {
if (!this.budget()) return;
if (a.op === "listen") this.listen(owner, a);
else this.exec(owner, a, true);
}
};
// The instance the listener's target names gets it (once per function and event).
Run.prototype.listen = function (owner, a) {
this.refresh();
const from = this.indexOf(owner);
if (from < 0) return;
const [i, err] = this.resolve(from, a);
if (i < 0) return this.out(a.d + ": " + err);
const node = this.nodes[i];
if (!node) return;
if (node.kind !== BUTTON && node.kind !== CLIP) {
const why = node.kind === ROOT ? "the main timeline doesn't get pointer events here" : "“" + node.name + "” is a graphic; only buttons and movie clips get pointer events";
return this.out(a.d + ": " + why);
}
let list = this.st.listeners.get(node.key);
if (list && list.some((x) => x.ev === a.ev && samePath(x.owner, owner) && x.k === a.k)) return;
if (list && list.length >= MAX_LISTENERS_PER_INSTANCE) return this.out(a.d + ": “" + node.name + "” already has " + MAX_LISTENERS_PER_INSTANCE + " listeners");
if (!list) {
list = [];
this.st.listeners.set(node.key, list);
}
list.push({ ev: a.ev, owner: owner, k: a.k, h: a.h, path: node.path });
};
// The node `a`'s target names, seen from timeline node `from`: [index] or [-1, why].
Run.prototype.resolve = function (from, a) {
@@ -593,7 +640,7 @@ var AniCraft = (function () {
}
return [cur];
};
Run.prototype.exec = function (owner, a) {
Run.prototype.exec = function (owner, a, script) {
this.refresh();
const from = this.indexOf(owner);
if (from < 0) return;
@@ -604,6 +651,8 @@ var AniCraft = (function () {
return;
case "next_scene":
case "prev_scene": {
// In ActionScript a movie clip's timeline has one scene.
if (script && owner.length > 0) return this.out(a.d + ": a movie clip's timeline has one scene; call it in the main timeline's script");
const s = a.op === "next_scene" ? st.scene + 1 : st.scene - 1;
if (s >= 0 && s < this.M.scenes.length) this.gotoRoot(s, 0);
return;
@@ -757,17 +806,19 @@ var AniCraft = (function () {
if (now !== null) this.fire(now, "over");
}
};
// Runs an instance's handler for `event`, in the timeline the instance is on.
// Runs an instance's handler for `event`, in the timeline the instance is on, then the
// listeners scripts added for it (each in its script's timeline), in the order added.
Run.prototype.fire = function (path, event) {
this.refresh();
const i = this.indexOf(path);
if (i < 0) return;
const n = this.nodes[i];
const h = (n.events || []).find((x) => x[0] === event);
if (!h) return;
const ls = (this.st.listeners.get(n.key) || []).filter((l) => l.ev === event);
if (!h && ls.length === 0) return;
const owner = this.nodes[n.owner];
if (!owner) return;
this.runList(owner.path, h[1]);
if (h && owner) this.runList(owner.path, h[1], false);
for (const l of ls) this.runList(l.owner, l.h, true);
this.settle();
};
Run.prototype.finish = function () {
+82
View File
@@ -200,6 +200,7 @@ fn snapshot(st: &PlayerState) -> Value {
json!({
"scene": st.scene, "frame": st.root.frame, "playing": st.root.playing,
"clips": st.clips.iter().map(|(p, c)| json!([ids(p), c.frame, c.playing])).collect::<Vec<_>>(),
"listeners": st.listeners.iter().filter(|(_, l)| !l.is_empty()).map(|(p, l)| json!([ids(p), l.iter().map(|x| json!([x.event.key(), ids(&x.owner), x.function])).collect::<Vec<_>>()])).collect::<Vec<_>>(),
"hover": st.hover.as_deref().map(ids), "pressed": st.pressed.as_deref().map(ids), "down": st.down,
})
}
@@ -585,3 +586,84 @@ fn hostile_documents_export_without_panicking() {
let m = movie(&Document::default(), &HtmlOptions::default());
assert_eq!(m.json["timelines"][0]["n"], 1);
}
/// `k` with a kept ActionScript 3.0 script in place of its actions.
fn as3(k: &mut Arc<Keyframe>, src: &str) {
Arc::make_mut(k).script = Some(FrameScript::Source(Arc::new(anicraft_doc::actions::SourceScript::new(anicraft_doc::actions::Language::ActionScript3, src))));
}
/// The fixture with its frame actions and the knob's handlers written as ActionScript: the
/// main timeline's first frame adds the knob's listeners (named and inline functions,
/// `currentTarget`), a listener makes the panel clip clickable, one names an instance that
/// isn't there, the door's last frame calls `nextScene()` in its own script, and a script
/// outside the subset stays kept and unrun.
fn scripted() -> Document {
let mut d = fixture();
let main = "import flash.events.MouseEvent;\n\
trace(\"start\");\n\
knob.addEventListener(MouseEvent.CLICK, openDoor);\n\
knob.addEventListener(MouseEvent.ROLL_OVER, function (e:MouseEvent):void { door.alpha = 0.5; });\n\
knob.addEventListener(MouseEvent.ROLL_OUT, function (e:MouseEvent):void { door.alpha = 1; });\n\
knob.addEventListener(MouseEvent.MOUSE_DOWN, pressed);\n\
knob.addEventListener(MouseEvent.MOUSE_UP, released);\n\
panel.addEventListener(MouseEvent.CLICK, function (e:MouseEvent):void { trace(\"panel \" + 1); MovieClip(e.currentTarget).gotoAndStop(1); e.currentTarget.alpha = 0.75; });\n\
ghost.addEventListener(MouseEvent.CLICK, pressed);\n\
navigateToURL(new URLRequest(\"https://example.com\"));\n\
function openDoor(e:MouseEvent):void { door.gotoAndPlay(\"opening\"); panel.door.play(); }\n\
function pressed(e:MouseEvent):void { trace(\"pressed\"); }\n\
function released(e:MouseEvent):void { MovieClip(root).panel.gotoAndStop(100); }";
let tl = d.timeline_mut(0);
let l1 = Arc::make_mut(&mut tl.layers[0]);
as3(&mut l1.keyframes[0], main);
as3(&mut l1.keyframes[1], "ghost.stop()\npanel.stop()");
as3(&mut l1.keyframes[2], "var n:int = 3; stop();");
let l2 = Arc::make_mut(&mut tl.layers[1]);
if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut Arc::make_mut(&mut l2.keyframes[0]).elements[0]).kind {
events.clear();
}
let door = Arc::make_mut(&mut d.library[0]);
let dl = Arc::make_mut(&mut door.timeline.layers[0]);
as3(&mut dl.keyframes[2], "stop();\ntrace('door open');\nnextScene();");
d
}
#[test]
fn the_js_player_runs_actionscript_like_the_rust_player() {
let doc = scripted();
let m = movie(&doc, &HtmlOptions::default());
assert_eq!(m.report.get(KEPT_SCRIPTS), Some(&1), "{:?}", m.report);
assert_eq!(m.report.get(OUTSIDE_CALLS), Some(&1), "{:?}", m.report);
let none = || (vec![], vec![]);
let mut script: Vec<(Vec<Event>, Vec<Event>)> = (0..2).map(|_| none()).collect();
script.push((vec![Event::Move(at(100.0, 100.0))], vec![]));
script.push((vec![Event::Down(at(101.0, 99.0))], vec![]));
script.push((vec![], vec![Event::Up(at(102.0, 101.0))]));
script.extend((0..6).map(|_| none()));
// Click the panel (a movie clip that a listener made clickable).
script.push((vec![Event::Move(at(380.0, 300.0))], vec![Event::Down(at(380.0, 300.0)), Event::Up(at(380.0, 300.0))]));
script.push((vec![Event::Move(at(10.0, 10.0)), Event::Leave], vec![]));
script.extend((0..30).map(|_| none()));
let lines = compare(&doc, &script);
for want in ["start", "pressed", "door open", "panel 1", "Listen for click (ghost): no instance named “ghost” here", "Stop (ghost): no instance named “ghost” here", "Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"] {
assert!(lines.iter().any(|l| l == want), "the scripted fixture never wrote {want:?}: {lines:?}");
}
}
#[test]
fn actionscript_plays_the_movie_its_hand_made_actions_play() {
// The scripted fixture and the fixture write the same lines and reach the same states, but
// for the lines only scripts write and the listeners they hold.
let (a, b) = (fixture(), scripted());
let events = [vec![], vec![], vec![Event::Move(at(100.0, 100.0))], vec![Event::Down(at(101.0, 99.0))], vec![Event::Up(at(102.0, 101.0))], vec![], vec![], vec![], vec![Event::Move(at(10.0, 10.0))]];
let (mut x, mut y) = (start(&a, &mut NoScripts), start(&b, &mut NoScripts));
let only_scripts = |l: &String| l.starts_with("Listen for") || l.starts_with("Next scene:");
for (i, ev) in events.iter().enumerate() {
x = step(&a, &x.state, ev, &mut NoScripts);
y = step(&b, &y.state, ev, &mut NoScripts);
let ys: Vec<&String> = y.output.iter().filter(|l| !only_scripts(l)).collect();
assert_eq!(x.output.iter().collect::<Vec<_>>(), ys, "step {}: output", i + 1);
let mut st = y.state.clone();
st.listeners.clear();
assert_eq!(x.state, st, "step {}: state", i + 1);
}
}