From 578fd1454057ee59c418f83c6b5a9070462ee668 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:16:56 -0700 Subject: [PATCH 001/192] docs: reserve ADR 0056 for colour effects (M2) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..2dba5749 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0056 | m2/colour-effects | Colour effects: one colour transform for every style | From e64a720a8ece8b2f3df051776e01d527923f88ad Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:42:30 -0700 Subject: [PATCH 002/192] feat(actions): ActionScript small logic: typed variables, expressions, loops, property reads, enter-frame and key listeners (M6) The ActionScript subset compiles to a small typed script IR (statements and expressions) that the player evaluates with a fuel budget, instead of a flat action list. Timeline variables live per instance; functions and variables link across the frames of one timeline; Math.random() is seeded. The HTML canvas player mirrors the evaluator and the parity tests run both. --- crates/actions/src/as3/ir.rs | 812 ++++++++++++++++++ crates/actions/src/as3/lower.rs | 1320 +++++++++++++++++++---------- crates/actions/src/as3/mod.rs | 163 ++-- crates/actions/src/as3/parse.rs | 188 +++- crates/actions/src/as3/run.rs | 528 ++++++++++++ crates/actions/src/as3/tests.rs | 479 ++++++++--- crates/doc/src/player.rs | 549 +++++++++++- crates/doc/src/player_tests.rs | 170 +++- crates/engine/src/cmds_actions.rs | 5 +- crates/engine/src/cmds_script.rs | 51 +- crates/engine/src/player.rs | 93 +- crates/engine/src/tests_script.rs | 45 +- crates/render/src/html.rs | 61 +- crates/render/src/html/canvas.js | 18 +- crates/render/src/html/player.js | 884 ++++++++++++++++++- crates/render/src/html_tests.rs | 108 ++- crates/xfl/src/tests.rs | 3 +- 17 files changed, 4669 insertions(+), 808 deletions(-) create mode 100644 crates/actions/src/as3/ir.rs create mode 100644 crates/actions/src/as3/run.rs diff --git a/crates/actions/src/as3/ir.rs b/crates/actions/src/as3/ir.rs new file mode 100644 index 00000000..eeaac074 --- /dev/null +++ b/crates/actions/src/as3/ir.rs @@ -0,0 +1,812 @@ +//! The script IR (ADR 0013 tier 2.5): a small, typed form of statements and expressions that a +//! compiled script runs as, evaluated by [`super::run`]. It is data, not code: the player (and +//! the HTML canvas player, which reads the same IR as JSON) walks it with a fuel budget. +//! +//! Names are resolved when the script compiles: a function's own variables are numbered slots, +//! the timeline's variables (`var` at the top of a frame script, shared by every frame script +//! of that timeline, as ActionScript 3.0 timelines keep them per instance) are looked up by +//! name, and instances are name paths from a base (the timeline, the stage, or the event's +//! target). Calls to functions go by name to the timeline's functions, so a frame can call a +//! function another frame of the same timeline declares. + +use crate::{FrameRef, Property, Target}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::sync::Arc; + +/// A variable's type: what values written to it are coerced to (ECMA-262 §9, ActionScript 3.0's +/// `int` and `uint` as ToInt32 and ToUint32). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Ty { + /// Untyped (`*`, `Object`, or no annotation): keeps any value. + #[default] + Any, + Number, + Int, + Uint, + Boolean, + String, +} + +impl Ty { + /// The type an annotation names, when it is one scripts can hold. + pub fn from_name(s: &str) -> Option { + Some(match s { + "*" | "Object" => Ty::Any, + "Number" => Ty::Number, + "int" => Ty::Int, + "uint" => Ty::Uint, + "Boolean" => Ty::Boolean, + "String" => Ty::String, + _ => return None, + }) + } + + /// What a variable of this type holds before anything is written to it. + pub fn default_value(self) -> Value { + match self { + Ty::Any => Value::Undefined, + Ty::Number => Value::Num(f64::NAN), + Ty::Int | Ty::Uint => Value::Num(0.0), + Ty::Boolean => Value::Bool(false), + Ty::String => Value::Null, + } + } + + /// `v` as this type. + pub fn coerce(self, v: Value) -> Value { + match self { + Ty::Any => v, + Ty::Number => Value::Num(v.number()), + Ty::Int => Value::Num(f64::from(to_int32(v.number()))), + Ty::Uint => Value::Num(f64::from(to_uint32(v.number()))), + Ty::Boolean => Value::Bool(v.truthy()), + Ty::String => match v { + Value::Null | Value::Undefined => Value::Null, + Value::Str(_) => v, + other => Value::Str(other.text().into()), + }, + } + } +} + +/// ToInt32 (ECMA-262 §9.5). +pub fn to_int32(n: f64) -> i32 { + let u = to_uint32(n); + u as i32 +} + +/// ToUint32 (ECMA-262 §9.6). +pub fn to_uint32(n: f64) -> u32 { + if !n.is_finite() { + return 0; + } + let m = n.trunc().rem_euclid(4_294_967_296.0); + // In 0 .. 2^32 by construction. + if (0.0..4_294_967_296.0).contains(&m) { m as u32 } else { 0 } +} + +/// A value a script computes with: ActionScript's primitive values. +#[derive(Clone, Debug, Default)] +pub enum Value { + #[default] + Undefined, + Null, + Bool(bool), + Num(f64), + Str(Arc), +} + +impl PartialEq for Value { + /// The same value (NaN is NaN): what state comparisons need, not ActionScript's `==`. + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true, + (Value::Bool(a), Value::Bool(b)) => a == b, + (Value::Num(a), Value::Num(b)) => a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan()), + (Value::Str(a), Value::Str(b)) => a == b, + _ => false, + } + } +} + +impl Value { + pub fn str(s: &str) -> Value { + Value::Str(s.into()) + } + + /// ToNumber (ECMA-262 §9.3). + pub fn number(&self) -> f64 { + match self { + Value::Num(n) => *n, + Value::Bool(b) => f64::from(u8::from(*b)), + Value::Null => 0.0, + Value::Undefined => f64::NAN, + Value::Str(s) => string_number(s), + } + } + + /// ToBoolean (§9.2). + pub fn truthy(&self) -> bool { + match self { + Value::Num(n) => *n != 0.0 && !n.is_nan(), + Value::Str(s) => !s.is_empty(), + Value::Bool(b) => *b, + Value::Null | Value::Undefined => false, + } + } + + /// ToString (§9.8). + pub fn text(&self) -> String { + match self { + Value::Num(n) => number_text(*n), + Value::Str(s) => s.to_string(), + Value::Bool(b) => b.to_string(), + Value::Null => "null".into(), + Value::Undefined => "undefined".into(), + } + } + + pub fn is_str(&self) -> bool { + matches!(self, Value::Str(_)) + } +} + +/// The JSON form: `"u"`, `"null"`, `{"b": true}`, `{"n": 1.5}`, `{"s": "text"}`, `"nan"`, +/// `{"inf": false}` (JSON has no NaN or infinities). +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +enum ValueRepr { + U, + Null, + B(bool), + N(f64), + S(String), + Nan, + /// `true`: negative. + Inf(bool), +} + +impl Serialize for Value { + fn serialize(&self, s: S) -> Result { + match self { + Value::Undefined => ValueRepr::U, + Value::Null => ValueRepr::Null, + Value::Bool(b) => ValueRepr::B(*b), + Value::Num(n) if n.is_nan() => ValueRepr::Nan, + Value::Num(n) if n.is_infinite() => ValueRepr::Inf(*n < 0.0), + Value::Num(n) => ValueRepr::N(*n), + Value::Str(t) => ValueRepr::S(t.to_string()), + } + .serialize(s) + } +} + +impl<'de> Deserialize<'de> for Value { + fn deserialize>(d: D) -> Result { + Ok(match ValueRepr::deserialize(d)? { + ValueRepr::U => Value::Undefined, + ValueRepr::Null => Value::Null, + ValueRepr::B(b) => Value::Bool(b), + ValueRepr::N(n) => Value::Num(n), + ValueRepr::S(t) => Value::Str(t.into()), + ValueRepr::Nan => Value::Num(f64::NAN), + ValueRepr::Inf(neg) => Value::Num(if neg { f64::NEG_INFINITY } else { f64::INFINITY }), + }) + } +} + +/// White space and line terminators as ECMAScript trims them from numbers in text. +fn js_space(c: char) -> bool { + matches!(c, '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}') +} + +/// A number written as text (StringToNumber, ECMA-262 §9.3.1 as browsers read it: decimal, +/// `Infinity`, and `0x`/`0o`/`0b` integers), or NaN. +pub fn string_number(s: &str) -> f64 { + let t = s.trim_matches(js_space); + if t.is_empty() { + return 0.0; + } + let radix = |p: &str, r: u32| -> f64 { + if p.is_empty() || !p.chars().all(|c| c.is_digit(r)) { + return f64::NAN; + } + p.chars().filter_map(|c| c.to_digit(r)).fold(0.0, |v, d| v * f64::from(r) + f64::from(d)) + }; + if let Some(p) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) { + return radix(p, 16); + } + if let Some(p) = t.strip_prefix("0o").or_else(|| t.strip_prefix("0O")) { + return radix(p, 8); + } + if let Some(p) = t.strip_prefix("0b").or_else(|| t.strip_prefix("0B")) { + return radix(p, 2); + } + let (neg, body) = match t.as_bytes().first() { + Some(b'-') => (true, t.get(1..).unwrap_or("")), + Some(b'+') => (false, t.get(1..).unwrap_or("")), + _ => (false, t), + }; + if body == "Infinity" { + return if neg { f64::NEG_INFINITY } else { f64::INFINITY }; + } + // digits [. digits] [e[+-]digits], or . digits [e…] + let b = body.as_bytes(); + let mut i = 0; + let digits = |i: &mut usize| { + let from = *i; + while b.get(*i).is_some_and(u8::is_ascii_digit) { + *i += 1; + } + *i - from + }; + let int = digits(&mut i); + let mut frac = 0; + if b.get(i) == Some(&b'.') { + i += 1; + frac = digits(&mut i); + } + if int + frac == 0 { + return f64::NAN; + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + if digits(&mut i) == 0 { + return f64::NAN; + } + } + if i != b.len() { + return f64::NAN; + } + let v: f64 = body.parse().unwrap_or(f64::NAN); + if neg { -v } else { v } +} + +/// A number as ActionScript writes it (`Number.toString()`, ECMA-262 §9.8.1): integers without +/// a point, exponents outside 1e-6 … 1e21. +pub fn number_text(n: f64) -> String { + if n.is_nan() { + return "NaN".into(); + } + if n.is_infinite() { + return if n > 0.0 { "Infinity".into() } else { "-Infinity".into() }; + } + if n == 0.0 { + return "0".into(); + } + let a = n.abs(); + if (1e-6..1e21).contains(&a) { + return format!("{n}"); + } + let s = format!("{n:e}"); + match s.split_once('e') { + Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"), + _ => s, + } +} + +/// Length in UTF-16 units, as ActionScript's `String.length` counts. +pub fn text_len(s: &str) -> usize { + s.encode_utf16().count() +} + +/// Where an instance path starts. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Base { + /// The script's timeline. + #[default] + This, + /// The stage (keyboard listeners live there). + Stage, + /// The event's `target`. + Target, + /// The event's `currentTarget`: the instance (or stage) listened to. + Current, +} + +impl Base { + pub fn is_this(&self) -> bool { + *self == Base::This + } +} + +/// An instance a script names: a base and a name path from it (`hero_mc.arm_mc`, `parent`, +/// `root.menu`). +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Place { + #[serde(default, skip_serializing_if = "Base::is_this")] + pub base: Base, + #[serde(default, skip_serializing_if = "Target::is_this")] + pub path: Target, +} + +impl Place { + pub fn this() -> Place { + Place::default() + } + pub fn named(path: impl Into) -> Place { + Place { base: Base::This, path: Target::new(path) } + } +} + +impl std::fmt::Display for Place { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let base = match self.base { + Base::This => "", + Base::Stage => "stage", + Base::Target => "e.target", + Base::Current => "e.currentTarget", + }; + match (base, self.path.is_this()) { + ("", _) => write!(f, "{}", self.path), + (b, true) => f.write_str(b), + (b, false) => write!(f, "{b}.{}", self.path), + } + } +} + +/// A property a script reads (of an instance or of the timeline). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Prop { + X, + Y, + Alpha, + Visible, + Rotation, + ScaleX, + ScaleY, + /// 1-based, as ActionScript counts frames. + CurrentFrame, + TotalFrames, + /// The label at or before the playhead, or `null`. + CurrentLabel, + /// The pointer in the instance's own space. + MouseX, + MouseY, + /// The instance name. + Name, +} + +impl Prop { + pub fn from_name(s: &str) -> Option { + Some(match s { + "x" => Prop::X, + "y" => Prop::Y, + "alpha" => Prop::Alpha, + "visible" => Prop::Visible, + "rotation" => Prop::Rotation, + "scaleX" => Prop::ScaleX, + "scaleY" => Prop::ScaleY, + "currentFrame" => Prop::CurrentFrame, + "totalFrames" => Prop::TotalFrames, + "currentLabel" => Prop::CurrentLabel, + "mouseX" => Prop::MouseX, + "mouseY" => Prop::MouseY, + "name" => Prop::Name, + _ => return None, + }) + } + pub fn name(self) -> &'static str { + match self { + Prop::X => "x", + Prop::Y => "y", + Prop::Alpha => "alpha", + Prop::Visible => "visible", + Prop::Rotation => "rotation", + Prop::ScaleX => "scaleX", + Prop::ScaleY => "scaleY", + Prop::CurrentFrame => "currentFrame", + Prop::TotalFrames => "totalFrames", + Prop::CurrentLabel => "currentLabel", + Prop::MouseX => "mouseX", + Prop::MouseY => "mouseY", + Prop::Name => "name", + } + } + /// The instance property a script may also set. + pub fn settable(self) -> Option { + Some(match self { + Prop::X => Property::X, + Prop::Y => Property::Y, + Prop::Alpha => Property::Alpha, + Prop::Visible => Property::Visible, + Prop::Rotation => Property::Rotation, + Prop::ScaleX => Property::ScaleX, + Prop::ScaleY => Property::ScaleY, + _ => return None, + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UnOp { + Neg, + Plus, + Not, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BinOp { + Add, + Sub, + Mul, + Div, + Mod, + Lt, + Gt, + Le, + Ge, + Eq, + Ne, + StrictEq, + StrictNe, +} + +impl BinOp { + pub fn from_token(s: &str) -> Option { + Some(match s { + "+" => BinOp::Add, + "-" => BinOp::Sub, + "*" => BinOp::Mul, + "/" => BinOp::Div, + "%" => BinOp::Mod, + "<" => BinOp::Lt, + ">" => BinOp::Gt, + "<=" => BinOp::Le, + ">=" => BinOp::Ge, + "==" => BinOp::Eq, + "!=" => BinOp::Ne, + "===" => BinOp::StrictEq, + "!==" => BinOp::StrictNe, + _ => return None, + }) + } +} + +/// `Math` functions scripts may call. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MathFn { + Min, + Max, + Abs, + Floor, + Ceil, + Round, + /// From the player's seeded generator: the same movie and events give the same numbers. + Random, +} + +impl MathFn { + pub fn from_name(s: &str) -> Option { + Some(match s { + "min" => MathFn::Min, + "max" => MathFn::Max, + "abs" => MathFn::Abs, + "floor" => MathFn::Floor, + "ceil" => MathFn::Ceil, + "round" => MathFn::Round, + "random" => MathFn::Random, + _ => return None, + }) + } + /// How many arguments it takes (`None`: any number). + pub fn arity(self) -> Option { + match self { + MathFn::Min | MathFn::Max => None, + MathFn::Random => Some(0), + MathFn::Abs | MathFn::Floor | MathFn::Ceil | MathFn::Round => Some(1), + } + } +} + +/// What an assignment writes to. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "k", rename_all = "snake_case")] +pub enum LValue { + /// A function's own variable (or parameter). + Local { i: u16 }, + /// A variable of the timeline. + Var { n: String }, + /// An instance property. + Prop { at: Place, p: Property }, +} + +/// An expression. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "e", rename_all = "snake_case")] +pub enum Expr { + Lit { v: Value }, + Local { i: u16 }, + Var { n: String }, + Get { at: Place, p: Prop }, + /// The keyboard event's `keyCode`. + Key, + /// The event a listener handles, passed on to a function's event parameter. + Event, + Un { op: UnOp, x: Box }, + Bin { op: BinOp, a: Box, b: Box }, + /// `a && b`, `a || b` (the operand's value, as ECMAScript gives it). + And { a: Box, b: Box }, + Or { a: Box, b: Box }, + Cond { c: Box, a: Box, b: Box }, + Math { f: MathFn, args: Vec }, + /// A call to a function of the timeline, by name. + Call { f: String, args: Vec }, + /// Whether two names are the same instance (`e.currentTarget == btn_a`); `ne` negates. + Same { a: Place, b: Place, ne: bool }, + /// `to = v` or `to op= v`; its value is what was written. + Set { to: LValue, op: Option, v: Box }, + /// `++` / `--` (`d` is +1 or -1); `post`: the value before. + Step { to: LValue, d: i8, post: bool }, + /// `int(x)`, `Number(x)`, `String(x)`, `Boolean(x)`, `uint(x)`. + Cast { t: Ty, x: Box }, +} + +impl Expr { + pub fn lit(v: Value) -> Expr { + Expr::Lit { v } + } +} + +/// A timeline method. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Method { + Stop, + Play, + GotoAndPlay, + GotoAndStop, + NextFrame, + PrevFrame, + NextScene, + PrevScene, +} + +impl Method { + pub fn from_name(s: &str) -> Option { + Some(match s { + "stop" => Method::Stop, + "play" => Method::Play, + "gotoAndPlay" => Method::GotoAndPlay, + "gotoAndStop" => Method::GotoAndStop, + "nextFrame" => Method::NextFrame, + "prevFrame" => Method::PrevFrame, + "nextScene" => Method::NextScene, + "prevScene" => Method::PrevScene, + _ => return None, + }) + } + pub fn name(self) -> &'static str { + match self { + Method::Stop => "stop", + Method::Play => "play", + Method::GotoAndPlay => "gotoAndPlay", + Method::GotoAndStop => "gotoAndStop", + Method::NextFrame => "nextFrame", + Method::PrevFrame => "prevFrame", + Method::NextScene => "nextScene", + Method::PrevScene => "prevScene", + } + } + /// The action it is, at a frame (go-tos) and scene. + pub fn action(self, target: Target, frame: FrameRef, scene: Option) -> crate::Action { + use crate::Action as A; + match self { + Method::Stop => A::Stop { target }, + Method::Play => A::Play { target }, + Method::GotoAndPlay => A::GotoAndPlay { target, frame, scene }, + Method::GotoAndStop => A::GotoAndStop { target, frame, scene }, + Method::NextFrame => A::NextFrame { target }, + Method::PrevFrame => A::PrevFrame { target }, + Method::NextScene => A::NextScene, + Method::PrevScene => A::PrevScene, + } + } +} + +/// An event a listener waits for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ListenEvent { + Click, + Press, + Release, + Over, + Out, + /// `Event.ENTER_FRAME`: every frame, playing or not. + EnterFrame, + /// `KeyboardEvent.KEY_DOWN` / `KEY_UP` on the stage. + KeyDown, + KeyUp, +} + +impl ListenEvent { + pub fn key(self) -> &'static str { + match self { + ListenEvent::Click => "click", + ListenEvent::Press => "press", + ListenEvent::Release => "release", + ListenEvent::Over => "over", + ListenEvent::Out => "out", + ListenEvent::EnterFrame => "enter_frame", + ListenEvent::KeyDown => "key_down", + ListenEvent::KeyUp => "key_up", + } + } + /// The pointer event it is, for mouse listeners. + pub fn mouse(self) -> Option { + use crate::ButtonEvent as B; + Some(match self { + ListenEvent::Click => B::Click, + ListenEvent::Press => B::Press, + ListenEvent::Release => B::Release, + ListenEvent::Over => B::Over, + ListenEvent::Out => B::Out, + _ => return None, + }) + } + pub fn from_mouse(b: crate::ButtonEvent) -> ListenEvent { + use crate::ButtonEvent as B; + match b { + B::Click => ListenEvent::Click, + B::Press => ListenEvent::Press, + B::Release => ListenEvent::Release, + B::Over => ListenEvent::Over, + B::Out => ListenEvent::Out, + } + } + pub fn is_key(self) -> bool { + matches!(self, ListenEvent::KeyDown | ListenEvent::KeyUp) + } +} + +/// The function a listener runs. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FuncRef { + /// A function of the timeline, by name. + Named(String), + /// A function written in place: the index in the enclosing code's `inner` list. + Inline(u16), +} + +/// A statement, with the line it starts on (for messages). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Stmt { + pub l: u32, + #[serde(flatten)] + pub s: S, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "s", rename_all = "snake_case")] +pub enum S { + /// An expression for its effect. + Do { x: Expr }, + If { c: Expr, a: Vec, b: Vec }, + /// `while (c)`, `for (; c; next)` (`first`: the condition is tested before the body) and + /// `do … while (c)`. + Loop { + c: Option, + body: Vec, + next: Option, + first: bool, + }, + Break, + Continue, + Return { v: Option }, + /// A timeline method on an instance; `args` are the frame and the scene, when it takes them. + Act { at: Place, m: Method, args: Vec }, + Trace { args: Vec }, + /// `addEventListener` (`add`) or `removeEventListener`. + Listen { at: Place, ev: ListenEvent, f: FuncRef, add: bool }, +} + +/// A parameter. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Param { + pub t: Ty, + /// The value when a call leaves it out. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub d: Option, + /// It is the event (typed `…Event`): its fields read the event the listener handles. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub ev: bool, +} + +/// A function: its parameters, its own variables (parameters first, each slot's type), what it +/// returns and its body. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Function { + pub name: String, + pub line: u32, + pub params: Vec, + pub locals: Vec, + /// `None`: `void`, or no result. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ret: Option, + pub body: Vec, + /// Functions written in place inside it (listeners). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub inner: Vec>, +} + +impl Function { + /// Whether the function's first parameter takes an event (it can be a listener). + pub fn takes_event(&self) -> bool { + let required = self.params.iter().filter(|p| p.d.is_none()).count(); + required <= 1 && self.params.first().is_some_and(|p| p.ev || p.t == Ty::Any) + } +} + +/// The keyboard key codes ActionScript names (`Keyboard.LEFT`, …): the public `flash.ui.Keyboard` +/// constants scripts compare `e.keyCode` with. +pub fn key_code(name: &str) -> Option { + let one = |s: &str| { + let mut c = s.chars(); + match (c.next(), c.next()) { + (Some(ch), None) => Some(ch), + _ => None, + } + }; + if let Some(c) = one(name).filter(char::is_ascii_uppercase) { + return Some(u32::from(c)); + } + if let Some(d) = name.strip_prefix("NUMBER_").and_then(one).and_then(|c| c.to_digit(10)) { + return Some(48 + d); + } + if let Some(d) = name.strip_prefix("NUMPAD_").and_then(one).and_then(|c| c.to_digit(10)) { + return Some(96 + d); + } + if let Some(n) = name.strip_prefix('F').and_then(|n| n.parse::().ok()).filter(|n| (1..=15).contains(n)) { + return Some(111 + n); + } + Some(match name { + "BACKSPACE" => 8, + "TAB" => 9, + "ENTER" => 13, + "SHIFT" => 16, + "CONTROL" => 17, + "ALTERNATE" => 18, + "CAPS_LOCK" => 20, + "ESCAPE" => 27, + "SPACE" => 32, + "PAGE_UP" => 33, + "PAGE_DOWN" => 34, + "END" => 35, + "HOME" => 36, + "LEFT" => 37, + "UP" => 38, + "RIGHT" => 39, + "DOWN" => 40, + "INSERT" => 45, + "DELETE" => 46, + "NUMPAD_MULTIPLY" => 106, + "NUMPAD_ADD" => 107, + "NUMPAD_ENTER" => 108, + "NUMPAD_SUBTRACT" => 109, + "NUMPAD_DECIMAL" => 110, + "NUMPAD_DIVIDE" => 111, + "SEMICOLON" => 186, + "EQUAL" => 187, + "COMMA" => 188, + "MINUS" => 189, + "PERIOD" => 190, + "SLASH" => 191, + "BACKQUOTE" => 192, + "LEFTBRACKET" => 219, + "BACKSLASH" => 220, + "RIGHTBRACKET" => 221, + "QUOTE" => 222, + _ => return None, + }) +} diff --git a/crates/actions/src/as3/lower.rs b/crates/actions/src/as3/lower.rs index 6597f57a..a8519622 100644 --- a/crates/actions/src/as3/lower.rs +++ b/crates/actions/src/as3/lower.rs @@ -1,116 +1,71 @@ -//! Lowering: the syntax tree to the action IR. It accepts only what it can say exactly in the -//! IR and reports everything else where it is, so a script either runs whole or not at all. +//! Lowering: the syntax tree to the script IR ([`super::ir`]). It accepts what the IR can say +//! exactly and reports everything else where it is, so a script either compiles whole or +//! doesn't run at all. Names resolve here: a function's own variables become numbered slots, +//! the timeline's variables and functions are named (those another frame declares are listed +//! as [`Free`] names, which the timeline must have for the script to run), and instances become +//! name paths from a base. -use super::parse::{E, Expr, Func, S, Stmt}; -use super::{Compiled, Listener, MAX_INLINE_DEPTH, MAX_LISTENERS, MAX_PROBLEMS, Pos, Problem, ScriptOp}; -use crate::{Action, ButtonEvent, FrameRef, MAX_ACTIONS, MAX_FRAME, MAX_LABEL_CHARS, MAX_TRACE_CHARS, Property, Target, valid_instance_name}; -use std::collections::BTreeMap; +use super::ir::{self, Base, BinOp, Expr as X, FuncRef, Function, LValue, ListenEvent, MathFn, Method, Param as IrParam, Place, Prop, S as IS, Stmt as IStmt, Ty, UnOp, Value}; +use super::parse::{E, Expr, Func, S, Stmt, VarDecl}; +use super::{Compiled, Free, MAX_LISTENERS, MAX_PROBLEMS, Pos, Problem}; +use crate::{MAX_FRAME, MAX_LABEL_CHARS, Target, valid_instance_name}; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; -/// The timeline methods a script may call (on this timeline or on a named instance). -const METHODS: [&str; 8] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene"]; /// Names a script's own function can't take: they would hide the timeline's methods. -const BUILTINS: [&str; 11] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene", "trace", "addEventListener", "removeEventListener"]; +const BUILTINS: [&str; 12] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene", "trace", "addEventListener", "removeEventListener", "getChildByName"]; /// Calls that would reach outside the movie: ignored, and noted. const OUTSIDE: [&str; 4] = ["navigateToURL", "sendToURL", "fscommand", "fsCommand"]; /// Type casts that leave an instance path as it is (`MovieClip(parent)`). const CASTS: [&str; 7] = ["MovieClip", "Object", "Sprite", "DisplayObject", "DisplayObjectContainer", "InteractiveObject", "SimpleButton"]; +/// Names that are classes, not values. +const CLASSES: [&str; 6] = ["Math", "Keyboard", "MouseEvent", "Event", "KeyboardEvent", "ExternalInterface"]; +/// Names that are always the path words. +const PATH_WORDS: [&str; 3] = ["root", "parent", "stage"]; -/// A constant value, as ActionScript computes it. -#[derive(Clone, Debug, PartialEq)] -enum Val { - Num(f64), - Str(String), - Bool(bool), - Null, - Undefined, -} - -impl Val { - fn number(&self) -> f64 { - match self { - Val::Num(n) => *n, - Val::Bool(b) => f64::from(u8::from(*b)), - Val::Null => 0.0, - Val::Undefined => f64::NAN, - Val::Str(s) => { - // ECMA-262 §9.3.1: a decimal number with optional sign and exponent (Rust would - // also read "inf" and "nan"). - let t = s.trim(); - match t.trim_start_matches(['+', '-']) { - "" if t.is_empty() => 0.0, - "Infinity" => if t.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY }, - u if u.chars().all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-')) => t.parse().unwrap_or(f64::NAN), - _ => f64::NAN, - } - } - } - } - - fn text(&self) -> String { - match self { - Val::Num(n) => number_text(*n), - Val::Str(s) => s.clone(), - Val::Bool(b) => b.to_string(), - Val::Null => "null".into(), - Val::Undefined => "undefined".into(), - } +/// A type annotation as a script variable's type, or why it can't be one. `…Event` types are +/// events (`Ok(None)`). +fn var_type(ty: &Option<(String, Pos)>) -> Result, (Pos, String)> { + match ty { + None => Ok(Some(Ty::Any)), + Some((t, _)) if t.ends_with("Event") => Ok(None), + Some((t, p)) => Ty::from_name(t).map(Some).ok_or_else(|| (*p, format!("variables of type `{t}` aren't supported yet (Number, int, uint, Boolean, String and untyped ones are)"))), } } -/// A number as ActionScript writes it (`Number.toString()`, ECMA-262 §9.8.1): integers without -/// a point, exponents outside 1e-6 … 1e21. -pub(super) fn number_text(n: f64) -> String { - if n.is_nan() { - return "NaN".into(); - } - if n.is_infinite() { - return if n > 0.0 { "Infinity".into() } else { "-Infinity".into() }; - } - if n == 0.0 { - return "0".into(); - } - let a = n.abs(); - if (1e-6..1e21).contains(&a) { - return format!("{n}"); - } - let s = format!("{n:e}"); - match s.split_once('e') { - Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"), - _ => s, - } -} - -/// Where lowering is. -#[derive(Clone, Default)] -struct Cx { - /// Inside a listener's function: its event parameter and the instance it listens on (what - /// `e.currentTarget` is). - event: Option<(String, Vec)>, - /// Inside a listener (or a function it calls): listeners can't be added there yet. - in_listener: bool, - /// Inside a function body (functions can't be declared there). +/// What lowering a function's (or the script's top level's) code knows. +struct Unit { + /// The function's own variables: slot and type. + locals: BTreeMap, + types: Vec, + /// Its parameters that are the event. + events: BTreeSet, in_function: bool, - /// The parameters of the function being lowered (they can't be read). - params: Vec, - /// The script's functions being lowered, innermost last (to refuse recursion). - stack: Vec, + /// Loops it is inside (for `break` and `continue`). + loops: usize, + /// Functions written in place inside it. + inner: Vec>, +} + +impl Unit { + fn top() -> Unit { + Unit { locals: BTreeMap::new(), types: Vec::new(), events: BTreeSet::new(), in_function: false, loops: 0, inner: Vec::new() } + } } struct Lower<'a> { funcs: BTreeMap<&'a str, &'a Func>, + /// The script's top-level variables (the timeline's). + vars: BTreeMap, problems: Vec, notes: Vec, + free: Vec, listeners: usize, - /// Statements lowered so far, counting each inlined copy (calls can fan out). - work: usize, + /// Functions being lowered (inline listeners nest). + depth: usize, } -/// Most statements lowered for one script, inlined copies included. -const MAX_WORK: usize = 100_000; - -/// Whether the statement list ended in a `return`. -type Returned = bool; +type O = Option; impl<'a> Lower<'a> { fn problem(&mut self, pos: Pos, msg: impl Into) { @@ -125,444 +80,887 @@ impl<'a> Lower<'a> { } } - fn stmts(&mut self, list: &'a [Stmt], cx: &Cx, out: &mut Vec) -> Returned { - for s in list { - if self.stmt(s, cx, out) { - return true; - } + fn free(&mut self, name: &str, pos: Pos, call: bool) { + if !self.free.iter().any(|f| f.name == name && f.call == call) && self.free.len() < 1024 { + self.free.push(Free { name: name.to_string(), line: pos.line, column: pos.column, call }); } - false } - fn stmt(&mut self, s: &'a Stmt, cx: &Cx, out: &mut Vec) -> Returned { - self.work += 1; - if self.work > MAX_WORK { - if self.work == MAX_WORK + 1 { - self.problem(s.pos, format!("the script's functions call each other into more than {MAX_WORK} statements")); - } - return true; + // ----- statements ---------------------------------------------------------------------- + + fn stmts(&mut self, list: &'a [Stmt], u: &mut Unit, out: &mut Vec) { + for s in list { + self.stmt(s, u, out); } + } + + fn body(&mut self, list: &'a [Stmt], u: &mut Unit) -> Vec { + let mut out = Vec::new(); + self.stmts(list, u, &mut out); + out + } + + fn stmt(&mut self, s: &'a Stmt, u: &mut Unit, out: &mut Vec) { + let l = s.pos.line; + let push = |out: &mut Vec, s: IS| out.push(IStmt { l, s }); match &s.kind { S::Empty | S::Import => {} // Declared functions run where they are called or listened for. S::Function(_) => { - if cx.in_function { + if u.in_function { self.problem(s.pos, "functions declared inside functions aren't supported yet"); } } - S::Block(b) => return self.stmts(b, cx, out), - S::Var(w) => self.problem(s.pos, format!("variables (`{w}`) aren't supported yet")), - S::If(..) => self.problem(s.pos, "`if` statements aren't supported yet"), + S::Block(b) => self.stmts(b, u, out), + S::Var(_, list) => self.var_stmt(list, u, out, l), + S::If(c, a, b) => { + let Some(c) = self.expr(c, u) else { return }; + let a = self.body(a, u); + let b = self.body(b, u); + push(out, IS::If { c, a, b }); + } + S::For(init, c, next, body) => { + if let Some(init) = init { + self.stmt(init, u, out); + } + let c = c.as_ref().and_then(|c| self.expr(c, u)); + let next = next.as_ref().and_then(|n| self.expr(n, u)); + u.loops += 1; + let body = self.body(body, u); + u.loops -= 1; + push(out, IS::Loop { c, body, next, first: true }); + } + S::While(c, body) | S::DoWhile(body, c) => { + let first = matches!(s.kind, S::While(..)); + let c = self.expr(c, u); + u.loops += 1; + let body = self.body(body, u); + u.loops -= 1; + push(out, IS::Loop { c, body, next: None, first }); + } + S::Break | S::Continue => { + if u.loops == 0 { + let w = if matches!(s.kind, S::Break) { "break" } else { "continue" }; + return self.problem(s.pos, format!("`{w}` is only for loops here")); + } + push(out, if matches!(s.kind, S::Break) { IS::Break } else { IS::Continue }); + } S::Other(w, _) => { let what = match *w { - "for" | "while" | "do" => format!("`{w}` loops aren't supported yet"), + "for each" | "for in" => format!("`{w}` loops aren't supported yet (`for`, `while` and `do` are)"), + "labelled break" => "labels on `break` and `continue` aren't supported".to_string(), _ => format!("`{w}` statements aren't supported yet"), }; self.problem(s.pos, what); } - S::Return(None) => return true, - S::Return(Some(e)) => { - if self.constant(e, cx).is_err() { - self.problem(e.pos, "returning a value isn't supported"); - } - return true; + S::Return(e) => { + let v = match e { + Some(e) => match self.expr(e, u) { + Some(v) => Some(v), + None => return, + }, + None => None, + }; + push(out, IS::Return { v }); } - S::Expr(e) => self.expr_stmt(e, cx, out), + S::Expr(e) => self.expr_stmt(e, u, out, l), } - false } - fn expr_stmt(&mut self, e: &'a Expr, cx: &Cx, out: &mut Vec) { + fn var_stmt(&mut self, list: &'a [VarDecl], u: &mut Unit, out: &mut Vec, l: u32) { + for d in list { + let Some(init) = &d.init else { continue }; + let to = if u.in_function { + match u.locals.get(&d.name) { + Some((i, _)) => LValue::Local { i: *i }, + None => continue, + } + } else { + LValue::Var { n: d.name.clone() } + }; + let Some(v) = self.expr(init, u) else { continue }; + out.push(IStmt { l, s: IS::Do { x: X::Set { to, op: None, v: Box::new(v) } } }); + } + } + + fn expr_stmt(&mut self, e: &'a Expr, u: &mut Unit, out: &mut Vec, l: u32) { match &e.kind { - E::Call(callee, args) => self.call(e.pos, callee, args, cx, out), - E::Assign("=", lhs, rhs) => self.assign(e.pos, lhs, rhs, cx, out), - E::Assign(op, _, _) => self.problem(e.pos, format!("`{op}` reads a value first; only `=` with a value is supported")), + E::Call(callee, args) => { + if let Some(s) = self.call_stmt(e.pos, callee, args, u) { + out.push(IStmt { l, s }); + } + } E::Comma(list) => { for x in list { - self.expr_stmt(x, cx, out); + self.expr_stmt(x, u, out, l); } } // A literal alone does nothing (`"use strict"`). E::Num(_) | E::Str(_) | E::Bool(_) | E::Null => {} - E::Unary("++" | "--", _) | E::Postfix(..) => self.problem(e.pos, "`++` and `--` read a value first and aren't supported"), - _ => self.problem(e.pos, "only calls (such as `stop()`) and settings (such as `hero_mc.x = 10`) run as statements"), + E::Assign(_, lhs, _) if matches!(&lhs.kind, E::Member(_, p) if p == "buttonMode" || p == "useHandCursor") => { + let E::Member(_, p) = &lhs.kind else { return }; + self.note(e.pos, format!("`{p}` is ignored: the pointer is a hand over everything clickable here")); + } + _ => { + if let Some(x) = self.expr(e, u) { + out.push(IStmt { l, s: IS::Do { x } }); + } + } } } - fn call(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], cx: &Cx, out: &mut Vec) { + /// A call as a statement: timeline methods, `trace`, listeners, and any call with a value. + fn call_stmt(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], u: &mut Unit) -> O { match &callee.kind { - E::Name(n) => { + E::Name(n) if !u.locals.contains_key(n) => { let n = n.as_str(); - if let Some(f) = self.funcs.get(n).copied() { - return self.inline(pos, f, args, cx, out); + if self.funcs.contains_key(n) { + return self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }); } match n { - "trace" => self.trace(pos, args, cx, out), - "addEventListener" => self.listen(pos, Vec::new(), args, cx, out), - n if METHODS.contains(&n) => self.method(pos, Vec::new(), n, args, cx, out), - n if OUTSIDE.contains(&n) => self.note(pos, format!("`{n}` is ignored: a movie here can't open web pages or reach outside itself")), - "removeEventListener" => self.problem(pos, "removing listeners isn't supported yet"), - n if CASTS.contains(&n) => self.problem(pos, format!("`{n}(…)` alone does nothing; call a method on it, as in `{n}(parent).play()`")), - n => self.problem(pos, format!("`{n}` isn't declared in this frame script (functions from other frames, and the rest of the language, aren't supported yet)")), + "trace" => { + let args = self.args(args, u)?; + Some(IS::Trace { args }) + } + "addEventListener" | "removeEventListener" => self.listen(pos, Place::this(), args, n == "addEventListener", u), + n if Method::from_name(n).is_some() => self.method(pos, Place::this(), n, args, u), + n if OUTSIDE.contains(&n) => { + self.note(pos, format!("`{n}` is ignored: a movie here can't open web pages or reach outside itself")); + None + } + n if CASTS.contains(&n) => { + self.problem(pos, format!("`{n}(…)` alone does nothing; call a method on it, as in `{n}(parent).play()`")); + None + } + _ => self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }), } } E::Member(obj, m) => { let m = m.as_str(); if OUTSIDE.contains(&m) || (matches!(&obj.kind, E::Name(o) if o == "ExternalInterface") && matches!(m, "call" | "addCallback")) { - return self.note(pos, format!("`{m}` is ignored: a movie here can't open web pages or reach outside itself")); + self.note(pos, format!("`{m}` is ignored: a movie here can't open web pages or reach outside itself")); + return None; } - let known = METHODS.contains(&m) || m == "addEventListener"; - if !known { - let msg = if m == "removeEventListener" { "removing listeners isn't supported yet".to_string() } else { format!("calling `{m}` isn't supported (timeline methods such as `play()` and `gotoAndStop()`, and `addEventListener`, are)") }; - return self.problem(pos, msg); + if matches!(&obj.kind, E::Name(o) if o == "Math") { + return self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }); + } + if Method::from_name(m).is_none() && m != "addEventListener" && m != "removeEventListener" { + self.problem(pos, format!("calling `{m}` isn't supported (timeline methods such as `play()` and `gotoAndStop()`, `addEventListener` and `removeEventListener` are)")); + return None; + } + let at = self.place(obj, u)?; + match m { + "addEventListener" | "removeEventListener" => self.listen(pos, at, args, m == "addEventListener", u), + _ => self.method(pos, at, m, args, u), } - let Some(t) = self.target(obj, cx) else { return }; - if m == "addEventListener" { self.listen(pos, t, args, cx, out) } else { self.method(pos, t, m, args, cx, out) } } - _ => self.problem(pos, "only named functions and methods can be called"), + _ => self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }), } } - /// A call to one of the script's own functions: its body runs in place. - fn inline(&mut self, pos: Pos, f: &'a Func, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - let name = f.name.clone().unwrap_or_default(); - if cx.stack.contains(&name) { - return self.problem(pos, format!("`{name}` calls itself; recursion isn't supported")); - } - if cx.stack.len() >= MAX_INLINE_DEPTH { - return self.problem(pos, format!("functions call each other more than {MAX_INLINE_DEPTH} deep")); - } - // Arguments are passed but never read (a parameter read is reported in the body). + fn args(&mut self, args: &'a [Expr], u: &mut Unit) -> O> { + let mut out = Vec::with_capacity(args.len()); + let mut ok = true; for a in args { - let passes_event = matches!((&a.kind, &cx.event), (E::Name(n), Some((e, _))) if n == e); - if !passes_event && self.constant(a, cx).is_err() { - self.problem(a.pos, "arguments are values or the event; computing them isn't supported"); + match self.expr(a, u) { + Some(x) => out.push(x), + None => ok = false, } } - if args.len() < f.params.iter().filter(|p| !p.default && !p.rest).count() { - return self.problem(pos, format!("`{name}` needs more arguments than this call passes")); - } - let mut inner = Cx { event: None, in_listener: cx.in_listener, in_function: true, params: f.params.iter().map(|p| p.name.clone()).collect(), stack: cx.stack.clone() }; - inner.stack.push(name); - self.stmts(&f.body, &inner, out); + ok.then_some(out) } - fn trace(&mut self, pos: Pos, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - let mut parts = Vec::new(); - for a in args { - match self.constant(a, cx) { - Ok(v) => parts.push(v.text()), - Err(p) => return self.problems.push(p), - } + /// A timeline method on the instance at `at`. + fn method(&mut self, pos: Pos, at: Place, m: &str, args: &'a [Expr], u: &mut Unit) -> O { + let method = Method::from_name(m)?; + let takes = matches!(method, Method::GotoAndPlay | Method::GotoAndStop); + if !takes && !args.is_empty() { + self.problem(pos, format!("`{m}()` takes no arguments")); + return None; } - let message = parts.join(" "); - if message.chars().count() > MAX_TRACE_CHARS { - return self.problem(pos, format!("a trace message is at most {MAX_TRACE_CHARS} characters")); + if matches!(method, Method::NextScene | Method::PrevScene) && (!at.path.is_this() || !at.base.is_this()) { + // Scenes belong to the main timeline; on this timeline the player checks that it is + // the main one (a movie clip has no other scenes). + self.problem(pos, format!("call `{m}()` in the main timeline's own script: scenes belong to the main timeline")); + return None; } - out.push(ScriptOp::Action(Action::Trace { message })); - } - - /// A timeline method on the instance at `path`. - fn method(&mut self, pos: Pos, path: Vec, m: &str, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - let Some(target) = self.path(pos, &path) else { return }; - let none = |l: &mut Self| { - if args.is_empty() { - true - } else { - l.problem(pos, format!("`{m}()` takes no arguments")); - false - } - }; - let action = match m { - "stop" if none(self) => Action::Stop { target }, - "play" if none(self) => Action::Play { target }, - "nextFrame" if none(self) => Action::NextFrame { target }, - "prevFrame" if none(self) => Action::PrevFrame { target }, - "nextScene" | "prevScene" => { - if !none(self) { - return; + if takes && (args.is_empty() || args.len() > 2) { + self.problem(pos, format!("`{m}` takes a frame, and optionally a scene")); + return None; + } + // Frames and scenes written out are checked now; computed ones when they run. + if let Some(f) = args.first() { + match &f.kind { + E::Num(n) if !(n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(n)) => { + self.problem(f.pos, format!("a frame number is a whole number from 1 to {}", u64::from(MAX_FRAME) + 1)); + return None; } - // Scenes belong to the main timeline; on this timeline the player checks that - // it is the main one (a movie clip has no other scenes). - if !target.is_this() { - return self.problem(pos, format!("call `{m}()` in the main timeline's own script: scenes belong to the main timeline")); + E::Str(s) if !label_ok(s) => { + self.problem(f.pos, format!("a frame label is 1 to {MAX_LABEL_CHARS} printable characters")); + return None; } - if m == "nextScene" { Action::NextScene } else { Action::PrevScene } + E::Bool(_) | E::Null => { + self.problem(f.pos, "the frame is a number or a label"); + return None; + } + _ => {} } - "gotoAndPlay" | "gotoAndStop" => { - let (Some(f), true) = (args.first(), args.len() <= 2) else { - return self.problem(pos, format!("`{m}` takes a frame, and optionally a scene")); - }; - let frame = match self.constant(f, cx) { - Ok(Val::Num(n)) if n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(&n) => FrameRef::Number(n as u32 - 1), - Ok(Val::Num(_)) => return self.problem(f.pos, format!("a frame number is a whole number from 1 to {}", u64::from(MAX_FRAME) + 1)), - Ok(Val::Str(s)) if label_ok(&s) => FrameRef::Label(s), - Ok(Val::Str(_)) => return self.problem(f.pos, format!("a frame label is 1 to {MAX_LABEL_CHARS} printable characters")), - Ok(_) => return self.problem(f.pos, "the frame is a number or a label"), - Err(p) => return self.problems.push(p), - }; - let scene = match args.get(1).map(|s| (s.pos, self.constant(s, cx))) { - None | Some((_, Ok(Val::Null | Val::Undefined))) => None, - Some((_, Ok(Val::Str(s)))) if label_ok(&s) => Some(s), - Some((p, Ok(_))) => return self.problem(p, "the scene is its name, as a string"), - Some((_, Err(p))) => return self.problems.push(p), - }; - if m == "gotoAndPlay" { Action::GotoAndPlay { target, frame, scene } } else { Action::GotoAndStop { target, frame, scene } } - } - _ => return, - }; - out.push(ScriptOp::Action(action)); - } - - /// `target.addEventListener(event, function)`. - fn listen(&mut self, pos: Pos, path: Vec, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - if cx.in_listener { - return self.problem(pos, "adding a listener from inside a listener isn't supported yet"); } - let Some(target) = self.path(pos, &path) else { return }; - let (Some(ev), Some(handler), true) = (args.first(), args.get(1), args.len() <= 5) else { - return self.problem(pos, "`addEventListener` takes an event and a function"); - }; - let Some(event) = self.event(ev) else { return }; - if let Some(c) = args.get(2) - && !matches!(self.constant(c, cx), Ok(Val::Bool(false) | Val::Null | Val::Undefined)) + if let Some(s) = args.get(1) + && (matches!(&s.kind, E::Num(_) | E::Bool(_)) || matches!(&s.kind, E::Str(t) if !label_ok(t))) { - return self.problem(c.pos, "capture-phase listeners (`useCapture`) aren't supported"); + self.problem(s.pos, "the scene is its name, as a string"); + return None; + } + let args = self.args(args, u)?; + Some(IS::Act { at, m: method, args }) + } + + /// `at.addEventListener(event, function)` (or `removeEventListener`). + fn listen(&mut self, pos: Pos, at: Place, args: &'a [Expr], add: bool, u: &mut Unit) -> O { + let verb = if add { "addEventListener" } else { "removeEventListener" }; + let (Some(ev), Some(handler), true) = (args.first(), args.get(1), args.len() <= if add { 5 } else { 3 }) else { + self.problem(pos, format!("`{verb}` takes an event and a function")); + return None; + }; + let event = self.event(ev)?; + if let Some(c) = args.get(2) + && !matches!(c.kind, E::Bool(false) | E::Null) + { + self.problem(c.pos, "capture-phase listeners (`useCapture`) aren't supported"); + return None; } for extra in args.iter().skip(3) { - if self.constant(extra, cx).is_err() { - return self.problem(extra.pos, "listener priority and weak references are values"); + if !matches!(extra.kind, E::Num(_) | E::Bool(_) | E::Null) { + self.problem(extra.pos, "listener priority and weak references are values"); + return None; } } - let (f, function) = match &handler.kind { - E::Name(n) => match self.funcs.get(n.as_str()).copied() { - Some(f) => (f, n.clone()), - None => return self.problem(handler.pos, format!("`{n}` isn't a function declared in this frame script")), - }, - E::Function(f) => (&**f, format!("function at line {}", f.pos.line)), - _ => return self.problem(handler.pos, "the listener is a function declared in this frame script, or written in place"), + if event.is_key() && at.base != Base::Stage { + self.note(pos, "keys go to the stage here: listen with `stage.addEventListener(KeyboardEvent.KEY_DOWN, …)`; this listener is ignored"); + return None; + } + if at.base == Base::Stage && event.mouse().is_some() { + self.problem(pos, "mouse listeners on the stage aren't supported yet (on buttons and movie clips they are)"); + return None; + } + let f = match &handler.kind { + E::Name(n) if !u.locals.contains_key(n) => { + match self.funcs.get(n.as_str()).copied() { + Some(f) => { + if !takes_event(f) { + self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); + return None; + } + } + None if CLASSES.contains(&n.as_str()) || BUILTINS.contains(&n.as_str()) => { + self.problem(handler.pos, format!("`{n}` isn't a function declared in a frame script")); + return None; + } + None => self.free(n, handler.pos, true), + } + FuncRef::Named(n.clone()) + } + E::Function(f) if add => { + if !takes_event(f) { + self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); + return None; + } + let name = format!("function at line {}, column {}", f.pos.line, f.pos.column); + let func = self.function(f, name)?; + if u.inner.len() >= usize::from(u16::MAX) { + return None; + } + u.inner.push(func); + FuncRef::Inline((u.inner.len() - 1) as u16) + } + E::Function(_) => { + self.problem(handler.pos, "a function written in place can't be removed; give it a name and listen with that"); + return None; + } + _ => { + self.problem(handler.pos, "the listener is a function declared in a frame script, or written in place"); + return None; + } }; - // The event is passed to the function: it takes exactly one argument. - let required = f.params.iter().filter(|p| !p.default && !p.rest).count(); - let Some(first) = f.params.first().filter(|_| required <= 1) else { - return self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); - }; - if cx.stack.contains(&function) { - return self.problem(pos, format!("`{function}` adds itself as a listener; recursion isn't supported")); + if add { + if self.listeners >= MAX_LISTENERS { + self.problem(pos, format!("a frame script adds at most {MAX_LISTENERS} listeners")); + return None; + } + self.listeners += 1; } - if self.listeners >= MAX_LISTENERS { - return self.problem(pos, format!("a frame script adds at most {MAX_LISTENERS} listeners")); - } - self.listeners += 1; - let mut inner = Cx { event: Some((first.name.clone(), path)), in_listener: true, in_function: true, params: f.params.iter().map(|p| p.name.clone()).collect(), stack: cx.stack.clone() }; - inner.stack.push(function.clone()); - let mut body = Vec::new(); - self.stmts(&f.body, &inner, &mut body); - let actions: Vec = body - .into_iter() - .filter_map(|op| match op { - ScriptOp::Action(a) => Some(a), - ScriptOp::Listen(_) => None, - }) - .collect(); - if actions.len() > MAX_ACTIONS { - return self.problem(f.pos, format!("a listener runs at most {MAX_ACTIONS} actions")); - } - out.push(ScriptOp::Listen(Listener { target, event, function, actions: Arc::new(actions) })); + Some(IS::Listen { at, ev: event, f, add }) } - /// The mouse event an `addEventListener` names. - fn event(&mut self, e: &Expr) -> Option { - let (pos, name, constant) = match &e.kind { - E::Member(o, k) if matches!(&o.kind, E::Name(c) if c == "MouseEvent" || c == "Event" || c.ends_with("Event")) => { + /// The event an `addEventListener` names. + fn event(&mut self, e: &Expr) -> O { + let (name, key) = match &e.kind { + E::Member(o, k) if matches!(&o.kind, E::Name(c) if c.ends_with("Event")) => { let class = if let E::Name(c) = &o.kind { c.as_str() } else { "" }; - (e.pos, format!("{class}.{k}"), if class == "MouseEvent" { k.as_str() } else { "" }) + let ev = match (class, k.as_str()) { + ("MouseEvent", "CLICK") => Some(ListenEvent::Click), + ("MouseEvent", "MOUSE_DOWN") => Some(ListenEvent::Press), + ("MouseEvent", "MOUSE_UP") => Some(ListenEvent::Release), + ("MouseEvent", "ROLL_OVER" | "MOUSE_OVER") => Some(ListenEvent::Over), + ("MouseEvent", "ROLL_OUT" | "MOUSE_OUT") => Some(ListenEvent::Out), + ("Event", "ENTER_FRAME") => Some(ListenEvent::EnterFrame), + ("KeyboardEvent", "KEY_DOWN") => Some(ListenEvent::KeyDown), + ("KeyboardEvent", "KEY_UP") => Some(ListenEvent::KeyUp), + _ => None, + }; + (format!("{class}.{k}"), ev) } - E::Str(s) => (e.pos, format!("\"{s}\""), match s.as_str() { - "click" => "CLICK", - "mouseDown" => "MOUSE_DOWN", - "mouseUp" => "MOUSE_UP", - "rollOver" => "ROLL_OVER", - "rollOut" => "ROLL_OUT", - "mouseOver" => "MOUSE_OVER", - "mouseOut" => "MOUSE_OUT", - _ => "", - }), + E::Str(s) => ( + format!("\"{s}\""), + match s.as_str() { + "click" => Some(ListenEvent::Click), + "mouseDown" => Some(ListenEvent::Press), + "mouseUp" => Some(ListenEvent::Release), + "rollOver" | "mouseOver" => Some(ListenEvent::Over), + "rollOut" | "mouseOut" => Some(ListenEvent::Out), + "enterFrame" => Some(ListenEvent::EnterFrame), + "keyDown" => Some(ListenEvent::KeyDown), + "keyUp" => Some(ListenEvent::KeyUp), + _ => None, + }, + ), _ => { self.problem(e.pos, "the event is a constant such as `MouseEvent.CLICK`"); return None; } }; - let ev = match constant { - "CLICK" => ButtonEvent::Click, - "MOUSE_DOWN" => ButtonEvent::Press, - "MOUSE_UP" => ButtonEvent::Release, - "ROLL_OVER" | "MOUSE_OVER" => ButtonEvent::Over, - "ROLL_OUT" | "MOUSE_OUT" => ButtonEvent::Out, - _ => { - self.problem(pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT are)")); - return None; - } - }; - Some(ev) - } - - /// `x = value` on this timeline or `path.x = value`. - fn assign(&mut self, pos: Pos, lhs: &'a Expr, rhs: &'a Expr, cx: &Cx, out: &mut Vec) { - let (obj, prop) = match &lhs.kind { - E::Member(o, p) => (Some(&**o), p.as_str()), - E::Name(n) => (None, n.as_str()), - _ => return self.problem(pos, "only instance properties can be set"), - }; - let property = match prop { - "x" => Property::X, - "y" => Property::Y, - "alpha" => Property::Alpha, - "visible" => Property::Visible, - "rotation" => Property::Rotation, - "scaleX" => Property::ScaleX, - "scaleY" => Property::ScaleY, - "buttonMode" | "useHandCursor" => return self.note(pos, format!("`{prop}` is ignored: the pointer is a hand over everything clickable here")), - p if obj.is_none() => return self.problem(pos, format!("setting `{p}` isn't supported: variables don't run yet")), - p => return self.problem(pos, format!("setting `{p}` isn't supported yet (x, y, alpha, visible, rotation, scaleX and scaleY are)")), - }; - let path = match obj { - Some(o) => match self.target(o, cx) { - Some(t) => t, - None => return, - }, - None => Vec::new(), - }; - let Some(target) = self.path(pos, &path) else { return }; - let value = match self.constant(rhs, cx) { - Ok(v @ (Val::Num(_) | Val::Bool(_))) => v.number(), - Ok(_) => return self.problem(rhs.pos, format!("`{prop}` is set to a number{}", if property == Property::Visible { " or true or false" } else { "" })), - Err(p) => return self.problems.push(p), - }; - if !value.is_finite() { - return self.problem(rhs.pos, "the value must be a finite number"); + if key.is_none() { + self.problem(e.pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT, Event.ENTER_FRAME and KeyboardEvent.KEY_DOWN and KEY_UP are)")); } - out.push(ScriptOp::Action(Action::SetProperty { target, property, value })); + key } - /// An instance path as names (`root`, `parent` and instance names), relative to the - /// script's timeline; `None` after reporting why it isn't one. - fn target(&mut self, e: &Expr, cx: &Cx) -> Option> { - let mut path = match &e.kind { - E::This => Vec::new(), - E::Name(n) if n == "root" || n == "parent" => vec![n.clone()], - E::Name(n) if n == "stage" => { - self.problem(e.pos, "the stage isn't supported as a target"); + // ----- functions ----------------------------------------------------------------------- + + /// A function's IR: parameters, its own variables (hoisted, as ActionScript does) and body. + fn function(&mut self, f: &'a Func, name: String) -> O> { + if self.depth >= 8 { + self.problem(f.pos, "listeners written in place nest more than 8 deep"); + return None; + } + let before = self.problems.len(); + let mut u = Unit { in_function: true, ..Unit::top() }; + let mut params = Vec::new(); + for (i, p) in f.params.iter().enumerate() { + if p.rest { + self.problem(p.pos, "rest parameters (`...args`) aren't supported"); + continue; + } + let (t, ev) = match var_type(&p.ty) { + Ok(Some(t)) => (t, false), + Ok(None) => (Ty::Any, true), + Err((pos, m)) => { + self.problem(pos, m.replace("variables of type", "parameters of type")); + continue; + } + }; + // An untyped first parameter can be the event, too (`function f(e)`). + if ev || (i == 0 && p.ty.is_none()) { + u.events.insert(p.name.clone()); + } + let d = match &p.default { + None => None, + Some(e) => match literal(e) { + Some(v) => Some(t.coerce(v)), + None => { + self.problem(e.pos, "a parameter's default is a value written out (a number, a string, true, false or null)"); + continue; + } + }, + }; + if u.locals.insert(p.name.clone(), (u.types.len() as u16, t)).is_some() { + self.problem(p.pos, format!("the parameter `{}` is named twice", p.name)); + } + u.types.push(t); + params.push(IrParam { t, d, ev }); + } + // Every `var` in the body is the function's (hoisted). + let mut decls = Vec::new(); + collect_vars(&f.body, &mut decls); + for d in decls { + let t = match var_type(&d.ty) { + Ok(Some(t)) => t, + Ok(None) => { + self.problem(d.pos, "variables can't hold events; read `e.keyCode`, `e.target` or `e.currentTarget` from the parameter"); + continue; + } + Err((pos, m)) => { + self.problem(pos, m); + continue; + } + }; + match u.locals.get(&d.name) { + Some((_, old)) if *old != t && d.ty.is_some() => self.problem(d.pos, format!("`{}` is declared again with another type", d.name)), + Some(_) => {} + None => { + if u.types.len() >= 1024 { + self.problem(d.pos, "a function has at most 1024 variables"); + continue; + } + u.locals.insert(d.name.clone(), (u.types.len() as u16, t)); + u.types.push(t); + } + } + } + let ret = match &f.ret { + None => Some(Ty::Any), + Some((t, _)) if t == "void" => None, + Some((t, p)) => match Ty::from_name(t) { + Some(t) => Some(t), + None => { + self.problem(*p, format!("functions returning `{t}` aren't supported yet (Number, int, uint, Boolean, String, void and untyped ones are)")); + None + } + }, + }; + self.depth += 1; + let body = self.body(&f.body, &mut u); + self.depth -= 1; + if self.problems.len() > before { + return None; + } + Some(Arc::new(Function { name, line: f.pos.line, params, locals: u.types, ret, body, inner: u.inner })) + } + + // ----- names and places ---------------------------------------------------------------- + + /// An instance a script names, from the timeline or the event; `None` after reporting why + /// it isn't one. + fn place(&mut self, e: &Expr, u: &Unit) -> O { + let mut at = match &e.kind { + E::This => Place::this(), + E::Name(n) if u.locals.contains_key(n) && !u.events.contains(n) => { + self.problem(e.pos, format!("`{n}` is a variable, not an instance")); return None; } - E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => { + E::Name(n) if u.events.contains(n) => { self.problem(e.pos, format!("the event `{n}` isn't an instance; `{n}.currentTarget` is the one listened to")); return None; } - E::Name(n) if cx.params.contains(n) => { - self.problem(e.pos, format!("reading the parameter `{n}` isn't supported")); + E::Name(n) if n == "stage" => Place { base: Base::Stage, path: Target::this() }, + E::Name(n) if n == "root" || n == "parent" => Place::named(n.clone()), + E::Name(n) if self.vars.contains_key(n) => { + self.problem(e.pos, format!("`{n}` is a variable, not an instance")); return None; } - E::Name(n) => vec![n.clone()], - E::Member(o, m) if m == "currentTarget" && matches!((&o.kind, &cx.event), (E::Name(n), Some((p, _))) if n == p) => cx.event.as_ref().map(|(_, t)| t.clone()).unwrap_or_default(), - E::Member(o, m) if m == "target" && matches!((&o.kind, &cx.event), (E::Name(n), Some((p, _))) if n == p) => { - self.problem(e.pos, "`target` can be a part inside the instance; use `currentTarget`, the instance listened to"); + E::Name(n) if CLASSES.contains(&n.as_str()) => { + self.problem(e.pos, format!("`{n}` is a class, not an instance")); return None; } + E::Name(n) => Place::named(n.clone()), + E::Member(o, m) if (m == "currentTarget" || m == "target") && matches!(&o.kind, E::Name(n) if u.events.contains(n)) => Place { base: if m == "target" { Base::Target } else { Base::Current }, path: Target::this() }, E::Member(o, m) => { - let mut p = self.target(o, cx)?; - p.push(m.clone()); + let mut p = self.place(o, u)?; + if p.base == Base::Stage { + self.problem(e.pos, format!("`stage.{m}` isn't supported")); + return None; + } + let path = if p.path.is_this() { m.clone() } else { format!("{}.{m}", p.path.0.trim()) }; + p.path = Target::new(path); p } - E::Call(f, args) if matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1 => return args.first().and_then(|a| self.target(a, cx)), - E::Binary("as", x, _) => return self.target(x, cx), + E::Call(f, args) if matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1 => return args.first().and_then(|a| self.place(a, u)), + E::Binary("as", x, _) => return self.place(x, u), _ => { self.problem(e.pos, "this isn't an instance (a name path such as `hero_mc.arm_mc`, `parent` or `root`)"); return None; } }; // Every instance's `root` is the main timeline. - if let Some(i) = path.iter().rposition(|s| s == "root") { - path.drain(..i); + let segs: Vec = at.path.0.trim().split('.').filter(|s| !s.is_empty()).map(str::to_string).collect(); + if let Some(i) = segs.iter().rposition(|s| s == "root") { + at = Place { base: Base::This, path: Target::new(segs.get(i..).unwrap_or_default().join(".")) }; } - Some(path) - } - - /// The IR target for a path, checked. - fn path(&mut self, pos: Pos, path: &[String]) -> Option { - for s in path { - if !matches!(s.as_str(), "root" | "parent") && !valid_instance_name(s) { - self.problem(pos, format!("`{s}` isn't an instance name AniCraft can address (1-64 letters, digits, `_` or `$`)")); + for s in at.path.0.split('.').filter(|s| !s.is_empty()) { + if !matches!(s, "root" | "parent" | "this") && !valid_instance_name(s) { + self.problem(e.pos, format!("`{s}` isn't an instance name AniCraft can address (1-64 letters, digits, `_` or `$`)")); return None; } } - let t = Target::new(path.join(".")); - match t.segments() { - Ok(_) => Some(t), - Err(e) => { - self.problem(pos, e); + if let Err(m) = at.path.segments() { + self.problem(e.pos, m); + return None; + } + Some(at) + } + + /// Whether an expression names an instance rather than a value (for `==` between instances). + fn is_instance(&self, e: &Expr, u: &Unit) -> bool { + match &e.kind { + E::This => true, + E::Name(n) => n == "stage" || n == "root" || n == "parent", + E::Member(o, m) => (m == "currentTarget" || m == "target") && matches!(&o.kind, E::Name(n) if u.events.contains(n)), + E::Call(f, args) => matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1, + E::Binary("as", ..) => true, + _ => false, + } + } + + /// Where an assignment writes. + fn lvalue(&mut self, e: &'a Expr, u: &mut Unit) -> O { + match &e.kind { + E::Name(n) => { + if let Some((i, _)) = u.locals.get(n) { + return Some(LValue::Local { i: *i }); + } + if self.vars.contains_key(n) { + return Some(LValue::Var { n: n.clone() }); + } + if let Some(p) = Prop::from_name(n) { + return match p.settable() { + Some(p) => Some(LValue::Prop { at: Place::this(), p }), + None => { + self.problem(e.pos, format!("`{n}` can only be read")); + None + } + }; + } + if self.funcs.contains_key(n.as_str()) || PATH_WORDS.contains(&n.as_str()) || CLASSES.contains(&n.as_str()) || BUILTINS.contains(&n.as_str()) || matches!(n.as_str(), "undefined" | "NaN" | "Infinity") { + self.problem(e.pos, format!("`{n}` can't be assigned to")); + return None; + } + self.free(n, e.pos, false); + Some(LValue::Var { n: n.clone() }) + } + E::Member(o, m) => { + let Some(p) = Prop::from_name(m) else { + self.problem(e.pos, format!("setting `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX and scaleY are)")); + return None; + }; + let Some(p) = p.settable() else { + self.problem(e.pos, format!("`{m}` can only be read")); + return None; + }; + let at = self.place(o, u)?; + if at.base == Base::Stage { + self.problem(e.pos, "the stage's properties can't be set here"); + return None; + } + Some(LValue::Prop { at, p }) + } + _ => { + self.problem(e.pos, "only variables and instance properties can be assigned to"); None } } } - /// A value computed from literals (`"Score: " + 10`, `-5`, `0.5`). - fn constant(&self, e: &Expr, cx: &Cx) -> Result { - Ok(match &e.kind { - E::Num(n) => Val::Num(*n), - E::Str(s) => Val::Str(s.clone()), - E::Bool(b) => Val::Bool(*b), - E::Null => Val::Null, - E::Name(n) if n == "undefined" => Val::Undefined, - E::Name(n) if n == "NaN" => Val::Num(f64::NAN), - E::Name(n) if n == "Infinity" => Val::Num(f64::INFINITY), - E::Unary("-", x) => Val::Num(-self.constant(x, cx)?.number()), - E::Unary("+", x) => Val::Num(self.constant(x, cx)?.number()), - E::Unary("!", x) => Val::Bool(!truthy(&self.constant(x, cx)?)), - E::Binary(op @ ("+" | "-" | "*" | "/" | "%"), a, b) => { - let (a, b) = (self.constant(a, cx)?, self.constant(b, cx)?); - match *op { - "+" if matches!(a, Val::Str(_)) || matches!(b, Val::Str(_)) => { - let s = a.text() + &b.text(); - if s.len() > MAX_TRACE_CHARS * 4 { - return Err(Problem::at(e.pos, "this text is too long")); + // ----- expressions --------------------------------------------------------------------- + + fn expr(&mut self, e: &'a Expr, u: &mut Unit) -> O { + Some(match &e.kind { + E::Num(n) => X::lit(Value::Num(*n)), + E::Str(s) => { + if ir::text_len(s) > super::run::MAX_TEXT { + self.problem(e.pos, "this text is too long"); + return None; + } + X::lit(Value::str(s)) + } + E::Bool(b) => X::lit(Value::Bool(*b)), + E::Null => X::lit(Value::Null), + E::Name(n) => return self.name(e.pos, n, u), + E::Member(o, m) => return self.member(e, o, m, u), + E::Unary(op, x) => match *op { + "-" | "+" | "!" => { + let x = self.expr(x, u)?; + let op = match *op { + "-" => UnOp::Neg, + "+" => UnOp::Plus, + _ => UnOp::Not, + }; + X::Un { op, x: Box::new(x) } + } + "++" | "--" => X::Step { to: self.lvalue(x, u)?, d: if *op == "++" { 1 } else { -1 }, post: false }, + other => { + self.problem(e.pos, format!("`{other}` isn't supported yet")); + return None; + } + }, + E::Postfix(op, x) => X::Step { to: self.lvalue(x, u)?, d: if *op == "++" { 1 } else { -1 }, post: true }, + E::Binary(op, a, b) => match *op { + "&&" | "||" => { + let (a, b) = (self.expr(a, u), self.expr(b, u)); + let (a, b) = (Box::new(a?), Box::new(b?)); + if *op == "&&" { X::And { a, b } } else { X::Or { a, b } } + } + "==" | "!=" | "===" | "!==" if self.is_instance(a, u) || self.is_instance(b, u) => { + let (pa, pb) = (self.place(a, u), self.place(b, u)); + X::Same { a: pa?, b: pb?, ne: op.starts_with('!') } + } + op => { + let Some(bop) = BinOp::from_token(op) else { + let what = match op { + "as" | "is" | "instanceof" | "in" => format!("`{op}` isn't supported here"), + _ => format!("the `{op}` operator isn't supported yet"), + }; + self.problem(e.pos, what); + return None; + }; + let (a, b) = (self.expr(a, u), self.expr(b, u)); + X::Bin { op: bop, a: Box::new(a?), b: Box::new(b?) } + } + }, + E::Assign(op, lhs, rhs) => { + let op = match *op { + "=" => None, + o => match BinOp::from_token(o.trim_end_matches('=')) { + Some(b @ (BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod)) => Some(b), + _ => { + self.problem(e.pos, format!("`{o}` isn't supported yet (`=`, `+=`, `-=`, `*=`, `/=` and `%=` are)")); + return None; } - Val::Str(s) - } - "+" => Val::Num(a.number() + b.number()), - "-" => Val::Num(a.number() - b.number()), - "*" => Val::Num(a.number() * b.number()), - "/" => Val::Num(a.number() / b.number()), - _ => Val::Num(a.number() % b.number()), - } - } - E::Name(n) => { - let msg = if cx.event.as_ref().is_some_and(|(p, _)| p == n) { format!("reading the event `{n}` isn't supported") } else { format!("reading `{n}` isn't supported: only values written out (numbers, strings, true, false) and `+` of them are") }; - return Err(Problem::at(e.pos, msg)); - } - E::Member(..) => { - let mut root = e; - while let E::Member(o, _) = &root.kind { - root = o; - } - let msg = match &root.kind { - E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => format!("reading the event `{n}` isn't supported"), - _ => "reading properties isn't supported: only values written out (numbers, strings, true, false) and `+` of them are".into(), + }, }; - return Err(Problem::at(e.pos, msg)); + let (to, v) = (self.lvalue(lhs, u), self.expr(rhs, u)); + X::Set { to: to?, op, v: Box::new(v?) } + } + E::Cond(c, a, b) => { + let (c, a, b) = (self.expr(c, u), self.expr(a, u), self.expr(b, u)); + X::Cond { c: Box::new(c?), a: Box::new(a?), b: Box::new(b?) } + } + E::Call(callee, args) => return self.call_expr(e.pos, callee, args, u), + E::Comma(_) => { + self.problem(e.pos, "`,` between expressions isn't supported here"); + return None; + } + E::Function(_) => { + self.problem(e.pos, "a function written in place is only supported as a listener"); + return None; + } + E::This => { + self.problem(e.pos, "`this` is the timeline; read a property of it, as in `this.currentFrame`"); + return None; + } + E::Array(_) => { + self.problem(e.pos, "arrays aren't supported yet"); + return None; + } + E::Object(_) => { + self.problem(e.pos, "objects (`{…}`) aren't supported yet"); + return None; + } + E::New(..) => { + self.problem(e.pos, "`new` isn't supported yet"); + return None; + } + E::Index(..) => { + self.problem(e.pos, "`[…]` access isn't supported yet"); + return None; } - _ => return Err(Problem::at(e.pos, "only values written out (numbers, strings, true, false) and `+` of them are supported here")), }) } + + /// A bare name as a value. + fn name(&mut self, pos: Pos, n: &str, u: &mut Unit) -> O { + if let Some((i, _)) = u.locals.get(n) { + return Some(X::Local { i: *i }); + } + if self.vars.contains_key(n) { + return Some(X::Var { n: n.to_string() }); + } + match n { + "undefined" => return Some(X::lit(Value::Undefined)), + "NaN" => return Some(X::lit(Value::Num(f64::NAN))), + "Infinity" => return Some(X::lit(Value::Num(f64::INFINITY))), + _ => {} + } + if let Some(p) = Prop::from_name(n) { + return Some(X::Get { at: Place::this(), p }); + } + if self.funcs.contains_key(n) || BUILTINS.contains(&n) { + self.problem(pos, format!("`{n}` is a function; call it, as in `{n}()`")); + return None; + } + if PATH_WORDS.contains(&n) || CLASSES.contains(&n) || CASTS.contains(&n) { + self.problem(pos, format!("`{n}` isn't a value; read one of its properties")); + return None; + } + self.free(n, pos, false); + Some(X::Var { n: n.to_string() }) + } + + /// `o.m` as a value: constants, the event's key code, or a property of an instance. + fn member(&mut self, e: &'a Expr, o: &'a Expr, m: &str, u: &mut Unit) -> O { + if let E::Name(c) = &o.kind + && (!u.locals.contains_key(c) || u.events.contains(c)) + && !self.vars.contains_key(c) + { + match c.as_str() { + "Math" => { + return match m { + "PI" => Some(X::lit(Value::Num(std::f64::consts::PI))), + "E" => Some(X::lit(Value::Num(std::f64::consts::E))), + _ => { + self.problem(e.pos, format!("`Math.{m}` isn't supported yet (min, max, abs, floor, ceil, round, random and PI are)")); + None + } + }; + } + "Keyboard" => { + return match ir::key_code(m) { + Some(k) => Some(X::lit(Value::Num(f64::from(k)))), + None => { + self.problem(e.pos, format!("`Keyboard.{m}` isn't a key AniCraft knows")); + None + } + }; + } + ev if u.events.contains(ev) => { + return match m { + "keyCode" => Some(X::Key), + "currentTarget" | "target" => { + self.problem(e.pos, format!("`{ev}.{m}` is an instance; read one of its properties, as in `{ev}.{m}.name`")); + None + } + _ => { + self.problem(e.pos, format!("reading the event's `{m}` isn't supported yet (keyCode, target and currentTarget are)")); + None + } + }; + } + _ => {} + } + } + if let E::Name(n) = &o.kind + && n == "stage" + && !matches!(m, "mouseX" | "mouseY") + { + self.problem(e.pos, format!("`stage.{m}` isn't supported yet")); + return None; + } + if let E::Name(n) = &o.kind + && ((u.locals.contains_key(n) && !u.events.contains(n)) || self.vars.contains_key(n)) + { + self.problem(e.pos, format!("reading `{m}` of a value isn't supported yet")); + return None; + } + let Some(p) = Prop::from_name(m) else { + self.problem(e.pos, format!("reading `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY, currentFrame, totalFrames, currentLabel, mouseX, mouseY and name are)")); + return None; + }; + let at = self.place(o, u)?; + if at.base == Base::Stage && !matches!(p, Prop::MouseX | Prop::MouseY) { + self.problem(e.pos, format!("`stage.{m}` isn't supported yet")); + return None; + } + Some(X::Get { at, p }) + } + + /// A call with a value: the timeline's functions, `Math`, and casts. + fn call_expr(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], u: &mut Unit) -> O { + match &callee.kind { + E::Member(o, m) if matches!(&o.kind, E::Name(c) if c == "Math") => { + let Some(f) = MathFn::from_name(m) else { + self.problem(pos, format!("`Math.{m}` isn't supported yet (min, max, abs, floor, ceil, round and random are)")); + return None; + }; + if let Some(n) = f.arity() + && n != args.len() + { + self.problem(pos, format!("`Math.{m}` takes {n} argument{}", if n == 1 { "" } else { "s" })); + return None; + } + let args = self.args(args, u)?; + Some(X::Math { f, args }) + } + E::Name(n) if !u.locals.contains_key(n) => { + let n = n.as_str(); + let cast = match n { + "int" => Some(Ty::Int), + "uint" => Some(Ty::Uint), + "Number" => Some(Ty::Number), + "String" => Some(Ty::String), + "Boolean" => Some(Ty::Boolean), + _ => None, + }; + if let Some(t) = cast { + let [a] = args else { + self.problem(pos, format!("`{n}(…)` takes one value")); + return None; + }; + let x = self.expr(a, u)?; + // `String(x)` of null is "null"; as a variable type it stays null. + return Some(match t { + Ty::String => X::Bin { op: BinOp::Add, a: Box::new(X::lit(Value::str(""))), b: Box::new(x) }, + t => X::Cast { t, x: Box::new(x) }, + }); + } + if Method::from_name(n).is_some() || matches!(n, "trace" | "addEventListener" | "removeEventListener") { + self.problem(pos, format!("`{n}()` gives no value; call it as a statement")); + return None; + } + if OUTSIDE.contains(&n) || CASTS.contains(&n) || CLASSES.contains(&n) || n == "getChildByName" { + self.problem(pos, format!("`{n}(…)` isn't supported here")); + return None; + } + let local = self.funcs.get(n).copied(); + if local.is_none() { + self.free(n, callee.pos, true); + } + if let Some(f) = local { + let required = f.params.iter().filter(|p| p.default.is_none() && !p.rest).count(); + if args.len() < required || args.len() > f.params.len() { + self.problem(pos, format!("`{n}` takes {}{} argument{}, not {}", required, if required == f.params.len() { String::new() } else { format!(" to {}", f.params.len()) }, if f.params.len() == 1 { "" } else { "s" }, args.len())); + return None; + } + } + let mut out = Vec::with_capacity(args.len()); + let mut ok = true; + for a in args { + // The event a listener handles passes on to the function's event parameter. + if let E::Name(x) = &a.kind + && u.events.contains(x) + { + out.push(X::Event); + continue; + } + match self.expr(a, u) { + Some(x) => out.push(x), + None => ok = false, + } + } + ok.then_some(X::Call { f: n.to_string(), args: out }) + } + E::Member(_, m) => { + self.problem(pos, format!("calling `{m}` here isn't supported")); + None + } + _ => { + self.problem(pos, "only named functions and methods can be called"); + None + } + } + } } -fn truthy(v: &Val) -> bool { - match v { - Val::Num(n) => *n != 0.0 && !n.is_nan(), - Val::Str(s) => !s.is_empty(), - Val::Bool(b) => *b, - Val::Null | Val::Undefined => false, - } +/// Whether a declared function can be a listener: the event is its one required parameter. +fn takes_event(f: &Func) -> bool { + let required = f.params.iter().filter(|p| p.default.is_none() && !p.rest).count(); + required <= 1 && !f.params.is_empty() +} + +/// A value written out (for parameter defaults). +fn literal(e: &Expr) -> O { + Some(match &e.kind { + E::Num(n) => Value::Num(*n), + E::Str(s) => Value::str(s), + E::Bool(b) => Value::Bool(*b), + E::Null => Value::Null, + E::Name(n) if n == "undefined" => Value::Undefined, + E::Name(n) if n == "NaN" => Value::Num(f64::NAN), + E::Unary("-", x) => match &x.kind { + E::Num(n) => Value::Num(-n), + _ => return None, + }, + _ => return None, + }) } fn label_ok(s: &str) -> bool { @@ -570,6 +968,27 @@ fn label_ok(s: &str) -> bool { (1..=MAX_LABEL_CHARS).contains(&n) && !s.chars().any(char::is_control) && s.chars().any(|c| !c.is_whitespace()) } +/// Every `var` in a list of statements, into blocks and loops but not into functions. +fn collect_vars<'a>(list: &'a [Stmt], out: &mut Vec<&'a VarDecl>) { + for s in list { + match &s.kind { + S::Var(_, l) => out.extend(l.iter()), + S::Block(b) | S::While(_, b) | S::DoWhile(b, _) | S::Other(_, b) => collect_vars(b, out), + S::If(_, a, b) => { + collect_vars(a, out); + collect_vars(b, out); + } + S::For(init, _, _, b) => { + if let Some(i) = init { + collect_vars(std::slice::from_ref(&**i), out); + } + collect_vars(b, out); + } + _ => {} + } + } +} + /// The statements' top-level function declarations (also those in plain blocks, which /// ActionScript hoists too). fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, problems: &mut Vec) { @@ -577,7 +996,7 @@ fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, proble match &s.kind { S::Function(f) => { let Some(n) = f.name.as_deref() else { continue }; - if BUILTINS.contains(&n) || CASTS.contains(&n) { + if BUILTINS.contains(&n) || CASTS.contains(&n) || CLASSES.contains(&n) || Prop::from_name(n).is_some() || matches!(n, "int" | "uint" | "Number" | "String" | "Boolean") { problems.push(Problem::at(s.pos, format!("a function named `{n}` would hide ActionScript's own `{n}`"))); } else if funcs.insert(n, f).is_some() { problems.push(Problem::at(s.pos, format!("`{n}` is declared twice"))); @@ -589,21 +1008,70 @@ fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, proble } } +/// Counts statements (for "runs, N steps"). +fn count(list: &[IStmt]) -> usize { + list.iter() + .map(|s| { + 1 + match &s.s { + IS::If { a, b, .. } => count(a) + count(b), + IS::Loop { body, .. } => count(body), + _ => 0, + } + }) + .sum() +} + pub(super) fn lower(prog: &[Stmt]) -> Result> { let mut funcs = BTreeMap::new(); let mut problems = Vec::new(); declare(prog, &mut funcs, &mut problems); - let mut l = Lower { funcs, problems, notes: Vec::new(), listeners: 0, work: 0 }; - let mut ops = Vec::new(); - l.stmts(prog, &Cx::default(), &mut ops); - if ops.len() > MAX_ACTIONS { - l.problems.push(Problem::whole(format!("a frame script runs at most {MAX_ACTIONS} steps"))); + // The script's top-level `var`s are the timeline's variables. + let mut decls = Vec::new(); + collect_vars(prog, &mut decls); + let mut vars = BTreeMap::new(); + for d in decls { + let t = match var_type(&d.ty) { + Ok(Some(t)) => t, + Ok(None) => { + problems.push(Problem::at(d.pos, "variables can't hold events")); + continue; + } + Err((p, m)) => { + problems.push(Problem::at(p, m)); + continue; + } + }; + if Prop::from_name(&d.name).is_some() || PATH_WORDS.contains(&d.name.as_str()) || funcs.contains_key(d.name.as_str()) || BUILTINS.contains(&d.name.as_str()) { + problems.push(Problem::at(d.pos, format!("`{}` is already a name of the timeline; choose another name for the variable", d.name))); + continue; + } + match vars.get(&d.name) { + Some(old) if *old != t && d.ty.is_some() => problems.push(Problem::at(d.pos, format!("`{}` is declared again with another type", d.name))), + Some(_) => {} + None => { + vars.insert(d.name.clone(), t); + } + } } + let mut l = Lower { funcs, vars, problems, notes: Vec::new(), free: Vec::new(), listeners: 0, depth: 0 }; + let mut functions = Vec::new(); + let names: Vec<(&str, &Func)> = l.funcs.iter().map(|(n, f)| (*n, *f)).collect(); + for (n, f) in names { + if let Some(func) = l.function(f, n.to_string()) { + functions.push(func); + } + } + let mut top = Unit::top(); + let body = l.body(prog, &mut top); let tidy = |mut v: Vec| { v.sort(); v.dedup(); v.truncate(MAX_PROBLEMS); v }; - if l.problems.is_empty() { Ok(Compiled { ops, notes: tidy(l.notes) }) } else { Err(tidy(l.problems)) } + if !l.problems.is_empty() { + return Err(tidy(l.problems)); + } + let steps = count(&body) + functions.iter().map(|f| count(&f.body)).sum::(); + Ok(Compiled { body, inner: top.inner, functions, vars: l.vars.into_iter().collect(), free: l.free, notes: tidy(l.notes), steps }) } diff --git a/crates/actions/src/as3/mod.rs b/crates/actions/src/as3/mod.rs index 191bd386..31702d3f 100644 --- a/crates/actions/src/as3/mod.rs +++ b/crates/actions/src/as3/mod.rs @@ -1,29 +1,40 @@ -//! The ActionScript 3.0 timeline subset (ADR 0013 tier 2): a hand-written lexer and -//! recursive-descent parser, and a lowering to the action IR. +//! The ActionScript 3.0 subset (ADR 0013 tiers 2 and 2.5): a hand-written lexer and +//! recursive-descent parser, a lowering to a small typed script IR ([`ir`]), and the evaluator +//! that runs it ([`run`]) over the player. //! -//! What runs is what most Animate frame scripts do: `stop()`, `play()`, `gotoAndPlay` and -//! `gotoAndStop` by frame number or label (and scene), `nextFrame()`, `prevFrame()`, -//! `nextScene()` and `prevScene()`, on this timeline or on instance-name paths -//! (`hero_mc.gotoAndStop("run")`, `MovieClip(this.parent).play()`); mouse listeners -//! (`btn.addEventListener(MouseEvent.CLICK, onClick)` with `function onClick(e:MouseEvent):void -//! { … }` made of those calls, or an inline function); `trace` of literals and their `+`; and -//! setting `x`, `y`, `alpha`, `visible`, `rotation`, `scaleX` and `scaleY` on named instances to -//! values. A function declared in the script and called from it runs in place. +//! What runs is what Animate frame scripts do: timeline control (`stop()`, `play()`, +//! `gotoAndPlay`/`gotoAndStop` by frame or label and scene, `nextFrame()` … on this timeline or +//! on instance-name paths); **typed variables** (`var n:int = 0;` as Number, int, uint, Boolean, +//! String or untyped), kept per timeline instance across its frame scripts as ActionScript 3.0 +//! timelines keep them; **expressions** (arithmetic, comparison, logic, joining text, +//! `Math.min/max/abs/floor/ceil/round/random`, `int(…)` and the other casts); `if`/`else`, +//! `for`, `while` and `do` loops; **reading properties** of named instances and of the +//! timeline (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, +//! `totalFrames`, `currentLabel`, `mouseX/Y`, `name`); setting the instance ones; functions +//! with parameters and results, called from any frame script of the same timeline; listeners +//! (`addEventListener` and `removeEventListener`) for mouse events on buttons and movie clips, +//! `Event.ENTER_FRAME`, and `KeyboardEvent.KEY_DOWN`/`KEY_UP` on the stage with `e.keyCode`; +//! `e.target` and `e.currentTarget`; and `trace`. //! -//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all: -//! nothing is ever half-run. Calls that would reach outside the movie (`navigateToURL`, -//! `fscommand`, `ExternalInterface`) are ignored and listed as notes. +//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all. +//! Calls that would reach outside the movie (`navigateToURL`, `fscommand`, `ExternalInterface`) +//! are ignored and listed as notes. A compiled script names the variables and functions it +//! uses from other frames ([`Compiled::free`]); the timeline must declare them +//! ([`Decls::problems`]) or the script doesn't run either. //! //! Learned from the ECMAScript 3rd edition standard (ECMA-262) and Adobe's public ActionScript //! 3.0 language reference; no Adobe code. Everything is bounded: source length, token count, -//! nesting depth, inlining depth, actions, listeners and problems. +//! nesting depth, listeners and problems here; fuel, call depth and text length when it runs. +pub mod ir; mod lex; mod lower; mod parse; +pub mod run; -use crate::{Action, ButtonEvent, Target}; +use ir::{Function, Ty}; use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; use std::sync::Arc; /// Longest script that runs, in bytes (far more than frame scripts written by hand). @@ -32,8 +43,6 @@ pub const MAX_RUN_BYTES: usize = 256 * 1024; pub const MAX_TOKENS: usize = 65_536; /// Deepest nesting of statements and expressions. pub const MAX_DEPTH: usize = 64; -/// Deepest chain of calls to the script's own functions. -pub const MAX_INLINE_DEPTH: usize = 16; /// Most listeners one script adds. pub const MAX_LISTENERS: usize = 64; /// Most problems reported for one script. @@ -73,53 +82,95 @@ impl std::fmt::Display for Problem { } } -/// A mouse listener a script adds: when `event` happens on `target` (a button or movie clip, -/// named from the script's timeline), `actions` run on the script's timeline. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Listener { - #[serde(default, skip_serializing_if = "Target::is_this")] - pub target: Target, - pub event: ButtonEvent, - /// The function's name (`function at line 7` for an inline one): adding the same function - /// for the same event again changes nothing, as in ActionScript. - pub function: String, - pub actions: Arc>, +/// A name a script uses that it doesn't declare: a variable or function of another frame +/// script of the same timeline. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Free { + pub name: String, + pub line: u32, + pub column: u32, + /// Called (a function), or read and written (a variable). + pub call: bool, } -impl Listener { - pub fn describe(&self) -> String { - let body = if self.actions.is_empty() { "nothing".to_string() } else { self.actions.iter().map(Action::describe).collect::>().join("; ") }; - format!("On {} ({}): {body}", self.event.key(), self.target) - } -} - -/// One step of a script, in source order. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ScriptOp { - Action(Action), - Listen(Listener), -} - -impl ScriptOp { - pub fn describe(&self) -> String { - match self { - ScriptOp::Action(a) => a.describe(), - ScriptOp::Listen(l) => l.describe(), - } - } -} - -/// A script that runs: its steps, and what in it is ignored. +/// A script that runs. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Compiled { - pub ops: Vec, + /// The top-level statements, in order. + pub body: Vec, + /// Functions written in place at the top level (listeners). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub inner: Vec>, + /// The functions it declares (the timeline's, callable from its other frames). + pub functions: Vec>, + /// The variables it declares (the timeline's), with their types. + pub vars: Vec<(String, Ty)>, + /// Names it uses from other frames of the timeline. + pub free: Vec, /// Calls that are ignored (they would reach outside the movie, or do nothing here). pub notes: Vec, + /// Statements it holds, functions included (for "runs, N steps"). + pub steps: usize, } -/// Compiles ActionScript 3.0 source to the action IR, or says why it doesn't run (the -/// problems sorted by position, at most [`MAX_PROBLEMS`]). +/// A timeline's declarations: every function and variable its frame scripts declare (the +/// first one of a name, in frame order, top layer first), as ActionScript 3.0 makes them +/// members of the timeline. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Decls { + pub functions: BTreeMap>, + pub vars: BTreeMap, +} + +impl Decls { + /// From the timeline's compiled scripts, in frame order (top layer first within a frame). + pub fn build<'a>(scripts: impl IntoIterator) -> Decls { + let mut d = Decls::default(); + for c in scripts { + for f in &c.functions { + d.functions.entry(f.name.clone()).or_insert_with(|| f.clone()); + } + for (n, t) in &c.vars { + d.vars.entry(n.clone()).or_insert(*t); + } + } + d + } + + /// Why `c` can't run on a timeline with these declarations: a name from another frame that + /// the timeline doesn't declare, or a declaration another frame already makes differently. + pub fn problems(&self, c: &Compiled) -> Vec { + let mut out = Vec::new(); + for f in &c.free { + let pos = Pos { line: f.line, column: f.column }; + let known = if f.call { self.functions.contains_key(&f.name) } else { self.vars.contains_key(&f.name) }; + if !known { + let msg = match (f.call, self.functions.contains_key(&f.name) || self.vars.contains_key(&f.name)) { + (true, true) => format!("`{}` is a variable, not a function", f.name), + (false, true) => format!("`{}` is a function; call it, as in `{}()`", f.name, f.name), + (true, false) => format!("`{}` isn't a function of this timeline (declare it in one of its frame scripts)", f.name), + (false, false) => format!("`{}` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)", f.name), + }; + out.push(Problem::at(pos, msg)); + } + } + for f in &c.functions { + if self.functions.get(&f.name).is_some_and(|g| !Arc::ptr_eq(f, g) && **f != **g) { + out.push(Problem::at(Pos { line: f.line, column: 1 }, format!("`{}` is also declared on another frame of this timeline", f.name))); + } + } + for (n, t) in &c.vars { + if self.vars.get(n).is_some_and(|u| u != t) { + out.push(Problem::whole(format!("`{n}` is declared with another type on another frame of this timeline"))); + } + } + out.truncate(MAX_PROBLEMS); + out + } +} + +/// Compiles ActionScript 3.0 source to the script IR, or says why it doesn't run (the problems +/// sorted by position, at most [`MAX_PROBLEMS`]). pub fn compile(src: &str) -> Result> { if src.len() > MAX_RUN_BYTES { return Err(vec![Problem::whole(format!("the script is longer than {} KiB, the most that runs", MAX_RUN_BYTES / 1024))]); diff --git a/crates/actions/src/as3/parse.rs b/crates/actions/src/as3/parse.rs index ccdea22d..da49786f 100644 --- a/crates/actions/src/as3/parse.rs +++ b/crates/actions/src/as3/parse.rs @@ -1,8 +1,8 @@ //! The parser: tokens to a syntax tree, by recursive descent (the grammar of ECMA-262 3rd //! edition §11–14, with ActionScript 3.0's type annotations, `import`, `as`, `is`, rest //! parameters and `for each`). It reads more of the language than AniCraft runs, so lowering -//! can say exactly which construct isn't run and where; what it reads but never runs (loop -//! headers, `switch` and `try` bodies) is skipped by balanced brackets. Bounded: nesting +//! can say exactly which construct isn't run and where; what it reads but never runs (`for in` +//! heads, `switch` and `try` bodies) is skipped by balanced brackets. Bounded: nesting //! deeper than [`super::MAX_DEPTH`] is a problem, not a stack overflow. use super::lex::{Tok, Token}; @@ -47,7 +47,9 @@ pub enum E { pub struct Param { pub name: String, pub pos: Pos, - pub default: bool, + /// The type annotation as written (`int`, `MouseEvent`, `*`), when there is one. + pub ty: Option<(String, Pos)>, + pub default: Option, pub rest: bool, } @@ -56,9 +58,20 @@ pub struct Func { pub name: Option, pub pos: Pos, pub params: Vec, + /// The result type as written (`void`, `int`), when there is one. + pub ret: Option<(String, Pos)>, pub body: Vec, } +/// One name of a `var` (or `const`) statement. +#[derive(Clone, Debug, PartialEq)] +pub struct VarDecl { + pub name: String, + pub pos: Pos, + pub ty: Option<(String, Pos)>, + pub init: Option, +} + #[derive(Clone, Debug, PartialEq)] pub struct Stmt { pub pos: Pos, @@ -71,8 +84,15 @@ pub enum S { Import, Function(Func), /// `var`, `const`. - Var(&'static str), + Var(&'static str, Vec), If(Expr, Vec, Vec), + /// `for (init; cond; update) body` (`init` a `var` statement or an expression). + For(Option>, Option, Option, Vec), + While(Expr, Vec), + DoWhile(Vec, Expr), + /// `break` and `continue` (without a label). + Break, + Continue, Return(Option), Block(Vec), Empty, @@ -228,12 +248,83 @@ impl<'a> Parser<'a> { } } - /// `: Type` (read and dropped: `*`, `void`, `a.b.C`, `Vector.`). - fn annotation(&mut self) -> R<()> { + /// `: Type` (`*`, `void`, `a.b.C`, `Vector.`), as written. + fn annotation(&mut self) -> R> { if !self.eat(":") { - return Ok(()); + return Ok(None); } - self.type_name() + let pos = self.pos(); + let start = self.i; + self.type_name()?; + let text: String = self + .toks + .get(start..self.i) + .unwrap_or_default() + .iter() + .map(|t| match &t.tok { + Tok::Name(n) => n.clone(), + Tok::Punct(p) => (*p).to_string(), + _ => String::new(), + }) + .collect(); + Ok(Some((text, pos))) + } + + /// The names of a `var` statement after the keyword. + fn var_list(&mut self) -> R> { + let mut out = Vec::new(); + loop { + let (name, pos) = self.name("a variable name")?; + let ty = self.annotation()?; + let init = if self.eat("=") { Some(self.assign()?) } else { None }; + out.push(VarDecl { name, pos, ty, init }); + if !self.eat(",") { + return Ok(out); + } + } + } + + /// `( init ; cond ; update )` after `for`, or `None` for `for … in` (read, not run). + #[allow(clippy::type_complexity)] + fn for_head(&mut self) -> R>, Option, Option)>> { + let open = self.i; + self.expect("(", "after `for`")?; + let pos = self.pos(); + let init = if self.is(";") { + None + } else if self.is_word("var") || self.is_word("const") { + let w = if self.is_word("var") { "var" } else { "const" }; + self.i += 1; + let list = self.var_list()?; + if self.is_word("in") || list.iter().any(|d| matches!(&d.init, Some(Expr { kind: E::Binary("in", ..), .. }))) { + self.i = open; + self.skip_group()?; + return Ok(None); + } + Some(Box::new(Stmt { pos, kind: S::Var(w, list) })) + } else { + let e = self.expr()?; + if matches!(e.kind, E::Binary("in", ..)) { + self.i = open; + self.skip_group()?; + return Ok(None); + } + Some(Box::new(Stmt { pos, kind: S::Expr(e) })) + }; + self.expect(";", "after the loop's start")?; + let cond = if self.is(";") { None } else { Some(self.expr()?) }; + self.expect(";", "after the loop's condition")?; + let update = if self.is(")") { None } else { Some(self.expr()?) }; + self.expect(")", "to close the loop's head")?; + Ok(Some((init, cond, update))) + } + + /// `( expr )` + fn paren(&mut self, what: &str) -> R { + self.expect("(", what)?; + let e = self.expr()?; + self.expect(")", "after the condition")?; + Ok(e) } fn type_name(&mut self) -> R<()> { @@ -323,18 +414,9 @@ impl<'a> Parser<'a> { "var" | "const" => { let w = if w == "var" { "var" } else { "const" }; self.i += 1; - loop { - self.name("a variable name")?; - self.annotation()?; - if self.eat("=") { - self.assign()?; - } - if !self.eat(",") { - break; - } - } + let list = self.var_list()?; self.end()?; - S::Var(w) + S::Var(w, list) } "if" => { self.i += 1; @@ -353,14 +435,20 @@ impl<'a> Parser<'a> { } "for" => { self.i += 1; - self.eat_word("each"); - self.skip_group()?; - S::Other("for", self.body()?) + if self.eat_word("each") { + self.skip_group()?; + S::Other("for each", self.body()?) + } else { + match self.for_head()? { + Some((init, cond, update)) => S::For(init, cond, update, self.body()?), + None => S::Other("for in", self.body()?), + } + } } "while" => { self.i += 1; - self.skip_group()?; - S::Other("while", self.body()?) + let c = self.paren("after `while`")?; + S::While(c, self.body()?) } "do" => { self.i += 1; @@ -368,9 +456,9 @@ impl<'a> Parser<'a> { if !self.eat_word("while") { return Err(self.unexpected("`while` after the `do` body")); } - self.skip_group()?; + let c = self.paren("after `while`")?; self.end()?; - S::Other("do", b) + S::DoWhile(b, c) } "with" => { self.i += 1; @@ -408,11 +496,17 @@ impl<'a> Parser<'a> { _ => "throw", }; self.i += 1; - if !(self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl()) { + let bare = self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl(); + if !bare { self.expr()?; } self.end()?; - S::Other(w, Vec::new()) + match (w, bare) { + ("break", true) => S::Break, + ("continue", true) => S::Continue, + ("throw", _) => S::Other("throw", Vec::new()), + _ => S::Other("labelled break", Vec::new()), + } } // Applications, not timeline scripts (ADR 0013 tier 3). "package" | "class" | "interface" | "namespace" | "use" | "include" | "default" => { @@ -454,21 +548,18 @@ impl<'a> Parser<'a> { loop { let rest = self.eat("..."); let (n, p) = self.name("a parameter name")?; - self.annotation()?; - let default = self.eat("="); - if default { - self.assign()?; - } - params.push(Param { name: n, pos: p, default, rest }); + let ty = self.annotation()?; + let default = if self.eat("=") { Some(self.assign()?) } else { None }; + params.push(Param { name: n, pos: p, ty, default, rest }); if self.eat(")") { break; } self.expect(",", "or `)` after the parameter")?; } } - self.annotation()?; + let ret = self.annotation()?; let body = self.block()?; - Ok(Func { name, pos, params, body }) + Ok(Func { name, pos, params, ret, body }) } /// An expression (`a, b` included). @@ -534,29 +625,44 @@ impl<'a> Parser<'a> { ]; let Some(ops) = LEVELS.get(level) else { return self.unary() }; let mut lhs = self.binary(level + 1)?; - loop { + // Each operator in a row nests the tree one deeper: it counts toward the depth limit, + // so what runs the tree can't recurse without bound. + let mut chain = 0; + let r = loop { let op = match self.tok() { Tok::Punct(p) if ops.contains(p) => ops.iter().find(|o| *o == p).copied(), Tok::Name(n) if ops.contains(&n.as_str()) => ops.iter().find(|o| **o == n.as_str()).copied(), _ => None, }; - let Some(op) = op else { return Ok(lhs) }; + let Some(op) = op else { break Ok(lhs) }; + chain += 1; + self.depth += 1; + if self.depth > MAX_DEPTH { + break Err(Problem::at(self.pos(), format!("this expression has too many operators in a row (code nests at most {MAX_DEPTH} levels deep)"))); + } self.i += 1; // The right side of `as` and `is` is a type. let rhs = if matches!(op, "as" | "is") { let pos = self.pos(); let start = self.i; - self.type_name()?; + if let Err(e) = self.type_name() { + break Err(e); + } let name = match self.toks.get(start..self.i) { Some([Token { tok: Tok::Name(n), .. }]) => n.clone(), _ => "*".into(), }; Expr { pos, kind: E::Name(name) } } else { - self.binary(level + 1)? + match self.binary(level + 1) { + Ok(e) => e, + Err(e) => break Err(e), + } }; lhs = Expr { pos: lhs.pos, kind: E::Binary(op, Box::new(lhs), Box::new(rhs)) }; - } + }; + self.depth -= chain; + r } fn unary(&mut self) -> R { diff --git a/crates/actions/src/as3/run.rs b/crates/actions/src/as3/run.rs new file mode 100644 index 00000000..a2a8f164 --- /dev/null +++ b/crates/actions/src/as3/run.rs @@ -0,0 +1,528 @@ +//! Running the script IR (ADR 0013 tier 2.5): a small tree-walking evaluator over a +//! [`World`] (the player, which knows the movie). It is deterministic (the only random numbers +//! come from the world's seeded generator) and bounded: every statement and expression costs +//! fuel, text has a length limit, calls a depth limit. When fuel runs out or something can't +//! be done (a name that isn't there, a value of the wrong kind), the run stops where it is, +//! as an ActionScript error stops a script, and says why; what it did before stays done. +//! +//! The HTML canvas player (`player.js`) mirrors this file step for step. + +use super::ir::*; +use crate::{FrameRef, MAX_FRAME, MAX_LABEL_CHARS, MAX_TRACE_CHARS, Property}; +use std::sync::Arc; + +/// Fuel one frame script (or one listener call) may use. +pub const FUEL_PER_RUN: u64 = 100_000; +/// Deepest chain of calls. +pub const MAX_CALL_DEPTH: usize = 16; +/// Longest text a script makes, in UTF-16 units. +pub const MAX_TEXT: usize = 16_384; + +/// Why a run stopped before its end. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Stop { + /// It used its fuel (an endless loop, most likely). + Fuel, + /// Something couldn't be done, at `line`. + Error { line: u32, message: String }, + /// The world stopped everything (a per-frame budget ran out); it already said why. + Halt, +} + +impl Stop { + pub fn describe(&self) -> String { + match self { + Stop::Fuel => format!("it ran more than {FUEL_PER_RUN} steps (an endless loop?)"), + Stop::Error { line, message } if *line > 0 => format!("line {line}: {message}"), + Stop::Error { message, .. } => message.clone(), + Stop::Halt => "the frame's budget ran out".into(), + } + } +} + +/// What a running script talks to. Errors stop the run (`Err(message)`); actions that can't +/// find their instance write a line to Output and the script goes on, as before (tier 2). +pub trait World { + /// A timeline action, on the instance `base` starts from (`action`'s target is the name path). + fn act(&mut self, base: Base, action: &crate::Action) -> Result<(), Option>; + /// Reads a property. + fn get(&mut self, at: &Place, p: Prop) -> Result; + /// Sets an instance property. + fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option>; + fn trace(&mut self, line: String); + /// A timeline variable's value, and writing one (the world knows its type). + fn read(&mut self, name: &str) -> Result; + fn write(&mut self, name: &str, v: Value) -> Result<(), String>; + /// The timeline's function by that name. + fn function(&mut self, name: &str) -> Option>; + /// Adds (or removes) a listener; `name` is how it is known (adding the same again does + /// nothing). + fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc, add: bool) -> Result<(), Option>; + /// The next number from the movie's seeded generator, in [0, 1). + fn random(&mut self) -> f64; + /// Whether two names are one instance. + fn same(&mut self, a: &Place, b: &Place) -> Result; + /// The keyboard event's key code. + fn key_code(&mut self) -> Result; +} + +/// The error of a world call: `None` means the world halted (and said so). +fn lift(line: u32, e: Option) -> Stop { + match e { + Some(message) => Stop::Error { line, message }, + None => Stop::Halt, + } +} + +enum Flow { + Normal, + Break, + Continue, + Return(Value), +} + +struct Frame<'f> { + locals: Vec, + /// Each local's type (a write coerces to it). + types: &'f [Ty], + inner: &'f [Arc], +} + +struct Vm<'w> { + w: &'w mut dyn World, + fuel: u64, + depth: usize, + line: u32, +} + +type R = Result; + +/// Runs a frame script's top-level statements; returns the fuel used and how it ended. +pub fn run_script(w: &mut dyn World, body: &[Stmt], inner: &[Arc], fuel: u64) -> (u64, Result<(), Stop>) { + let mut vm = Vm { w, fuel, depth: 0, line: 0 }; + let mut frame = Frame { locals: Vec::new(), types: &[], inner }; + let r = vm.block(body, &mut frame).map(|_| ()); + (fuel - vm.fuel, r) +} + +/// Calls a listener's function with the event (its first parameter). +pub fn run_listener(w: &mut dyn World, f: &Arc, fuel: u64) -> (u64, Result<(), Stop>) { + let mut vm = Vm { w, fuel, depth: 0, line: f.line }; + let r = vm.call(f, &[Expr::Event], &mut Frame { locals: Vec::new(), types: &[], inner: &[] }).map(|_| ()); + (fuel - vm.fuel, r) +} + +/// JavaScript's `Math.round`: the nearest integer, halves toward +∞. +pub fn round(x: f64) -> f64 { + if !x.is_finite() { + return x; + } + let f = x.floor(); + if x - f >= 0.5 { f + 1.0 } else { f } +} + +/// Math.min / Math.max: NaN wins, no arguments give ±Infinity. +fn min_max(vals: &[f64], max: bool) -> f64 { + let mut out = if max { f64::NEG_INFINITY } else { f64::INFINITY }; + for &v in vals { + if v.is_nan() { + return f64::NAN; + } + if (max && v > out) || (!max && v < out) { + out = v; + } + } + out +} + +/// `==` (ECMA-262 §11.9.3) over primitives. +pub fn loose_eq(a: &Value, b: &Value) -> bool { + use Value as V; + match (a, b) { + (V::Undefined | V::Null, V::Undefined | V::Null) => true, + (V::Undefined | V::Null, _) | (_, V::Undefined | V::Null) => false, + (V::Num(x), V::Num(y)) => x == y, + (V::Str(x), V::Str(y)) => x == y, + (V::Bool(x), V::Bool(y)) => x == y, + (V::Num(x), V::Str(_)) => *x == b.number(), + (V::Str(_), V::Num(y)) => a.number() == *y, + (V::Bool(_), _) => loose_eq(&V::Num(a.number()), b), + (_, V::Bool(_)) => loose_eq(a, &V::Num(b.number())), + } +} + +/// `===` (§11.9.6). +pub fn strict_eq(a: &Value, b: &Value) -> bool { + use Value as V; + match (a, b) { + (V::Num(x), V::Num(y)) => x == y, + (V::Undefined, V::Undefined) | (V::Null, V::Null) => true, + (V::Str(x), V::Str(y)) => x == y, + (V::Bool(x), V::Bool(y)) => x == y, + _ => false, + } +} + +/// `<` (§11.8.5): text by UTF-16 units, the rest as numbers; `None` when a NaN is involved. +fn compare(a: &Value, b: &Value) -> Option { + if let (Value::Str(x), Value::Str(y)) = (a, b) { + return Some(x.encode_utf16().cmp(y.encode_utf16())); + } + a.number().partial_cmp(&b.number()) +} + +/// Text cut to [`MAX_TRACE_CHARS`] UTF-16 units (never through a surrogate pair), with `…`. +pub fn trace_line(s: String) -> String { + let units: Vec = s.encode_utf16().collect(); + if units.len() <= MAX_TRACE_CHARS { + return s; + } + let mut n = MAX_TRACE_CHARS; + if units.get(n - 1).is_some_and(|u| (0xd800..0xdc00).contains(u)) { + n -= 1; + } + let mut out = String::from_utf16_lossy(units.get(..n).unwrap_or(&[])); + out.push('…'); + out +} + +impl Vm<'_> { + fn tick(&mut self, n: u64) -> R<()> { + if self.fuel < n { + self.fuel = 0; + return Err(Stop::Fuel); + } + self.fuel -= n; + Ok(()) + } + + fn err(&self, message: impl Into) -> R { + Err(Stop::Error { line: self.line, message: message.into() }) + } + + fn block(&mut self, list: &[Stmt], fr: &mut Frame<'_>) -> R { + for s in list { + match self.stmt(s, fr)? { + Flow::Normal => {} + other => return Ok(other), + } + } + Ok(Flow::Normal) + } + + fn stmt(&mut self, st: &Stmt, fr: &mut Frame<'_>) -> R { + self.tick(1)?; + self.line = st.l; + match &st.s { + S::Do { x } => { + self.expr(x, fr)?; + } + S::If { c, a, b } => { + let c = self.expr(c, fr)?.truthy(); + return self.block(if c { a } else { b }, fr); + } + S::Loop { c, body, next, first } => { + let mut test = *first; + loop { + if test && let Some(c) = c { + self.line = st.l; + if !self.expr(c, fr)?.truthy() { + break; + } + } + test = true; + // A loop with nothing in it still costs fuel. + self.tick(1)?; + match self.block(body, fr)? { + Flow::Break => break, + Flow::Return(v) => return Ok(Flow::Return(v)), + Flow::Normal | Flow::Continue => {} + } + if let Some(n) = next { + self.line = st.l; + self.expr(n, fr)?; + } + } + } + S::Break => return Ok(Flow::Break), + S::Continue => return Ok(Flow::Continue), + S::Return { v } => { + let v = match v { + Some(v) => self.expr(v, fr)?, + None => Value::Undefined, + }; + return Ok(Flow::Return(v)); + } + S::Act { at, m, args } => { + let frame = match args.first() { + Some(a) => Some(self.expr(a, fr)?), + None => None, + }; + let scene = match args.get(1) { + Some(a) => Some(self.expr(a, fr)?), + None => None, + }; + self.line = st.l; + let frame = match frame { + None => FrameRef::default(), + Some(Value::Str(s)) if label_ok(&s) => FrameRef::Label(s.to_string()), + Some(Value::Num(n)) if n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(&n) => FrameRef::Number(n as u32 - 1), + Some(v) => return self.err(format!("`{}` needs a frame number from 1 or a label, not {}", m.name(), shown(&v))), + }; + let scene = match scene { + None | Some(Value::Null | Value::Undefined) => None, + Some(Value::Str(s)) if label_ok(&s) => Some(s.to_string()), + Some(v) => return self.err(format!("the scene is its name, not {}", shown(&v))), + }; + let action = m.action(at.path.clone(), frame, scene); + self.w.act(at.base, &action).map_err(|e| lift(st.l, e))?; + } + S::Trace { args } => { + let mut parts = Vec::with_capacity(args.len()); + for a in args { + parts.push(self.expr(a, fr)?.text()); + } + self.w.trace(trace_line(parts.join(" "))); + } + S::Listen { at, ev, f, add } => { + let func = match f { + FuncRef::Named(n) => match self.w.function(n) { + Some(f) => f, + None => return self.err(format!("there's no function `{n}` on this timeline")), + }, + FuncRef::Inline(i) => match fr.inner.get(usize::from(*i)) { + Some(f) => f.clone(), + None => return self.err("the listener's function is missing"), + }, + }; + self.w.listen(at, *ev, &func, *add).map_err(|e| lift(st.l, e))?; + } + } + Ok(Flow::Normal) + } + + fn text(&mut self, s: String) -> R { + let n = text_len(&s); + if n > MAX_TEXT { + return self.err(format!("this text would be longer than {MAX_TEXT} characters")); + } + // Making text costs fuel for its length, so a loop building text can't run long. + self.tick(n as u64 / 64)?; + Ok(Value::Str(s.into())) + } + + fn binary(&mut self, op: BinOp, a: Value, b: Value) -> R { + use std::cmp::Ordering::*; + Ok(match op { + BinOp::Add if a.is_str() || b.is_str() => return self.text(a.text() + &b.text()), + BinOp::Add => Value::Num(a.number() + b.number()), + BinOp::Sub => Value::Num(a.number() - b.number()), + BinOp::Mul => Value::Num(a.number() * b.number()), + BinOp::Div => Value::Num(a.number() / b.number()), + BinOp::Mod => Value::Num(a.number() % b.number()), + BinOp::Lt => Value::Bool(compare(&a, &b) == Some(Less)), + BinOp::Gt => Value::Bool(compare(&a, &b) == Some(Greater)), + BinOp::Le => Value::Bool(matches!(compare(&a, &b), Some(Less | Equal))), + BinOp::Ge => Value::Bool(matches!(compare(&a, &b), Some(Greater | Equal))), + BinOp::Eq => Value::Bool(loose_eq(&a, &b)), + BinOp::Ne => Value::Bool(!loose_eq(&a, &b)), + BinOp::StrictEq => Value::Bool(strict_eq(&a, &b)), + BinOp::StrictNe => Value::Bool(!strict_eq(&a, &b)), + }) + } + + fn load(&mut self, to: &LValue, fr: &Frame<'_>) -> R { + match to { + LValue::Local { i } => Ok(fr.locals.get(usize::from(*i)).cloned().unwrap_or_default()), + LValue::Var { n } => self.w.read(n).map_err(|message| Stop::Error { line: self.line, message }), + LValue::Prop { at, p } => { + let prop = match p { + Property::X => Prop::X, + Property::Y => Prop::Y, + Property::Alpha => Prop::Alpha, + Property::Visible => Prop::Visible, + Property::Rotation => Prop::Rotation, + Property::ScaleX => Prop::ScaleX, + Property::ScaleY => Prop::ScaleY, + }; + self.w.get(at, prop).map_err(|message| Stop::Error { line: self.line, message }) + } + } + } + + /// Writes `v`; the value is what the place holds after (a typed variable's coercion). + fn store(&mut self, to: &LValue, v: Value, fr: &mut Frame<'_>) -> R { + match to { + LValue::Local { i } => { + let ty = fr.types.get(usize::from(*i)).copied().unwrap_or_default(); + let v = ty.coerce(v); + if let Some(slot) = fr.locals.get_mut(usize::from(*i)) { + *slot = v.clone(); + } + Ok(v) + } + LValue::Var { n } => { + self.w.write(n, v).map_err(|message| Stop::Error { line: self.line, message })?; + self.w.read(n).map_err(|message| Stop::Error { line: self.line, message }) + } + LValue::Prop { at, p } => { + let n = v.number(); + if !n.is_finite() { + return self.err(format!("`{}` is set to a number, not {}", prop_name(*p), shown(&v))); + } + self.w.set(at, *p, n).map_err(|e| lift(self.line, e))?; + Ok(v) + } + } + } + + fn expr(&mut self, e: &Expr, fr: &mut Frame<'_>) -> R { + self.tick(1)?; + Ok(match e { + Expr::Lit { v } => v.clone(), + Expr::Local { i } => fr.locals.get(usize::from(*i)).cloned().unwrap_or_default(), + Expr::Var { n } => self.w.read(n).map_err(|message| Stop::Error { line: self.line, message })?, + Expr::Get { at, p } => self.w.get(at, *p).map_err(|message| Stop::Error { line: self.line, message })?, + Expr::Key => Value::Num(self.w.key_code().map_err(|message| Stop::Error { line: self.line, message })?), + Expr::Event => return self.err("the event can only be passed to a function's event parameter"), + Expr::Un { op, x } => { + let v = self.expr(x, fr)?; + match op { + UnOp::Neg => Value::Num(-v.number()), + UnOp::Plus => Value::Num(v.number()), + UnOp::Not => Value::Bool(!v.truthy()), + } + } + Expr::Bin { op, a, b } => { + let a = self.expr(a, fr)?; + let b = self.expr(b, fr)?; + return self.binary(*op, a, b); + } + Expr::And { a, b } => { + let a = self.expr(a, fr)?; + if a.truthy() { self.expr(b, fr)? } else { a } + } + Expr::Or { a, b } => { + let a = self.expr(a, fr)?; + if a.truthy() { a } else { self.expr(b, fr)? } + } + Expr::Cond { c, a, b } => { + if self.expr(c, fr)?.truthy() { + self.expr(a, fr)? + } else { + self.expr(b, fr)? + } + } + Expr::Math { f, args } => { + let mut v = Vec::with_capacity(args.len()); + for a in args { + v.push(self.expr(a, fr)?.number()); + } + let x = v.first().copied().unwrap_or(f64::NAN); + Value::Num(match f { + MathFn::Min => min_max(&v, false), + MathFn::Max => min_max(&v, true), + MathFn::Abs => x.abs(), + MathFn::Floor => x.floor(), + MathFn::Ceil => x.ceil(), + MathFn::Round => round(x), + MathFn::Random => self.w.random(), + }) + } + Expr::Call { f, args } => { + let Some(func) = self.w.function(f) else { return self.err(format!("there's no function `{f}` on this timeline")) }; + let line = self.line; + let v = self.call(&func, args, fr)?; + self.line = line; + v + } + Expr::Same { a, b, ne } => { + let same = self.w.same(a, b).map_err(|message| Stop::Error { line: self.line, message })?; + Value::Bool(same != *ne) + } + Expr::Set { to, op, v } => { + let new = match op { + None => self.expr(v, fr)?, + Some(op) => { + let old = self.load(to, fr)?; + let rhs = self.expr(v, fr)?; + self.binary(*op, old, rhs)? + } + }; + return self.store(to, new, fr); + } + Expr::Step { to, d, post } => { + let old = Value::Num(self.load(to, fr)?.number()); + let new = Value::Num(old.number() + f64::from(*d)); + let stored = self.store(to, new, fr)?; + if *post { old } else { stored } + } + Expr::Cast { t, x } => { + let v = self.expr(x, fr)?; + t.coerce(v) + } + }) + } + + /// Calls `f` with `args` evaluated in the caller's frame. + fn call(&mut self, f: &Arc, args: &[Expr], caller: &mut Frame<'_>) -> R { + if self.depth >= MAX_CALL_DEPTH { + return self.err(format!("functions call each other more than {MAX_CALL_DEPTH} deep")); + } + let required = f.params.iter().filter(|p| p.d.is_none()).count(); + if args.len() < required || args.len() > f.params.len() { + let want = if required == f.params.len() { format!("{required}") } else { format!("{required} to {}", f.params.len()) }; + return self.err(format!("`{}` takes {want} argument{}, not {}", f.name, if f.params.len() == 1 { "" } else { "s" }, args.len())); + } + let mut locals: Vec = f.locals.iter().map(|t| t.default_value()).collect(); + for (i, p) in f.params.iter().enumerate() { + let v = match args.get(i) { + Some(Expr::Event) if p.ev || p.t == Ty::Any => Value::Null, + Some(Expr::Event) => return self.err("the event can only be passed to a function's event parameter"), + Some(a) => self.expr(a, caller)?, + None => p.d.clone().unwrap_or_default(), + }; + if let Some(slot) = locals.get_mut(i) { + *slot = p.t.coerce(v); + } + } + self.depth += 1; + self.line = f.line; + let mut fr = Frame { locals, types: &f.locals, inner: &f.inner }; + let flow = self.block(&f.body, &mut fr); + self.depth -= 1; + let v = match flow? { + Flow::Return(v) => v, + _ => Value::Undefined, + }; + Ok(match f.ret { + Some(t) => t.coerce(v), + None => Value::Undefined, + }) + } +} + +fn label_ok(s: &str) -> bool { + let n = s.chars().count(); + (1..=MAX_LABEL_CHARS).contains(&n) && !s.chars().any(char::is_control) && s.chars().any(|c| !c.is_whitespace()) +} + +/// A value as a message names it. +fn shown(v: &Value) -> String { + match v { + Value::Str(s) => format!("\"{}\"", s.chars().take(40).collect::()), + other => other.text(), + } +} + +fn prop_name(p: Property) -> &'static str { + match p { + Property::X => "x", + Property::Y => "y", + Property::Alpha => "alpha", + Property::Visible => "visible", + Property::Rotation => "rotation", + Property::ScaleX => "scaleX", + Property::ScaleY => "scaleY", + } +} diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs index 7ce85de8..dd2254d7 100644 --- a/crates/actions/src/as3/tests.rs +++ b/crates/actions/src/as3/tests.rs @@ -1,21 +1,13 @@ +use super::ir::*; +use super::run::{self, Stop, World}; use super::*; -use crate::{Action, ButtonEvent, FrameRef, Property, Target}; +use crate::{Action, FrameRef, Property}; +use std::collections::BTreeMap; fn ok(src: &str) -> Compiled { compile(src).unwrap_or_else(|p| panic!("{src:?} didn't compile: {p:?}")) } -fn actions(src: &str) -> Vec { - ok(src) - .ops - .into_iter() - .map(|o| match o { - ScriptOp::Action(a) => a, - ScriptOp::Listen(l) => panic!("unexpected listener {l:?}"), - }) - .collect() -} - /// The first problem: (line, column, message). fn err(src: &str) -> (u32, u32, String) { match compile(src) { @@ -27,99 +19,259 @@ fn err(src: &str) -> (u32, u32, String) { } } -fn t(s: &str) -> Target { - Target::new(s) +/// A movie in miniature: one timeline with its variables and functions, instances with +/// properties, and a log of everything the script did. +#[derive(Default)] +struct Mock { + decls: Decls, + vars: BTreeMap, + props: BTreeMap<(String, &'static str), f64>, + log: Vec, + rng: u32, + key: Option, + frame: u32, } -#[test] -fn timeline_calls_lower_to_actions() { - let a = actions("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();"); - assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }, Action::NextFrame { target: t("") }, Action::PrevFrame { target: t("") }, Action::NextScene, Action::PrevScene]); - // Frames are 1-based in ActionScript, 0-based in the IR; strings are labels. - let a = actions(r#"gotoAndStop(1); gotoAndPlay("run"); gotoAndPlay(12, "Scene 2"); gotoAndStop('end', null); gotoAndStop(2 + 3);"#); - assert_eq!( - a, - vec![ - Action::GotoAndStop { target: t(""), frame: FrameRef::Number(0), scene: None }, - Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("run".into()), scene: None }, - Action::GotoAndPlay { target: t(""), frame: FrameRef::Number(11), scene: Some("Scene 2".into()) }, - Action::GotoAndStop { target: t(""), frame: FrameRef::Label("end".into()), scene: None }, - Action::GotoAndStop { target: t(""), frame: FrameRef::Number(4), scene: None }, - ] - ); -} - -#[test] -fn instance_paths_become_targets() { - let a = actions("hero_mc.gotoAndStop(\"run\");\nthis.hero_mc.arm_mc.play();\nMovieClip(parent).stop();\nMovieClip(this.parent.parent).nextFrame();\nMovieClip(root).menu.play();\n(root as MovieClip).stop();\nhero_mc.root.stop();\nObject(parent).door.prevFrame();"); - let targets: Vec = a.iter().map(|a| a.target().map(|t| t.0.clone()).unwrap_or_default()).collect(); - assert_eq!(targets, ["hero_mc", "hero_mc.arm_mc", "parent", "parent.parent", "root.menu", "root", "root", "parent.door"]); - assert!(a.iter().all(|x| x.check().is_ok())); -} - -#[test] -fn properties_are_set_to_values() { - let a = actions("hero_mc.x = 100;\nhero_mc.y = -20.5;\nhero_mc.alpha = .5;\nhero_mc.visible = false;\ndoor.rotation = 45;\ndoor.scaleX = 2; door.scaleY = 1.5\nalpha = 0.25;"); - assert_eq!( - a, - vec![ - Action::SetProperty { target: t("hero_mc"), property: Property::X, value: 100.0 }, - Action::SetProperty { target: t("hero_mc"), property: Property::Y, value: -20.5 }, - Action::SetProperty { target: t("hero_mc"), property: Property::Alpha, value: 0.5 }, - Action::SetProperty { target: t("hero_mc"), property: Property::Visible, value: 0.0 }, - Action::SetProperty { target: t("door"), property: Property::Rotation, value: 45.0 }, - Action::SetProperty { target: t("door"), property: Property::ScaleX, value: 2.0 }, - Action::SetProperty { target: t("door"), property: Property::ScaleY, value: 1.5 }, - Action::SetProperty { target: t(""), property: Property::Alpha, value: 0.25 }, - ] - ); -} - -#[test] -fn trace_writes_literals_and_their_sums_as_actionscript_does() { - let msgs: Vec = actions(r#"trace("hello"); trace('a' + 1 + 2); trace(1 + 2 + "a"); trace(0.1, true, null, undefined); trace(1e21, 1e-7, -0, 5 / 2, 7 % 4); trace(); trace("tab\there é \x41");"#) - .into_iter() - .map(|a| match a { - Action::Trace { message } => message, - other => panic!("{other:?}"), +impl World for Mock { + fn act(&mut self, base: Base, a: &Action) -> Result<(), Option> { + if let Action::GotoAndStop { frame: FrameRef::Number(n), .. } = a { + self.frame = *n; + } + self.log.push(format!("{base:?} {}", a.describe())); + Ok(()) + } + fn get(&mut self, at: &Place, p: Prop) -> Result { + if at.path.0 == "ghost" { + return Err("no instance named “ghost” here".into()); + } + Ok(match p { + Prop::CurrentFrame => Value::Num(f64::from(self.frame + 1)), + Prop::Name => Value::str(&at.to_string()), + Prop::Visible => Value::Bool(true), + p => Value::Num(self.props.get(&(at.path.0.clone(), p.name())).copied().unwrap_or(0.0)), }) - .collect(); - assert_eq!(msgs, ["hello", "a12", "3a", "0.1 true null undefined", "1e+21 1e-7 0 2.5 3", "", "tab\there é A"]); -} - -#[test] -fn listeners_lower_to_handlers_with_their_bodies() { - let src = "import flash.events.MouseEvent;\n\nstop();\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(e:MouseEvent):void {\n\tgotoAndPlay(\"walk\"); // on\n\ttrace(\"go\");\n}\nmenu.btn.addEventListener(MouseEvent.ROLL_OVER, function (event:MouseEvent):void { MovieClip(event.currentTarget).gotoAndStop(2); });\naddEventListener(\"mouseDown\", onPlay);"; - let c = ok(src); - assert_eq!(c.ops.len(), 4); - assert_eq!(c.ops[0], ScriptOp::Action(Action::Stop { target: t("") })); - let ScriptOp::Listen(l) = &c.ops[1] else { panic!("{:?}", c.ops[1]) }; - assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("play_btn", ButtonEvent::Click, "onPlay")); - assert_eq!(*l.actions, vec![Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("walk".into()), scene: None }, Action::Trace { message: "go".into() }]); - let ScriptOp::Listen(l) = &c.ops[2] else { panic!() }; - // `currentTarget` is the instance listened to, named from the script's timeline. - assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("menu.btn", ButtonEvent::Over, "function at line 10")); - assert_eq!(*l.actions, vec![Action::GotoAndStop { target: t("menu.btn"), frame: FrameRef::Number(1), scene: None }]); - let ScriptOp::Listen(l) = &c.ops[3] else { panic!() }; - assert_eq!((l.target.is_this(), l.event), (true, ButtonEvent::Press)); - assert!(l.describe().starts_with("On press (this): Go to “walk” and play"), "{}", l.describe()); - for (k, e) in [("MOUSE_UP", ButtonEvent::Release), ("ROLL_OUT", ButtonEvent::Out), ("MOUSE_OVER", ButtonEvent::Over), ("MOUSE_OUT", ButtonEvent::Out)] { - let c = ok(&format!("b.addEventListener(MouseEvent.{k}, f, false, 0, true); function f(e) {{}}")); - assert!(matches!(&c.ops[0], ScriptOp::Listen(l) if l.event == e), "{k}"); + } + fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option> { + let name = Prop::from_name(match p { + Property::X => "x", + Property::Y => "y", + Property::Alpha => "alpha", + Property::Visible => "visible", + Property::Rotation => "rotation", + Property::ScaleX => "scaleX", + Property::ScaleY => "scaleY", + }) + .map_or("?", Prop::name); + self.props.insert((at.path.0.clone(), name), v); + Ok(()) + } + fn trace(&mut self, line: String) { + self.log.push(line); + } + fn read(&mut self, name: &str) -> Result { + match self.vars.get(name) { + Some(v) => Ok(v.clone()), + None => self.decls.vars.get(name).map(|t| t.default_value()).ok_or_else(|| format!("`{name}` isn't defined")), + } + } + fn write(&mut self, name: &str, v: Value) -> Result<(), String> { + let t = *self.decls.vars.get(name).ok_or_else(|| format!("`{name}` isn't defined"))?; + self.vars.insert(name.to_string(), t.coerce(v)); + Ok(()) + } + fn function(&mut self, name: &str) -> Option> { + self.decls.functions.get(name).cloned() + } + fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc, add: bool) -> Result<(), Option> { + self.log.push(format!("{} {} {at} {}", if add { "listen" } else { "unlisten" }, ev.key(), f.name)); + Ok(()) + } + fn random(&mut self) -> f64 { + self.rng = self.rng.wrapping_mul(1_103_515_245).wrapping_add(12345); + f64::from(self.rng >> 8) / f64::from(1u32 << 24) + } + fn same(&mut self, a: &Place, b: &Place) -> Result { + Ok(a == b) + } + fn key_code(&mut self) -> Result { + self.key.ok_or_else(|| "there's no keyboard event here".into()) } } +/// Compiles and runs `src` on a fresh timeline; the log and how the run ended. +fn exec(src: &str) -> (Vec, Result<(), Stop>, Mock) { + let c = ok(src); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + assert!(m.decls.problems(&c).is_empty(), "{:?}", m.decls.problems(&c)); + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + (std::mem::take(&mut m.log), r, m) +} + +fn lines(src: &str) -> Vec { + let (log, r, _) = exec(src); + assert_eq!(r, Ok(()), "{src}: {log:?}"); + log +} + #[test] -fn own_functions_run_where_they_are_called() { - let a = actions("function go(n:int = 1):void { gotoAndStop(3); return; trace(\"never\"); }\ngo();\nfunction twice() { go(); go(); }\ntwice();"); - assert_eq!(a.len(), 3, "{a:?}"); - assert!(a.iter().all(|x| matches!(x, Action::GotoAndStop { frame: FrameRef::Number(2), .. }))); +fn timeline_calls_run_as_actions() { + let a = lines("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();\ngotoAndStop(1); gotoAndPlay(\"run\"); gotoAndPlay(12, \"Scene 2\"); gotoAndStop('end', null); gotoAndStop(2 + 3);"); + assert_eq!(a, ["This Stop", "This Play", "This Next frame", "This Previous frame", "This Next scene", "This Previous scene", "This Go to frame 1 and stop", "This Go to “run” and play", "This Go to frame 12 in “Scene 2” and play", "This Go to “end” and stop", "This Go to frame 5 and stop"]); + let a = lines("hero_mc.gotoAndStop(\"run\");\nthis.hero_mc.arm_mc.play();\nMovieClip(parent).stop();\nMovieClip(this.parent.parent).nextFrame();\nMovieClip(root).menu.play();\n(root as MovieClip).stop();\nhero_mc.root.stop();\nObject(parent).door.prevFrame();"); + assert_eq!(a, ["This Go to “run” and stop (hero_mc)", "This Play (hero_mc.arm_mc)", "This Stop (parent)", "This Next frame (parent.parent)", "This Play (root.menu)", "This Stop (root)", "This Stop (root)", "This Previous frame (parent.door)"]); +} + +#[test] +fn typed_variables_coerce_as_actionscript_does() { + let a = lines( + "var n:int = 7.9; var u:uint = -1; var num:Number = \"2.5\"; var b:Boolean = \"no\"; var s:String = 12; var z:String; var any = \"x\";\n\ + var big:int = 2147483647; big = big + 1;\n\ + var nan:Number; var none:int;\n\ + trace(n, u, num, b, s, z, any, big, nan, none);\n\ + n += 0.7; n++; ++n; trace(n, n++ + n, --n);", + ); + assert_eq!(a, ["7 4294967295 2.5 true 12 null x -2147483648 NaN 0", "9 19 9"]); +} + +#[test] +fn expressions_follow_ecmascript() { + let a = lines( + r#"trace(1 + 2 * 3 - 4 / 8, 7 % 3, -7 % 3, 1 / 0, -1 / 0, 0 / 0); + trace("a" + 1 + 2, 1 + 2 + "a", "5" * "2", "x" - 1, true + 1, null + 1, undefined + 1); + trace(1 < 2, "b" < "a", "10" < "9", 10 < "9", NaN < 1, NaN >= 1, 2 >= 2); + trace(1 == "1", 1 === "1", null == undefined, null === undefined, 0 == false, "" == 0, NaN == NaN, "a" != "b"); + trace(0 || "x", 1 && "y", !0, !"", true ? "t" : "f", null || undefined); + trace(int("12px"), int(" 0x1F "), Number(""), Number("1e3"), String(null), Boolean("false"), uint(-2), Number("Infinity"), Number("infinity")); + trace(Math.min(3, 1, 2), Math.max(), Math.min(1, NaN), Math.abs(-4.5), Math.floor(-1.5), Math.ceil(1.2), Math.round(2.5), Math.round(-2.5), Math.round(-0.4), Math.PI > 3.14);"#, + ); + assert_eq!( + a, + [ + "6.5 1 -1 Infinity -Infinity NaN", + "a12 3a 10 NaN 2 1 NaN", + "true false true false false false true", + "true false true false true true false true", + "x y true true t undefined", + "0 31 0 1000 null true 4294967294 Infinity NaN", + "1 -Infinity NaN 4.5 -2 2 3 -2 0 true", + ] + ); +} + +#[test] +fn if_else_and_loops_run_with_break_and_continue() { + let a = lines( + "var total:int = 0;\n\ + for (var i:int = 0; i < 10; i++) { if (i == 2) continue; if (i > 5) break; total += i; }\n\ + trace(total, i);\n\ + var k:int = 3; while (k > 0) { k--; } trace(k);\n\ + do { k++; } while (k < 2); trace(k);\n\ + do { k = 100; } while (false); trace(k);\n\ + if (k > 50) trace(\"big\"); else if (k > 5) trace(\"mid\"); else trace(\"small\");\n\ + for (;;) { break; } trace(\"out\");", + ); + assert_eq!(a, ["13 6", "0", "2", "100", "big", "out"]); +} + +#[test] +fn functions_take_parameters_return_values_and_recurse() { + let a = lines( + "function add(a:int, b:int = 10):int { return a + b; }\n\ + function fact(n:Number):Number { if (n <= 1) return 1; return n * fact(n - 1); }\n\ + function hello(who:String):void { trace(\"hi \" + who); return; trace(\"never\"); }\n\ + function untyped(x) { return x; }\n\ + trace(add(1, 2), add(5), add(1.9, 0.9), fact(5), untyped(\"u\"), hello(\"you\"));\n\ + function loopy():int { var s:int; for (var j:int = 0; j < 4; j++) s += j; return s; } trace(loopy(), loopy());", + ); + assert_eq!(a, ["hi you", "3 15 1 120 u undefined", "6 6"]); +} + +#[test] +fn properties_are_read_and_set() { + let (log, r, m) = exec("hero.x = 10; hero.x += 5; hero.alpha = .5; trace(hero.x, hero.alpha, hero.name, currentFrame, this.currentFrame, hero.visible);\ngotoAndStop(4); trace(currentFrame);\nhero.rotation = hero.x * 2;"); + assert_eq!(r, Ok(())); + assert_eq!(log, ["15 0.5 hero 1 1 true", "This Go to frame 4 and stop", "4"]); + assert_eq!(m.props.get(&("hero".into(), "rotation")), Some(&30.0)); + // Reading an instance that isn't there stops the script there. + let (log, r, _) = exec("trace(\"a\");\ntrace(ghost.x);\ntrace(\"b\");"); + assert_eq!(log, ["a"]); + assert_eq!(r, Err(Stop::Error { line: 2, message: "no instance named “ghost” here".into() })); +} + +#[test] +fn listeners_name_their_events_and_functions() { + let c = ok("import flash.events.*;\nbtn.addEventListener(MouseEvent.CLICK, go);\naddEventListener(Event.ENTER_FRAME, tick);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { if (e.keyCode == Keyboard.LEFT) trace(\"left\"); });\nbtn.removeEventListener(MouseEvent.CLICK, go);\nfunction go(e:MouseEvent):void { MovieClip(e.currentTarget).gotoAndStop(2); trace(e.target.name); }\nfunction tick(e:Event):void {}\nhero.addEventListener(\"mouseOver\", go, false, 0, true);"); + assert_eq!(c.inner.len(), 1); + assert_eq!(c.functions.iter().map(|f| f.name.as_str()).collect::>(), ["go", "tick"]); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + assert_eq!(r, Ok(())); + assert_eq!(m.log, ["listen click btn go", "listen enter_frame this tick", "listen key_down stage function at line 4, column 48", "unlisten click btn go", "listen over hero go"]); + // The listener functions: the event's key code, target and current target. + m.log.clear(); + m.key = Some(37.0); + let key = c.inner[0].clone(); + assert_eq!(run::run_listener(&mut m, &key, 1000).1, Ok(())); + let go = c.functions[0].clone(); + assert_eq!(run::run_listener(&mut m, &go, 1000).1, Ok(())); + assert_eq!(m.log, ["left", "Current Go to frame 2 and stop", "e.target"]); + // Keyboard listeners belong on the stage; elsewhere they are ignored and noted. + let c = ok("addEventListener(KeyboardEvent.KEY_UP, f); function f(e) {}"); + assert!(c.body.is_empty() && c.notes[0].message.starts_with("keys go to the stage"), "{c:?}"); +} + +#[test] +fn names_from_other_frames_link_through_the_timeline() { + let frame1 = ok("var score:int = 0;\nfunction addPoints(n:int):void { score += n; }\nfunction shout():String { return \"score \" + score; }"); + let frame5 = ok("addPoints(3);\nscore = score * 2;\ntrace(shout(), lives);"); + assert_eq!(frame5.free.iter().map(|f| (f.name.as_str(), f.call)).collect::>(), [("addPoints", true), ("score", false), ("shout", true), ("lives", false)]); + let d = Decls::build([&frame1, &frame5]); + let p = d.problems(&frame5); + assert_eq!(p.len(), 1, "{p:?}"); + assert_eq!((p[0].line, p[0].column), (3, 16)); + assert!(p[0].message.starts_with("`lives` isn't a variable of this timeline"), "{}", p[0].message); + let ok5 = ok("addPoints(3);\nscore = score * 2;\ntrace(shout());"); + let d = Decls::build([&frame1, &ok5]); + assert!(d.problems(&ok5).is_empty() && d.problems(&frame1).is_empty()); + let mut m = Mock { decls: d, ..Mock::default() }; + for c in [&frame1, &ok5] { + assert_eq!(run::run_script(&mut m, &c.body, &c.inner, 10_000).1, Ok(())); + } + assert_eq!(m.log, ["score 6"]); + // A function declared on two frames, or a variable with two types, is a problem. + let again = ok("function shout():String { return \"again\"; }\nvar score:String;"); + let d = Decls::build([&frame1, &again]); + assert_eq!(d.problems(&again).len(), 2, "{:?}", d.problems(&again)); +} + +#[test] +fn fuel_stops_an_endless_loop_cleanly() { + let c = ok("trace(\"before\");\nwhile (true) {}\ntrace(\"after\");"); + let mut m = Mock::default(); + let (used, r) = run::run_script(&mut m, &c.body, &c.inner, 5_000); + assert_eq!((used, r), (5_000, Err(Stop::Fuel))); + assert_eq!(m.log, ["before"]); + // Recursion is bounded by depth, text by length, and both stop the run. + let (_, r, _) = exec("function f(n:int):int { return f(n + 1); } f(0);"); + assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("more than 16 deep")), "{r:?}"); + let (_, r, _) = exec("var s:String = \"x\"; while (true) s = s + s;"); + assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("longer than 16384")), "{r:?}"); + // Building text costs fuel for its length. + let c = ok("var s:String = \"\"; for (var i:int = 0; i < 100000; i++) s = s + \"ab\";"); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + assert_eq!(run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN).1, Err(Stop::Fuel)); +} + +#[test] +fn random_comes_from_the_world() { + let a = lines("var r:Number = Math.random(); trace(r >= 0 && r < 1, Math.floor(Math.random() * 6) + 1 <= 6);"); + assert_eq!(a, ["true true"]); } #[test] fn calls_outside_the_movie_are_ignored_and_noted() { let c = ok("navigateToURL(new URLRequest(\"https://example.com\"), \"_blank\");\nflash.net.navigateToURL(x);\nExternalInterface.call(\"f\");\nfscommand(\"quit\");\nbtn.buttonMode = true;\nstop();"); - assert_eq!(c.ops, vec![ScriptOp::Action(Action::Stop { target: t("") })]); + assert_eq!(c.body.len(), 1); let lines: Vec = c.notes.iter().map(|n| n.line).collect(); assert_eq!(lines, [1, 2, 3, 4, 5]); assert!(c.notes[0].message.contains("navigateToURL") && c.notes[0].message.contains("ignored"), "{:?}", c.notes); @@ -127,50 +279,52 @@ fn calls_outside_the_movie_are_ignored_and_noted() { #[test] fn comments_white_space_and_semicolons_are_read_as_actionscript_does() { - // Line and block comments, CR LF line ends, no semicolons, a BOM, empty statements. - let a = actions("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\""); - assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }]); + let a = lines("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\""); + assert_eq!(a, ["This Stop", "This Play"]); assert_eq!(err("stop() play()"), (1, 8, "expected `;` or a new line, found `play`".into())); } #[test] fn every_problem_says_where_it_is() { let cases: &[(&str, u32, u32, &str)] = &[ - ("stop();\nif (x) { play(); }", 2, 1, "`if` statements aren't supported yet"), - ("var n:int = 0;", 1, 1, "variables (`var`) aren't supported yet"), - (" for (var i = 0; i < 3; i++) {}", 1, 3, "`for` loops aren't supported yet"), - ("while (true) stop();", 1, 1, "`while` loops aren't supported yet"), + (" for each (var v in list) {}", 1, 3, "`for each` loops aren't supported yet"), + ("for (var k in o) {}", 1, 1, "`for in` loops aren't supported yet"), ("switch (x) { case 1: stop(); }", 1, 1, "`switch` statements aren't supported yet"), - ("hero.x += 5;", 1, 1, "`+=` reads a value first"), + ("var a:Array = [];", 1, 7, "variables of type `Array` aren't supported yet"), + ("var x:int = 1;", 1, 5, "`x` is already a name of the timeline"), ("hero.width = 5;", 1, 1, "setting `width` isn't supported yet"), - ("score = 5;", 1, 1, "setting `score` isn't supported: variables"), - ("foo();", 1, 1, "`foo` isn't declared in this frame script"), + ("currentFrame = 5;", 1, 1, "`currentFrame` can only be read"), ("hero.addChild(x);", 1, 1, "calling `addChild` isn't supported"), ("gotoAndStop(0);", 1, 13, "a frame number is a whole number from 1"), ("gotoAndStop(1.5);", 1, 13, "a frame number is a whole number"), - ("gotoAndStop(frame);", 1, 13, "reading `frame` isn't supported"), ("gotoAndStop();", 1, 1, "`gotoAndStop` takes a frame"), ("stop(1);", 1, 1, "`stop()` takes no arguments"), ("hero.nextScene();", 1, 1, "call `nextScene()` in the main timeline's own script"), - ("trace(hero.x);", 1, 7, "reading properties isn't supported"), - ("trace([1]);", 1, 7, "only values written out"), - ("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "the stage isn't supported"), - ("b.addEventListener(Event.ENTER_FRAME, f); function f(e) {}", 1, 20, "listening for Event.ENTER_FRAME isn't supported yet"), - ("b.addEventListener(MouseEvent.CLICK, nope);", 1, 38, "`nope` isn't a function declared"), + ("trace(hero.width);", 1, 7, "reading `width` isn't supported yet"), + ("trace([1]);", 1, 7, "arrays aren't supported yet"), + ("trace(stage.stageWidth);", 1, 7, "`stage.stageWidth` isn't supported yet"), + ("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "mouse listeners on the stage"), + ("b.addEventListener(Event.RESIZE, f); function f(e) {}", 1, 20, "listening for Event.RESIZE isn't supported yet"), ("b.addEventListener(MouseEvent.CLICK, f); function f() { stop(); }", 1, 42, "a listener function takes the event"), ("b.addEventListener(MouseEvent.CLICK, f, true); function f(e) {}", 1, 41, "capture-phase listeners"), - ("b.addEventListener(MouseEvent.CLICK, f); function f(e) { trace(e.target.name); }", 1, 64, "reading the event `e`"), - ("b.addEventListener(MouseEvent.CLICK, f); function f(e) { e.target.play(); }", 1, 58, "`target` can be a part inside"), - ("b.addEventListener(MouseEvent.CLICK, f); function f(e) { c.addEventListener(MouseEvent.CLICK, f); }", 1, 58, "adding a listener from inside a listener"), - ("b.removeEventListener(MouseEvent.CLICK, f);", 1, 1, "removing listeners isn't supported yet"), - ("function f() { f(); } f();", 1, 16, "`f` calls itself"), + ("b.addEventListener(MouseEvent.CLICK, f); function f(e:MouseEvent) { trace(e.stageX); }", 1, 75, "reading the event's `stageX`"), + ("b.removeEventListener(MouseEvent.CLICK, function (e) {});", 1, 41, "a function written in place can't be removed"), ("function stop() {}", 1, 1, "a function named `stop` would hide"), ("function f() {} function f() {}", 1, 17, "`f` is declared twice"), ("function f() { function g() {} } f();", 1, 16, "functions declared inside functions"), - ("function f(n) { n.play(); } f(1);", 1, 17, "reading the parameter `n`"), + ("function f(a:int, n) { n.play(); } f(1, 2);", 1, 24, "`n` is a variable, not an instance"), + ("function f(a:int) {} f();", 1, 22, "`f` takes 1 argument, not 0"), + ("function f(...rest) {}", 1, 15, "rest parameters"), + ("var n:int; n.play();", 1, 12, "`n` is a variable, not an instance"), + ("var s:String = \"ab\"; trace(s.length);", 1, 28, "reading `length` of a value"), ("hero_mc[\"arm\"].play();", 1, 1, "this isn't an instance"), - ("hero_mc.x = \"10\";", 1, 13, "`x` is set to a number"), - ("hero_mc.x = 1 / 0;", 1, 13, "the value must be a finite number"), + ("trace(new Date());", 1, 7, "`new` isn't supported yet"), + ("trace(1 & 2);", 1, 7, "the `&` operator isn't supported yet"), + ("var n:int; n <<= 2;", 1, 12, "`<<=` isn't supported yet"), + ("break;", 1, 1, "`break` is only for loops here"), + ("trace(stop());", 1, 7, "`stop()` gives no value"), + ("trace(Math.sqrt(4));", 1, 7, "`Math.sqrt` isn't supported yet"), + ("trace(Keyboard.WIGGLE);", 1, 7, "`Keyboard.WIGGLE` isn't a key"), ("package { }", 1, 1, "`package` belongs to class files"), ("class Hero {}", 1, 1, "`class` belongs to class files"), ("public function f() {}", 1, 1, "`public` declarations belong to classes"), @@ -183,9 +337,8 @@ fn every_problem_says_where_it_is() { ("stop(); #", 1, 9, "unexpected character '#'"), ("var re = /ab+c/;", 1, 10, "regular expressions aren't supported"), ("1 = 2;", 1, 3, "the left side of this assignment can't be assigned to"), - ("x++;", 1, 1, "`++` and `--` read a value first"), ("é.play();", 1, 1, "`é` isn't an instance name AniCraft can address"), - ("\tstop();\n\t\tif (a) {}", 2, 3, "`if` statements"), + ("\tstop();\n\t\twith (a) {}", 2, 3, "`with` statements"), ]; for (src, line, col, msg) in cases { let (l, c, m) = err(src); @@ -195,19 +348,34 @@ fn every_problem_says_where_it_is() { #[test] fn every_problem_is_listed_and_nothing_half_runs() { - let p = compile("stop();\nvar a = 1;\nif (a) {}\nplay();\nhero.width = 3;").unwrap_err(); + let p = compile("stop();\nvar a:Array;\nswitch (a) {}\nplay();\nhero.width = 3;").unwrap_err(); let at: Vec<(u32, u32)> = p.iter().map(|p| (p.line, p.column)).collect(); - assert_eq!(at, [(2, 1), (3, 1), (5, 1)]); - assert_eq!(p[0].to_string(), "line 2, column 1: variables (`var`) aren't supported yet"); - let many: String = (0..200).map(|i| format!("var v{i} = {i};\n")).collect(); + assert_eq!(at, [(2, 7), (3, 1), (5, 1)]); + let many: String = (0..200).map(|i| format!("hero.w{i} = {i};\n")).collect(); assert_eq!(compile(&many).unwrap_err().len(), MAX_PROBLEMS); } #[test] fn number_text_matches_actionscript() { for (n, s) in [(0.0, "0"), (-0.0, "0"), (5.0, "5"), (-3.25, "-3.25"), (0.1 + 0.2, "0.30000000000000004"), (1e21, "1e+21"), (1.5e-7, "1.5e-7"), (123456789012.0, "123456789012"), (f64::NAN, "NaN"), (f64::NEG_INFINITY, "-Infinity"), (0.000001, "0.000001")] { - assert_eq!(lower::number_text(n), s, "{n}"); + assert_eq!(number_text(n), s, "{n}"); } + for (s, n) in [("", 0.0), (" 12 ", 12.0), ("1e3", 1000.0), (".5", 0.5), ("5.", 5.0), ("-0x10", f64::NAN), ("0x10", 16.0), ("0b101", 5.0), ("+Infinity", f64::INFINITY), ("inf", f64::NAN), ("1_0", f64::NAN), ("\u{a0}7\u{feff}", 7.0), ("1e", f64::NAN), ("-", f64::NAN)] { + let v = string_number(s); + assert!(v == n || (v.is_nan() && n.is_nan()), "{s:?}: {v}"); + } + assert_eq!((to_int32(4_294_967_296.0 + 5.0), to_int32(-1.5), to_uint32(-1.0), to_int32(f64::NAN)), (5, -1, 4_294_967_295, 0)); + assert_eq!((run::round(0.49999999999999994), run::round(-0.5), run::round(1.5)), (0.0, 0.0, 2.0)); +} + +#[test] +fn the_ir_reads_and_writes_as_json() { + let c = ok("var n:Number = NaN; var s:String = \"a\"; if (n != n) trace(s + 1, -Infinity); function f(e:MouseEvent = null):void {} btn.addEventListener(MouseEvent.CLICK, f);"); + let v = serde_json::to_value(&c).unwrap(); + let back: Compiled = serde_json::from_value(v.clone()).unwrap(); + assert_eq!(back, c); + let text = v.to_string(); + assert!(text.contains("\"nan\"") && text.contains("{\"inf\":false}") && text.contains("\"s\":\"if\""), "{text}"); } #[test] @@ -218,25 +386,41 @@ fn limits_are_problems_not_crashes() { assert!(err(&deep).2.contains("nested more than")); let deep = format!("trace({}1);", "-".repeat(100_000)); assert!(err(&deep).2.contains("nested more than")); - let deep = format!("{}1;", "a = ".repeat(10_000)); + let deep = format!("var a; {}1;", "a = ".repeat(10_000)); assert!(err(&deep).2.contains("nested more than")); + // A long row of operators would make a deep tree; it counts as nesting. + let long = format!("trace({}1);", "1 + ".repeat(10_000)); + let m = err(&long).2; + assert!(m.contains("too many operators in a row") || m.contains("nested more than"), "{m}"); let deep = format!("b.addEventListener(\"click\", {}", "function (e) { ".repeat(5_000)); assert!(err(&deep).2.contains("nested more than")); let long = "stop();".repeat(MAX_RUN_BYTES / 7 + 1); assert!(err(&long).2.contains("longer than 256 KiB")); let tokens = ";".repeat(MAX_TOKENS + 1); assert!(err(&tokens).2.contains("tokens")); - let steps = "stop();".repeat(crate::MAX_ACTIONS + 1); - assert!(err(&steps).2.contains("at most 256 steps")); - // Calls that fan out are bounded, however deep they could go. - let mut src = String::from("function f0() { stop(); }\n"); - for i in 1..16 { - src.push_str(&format!("function f{i}() {{ {} }}\n", format!("f{}(); ", i - 1).repeat(8))); +} + +/// The deepest code the limits allow runs in a small stack: calls 16 deep, each as nested as +/// the parser lets code be. +#[test] +fn the_deepest_allowed_code_fits_a_small_stack() { + let nest = |depth: usize| format!("{}n{}", "(1 + ".repeat(depth), ")".repeat(depth)); + let mut src = String::from("function f0(n:int):int { return n; }\n"); + for i in 1..20 { + src.push_str(&format!("function f{i}(n:int):int {{ return f{}({}); }}\n", i - 1, nest(18))); } - src.push_str("f15();"); - let t0 = std::time::Instant::now(); - assert!(compile(&src).is_err()); - assert!(t0.elapsed().as_secs_f32() < 5.0); + src.push_str("trace(f19(0));"); + let c = ok(&src); + let r = std::thread::Builder::new() + .stack_size(512 * 1024) + .spawn(move || { + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN).1 + }) + .unwrap() + .join() + .unwrap(); + assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("deep")), "{r:?}"); } /// A small deterministic generator (no clock, no randomness crate). @@ -256,20 +440,25 @@ impl Rng { #[test] fn hostile_input_never_panics_and_ends_quickly() { - const PIECES: [&str; 64] = [ - "stop", "play", "gotoAndStop", "(", ")", "{", "}", "[", "]", ";", ",", ".", "\n", " ", "\"a", "\"", "'", "\\", "/*", "*/", "//", "1", "0x", "1e", ".5", "e", "function", "f", "e:MouseEvent", ":void", "addEventListener", "MouseEvent.CLICK", "=", "+", "-", "!", "?", ":", "if", "else", "var", "for", "new", "this", "parent", "root", "MovieClip", "as", "trace", "x", "alpha", "é", "\u{0}", "\r", "\t", "<", ">", "...", "::", "..", ".<", "return", "import", "@", + const PIECES: [&str; 80] = [ + "stop", "play", "gotoAndStop", "(", ")", "{", "}", "[", "]", ";", ",", ".", "\n", " ", "\"a", "\"", "'", "\\", "/*", "*/", "//", "1", "0x", "1e", ".5", "e", "function", "f", "e:MouseEvent", ":void", "addEventListener", "MouseEvent.CLICK", "=", "+", "-", "!", "?", ":", "if", "else", "var", "for", "new", "this", "parent", "root", "MovieClip", "as", "trace", "x", "alpha", "é", "\u{0}", "\r", "\t", "<", ">", "...", "::", "..", ".<", "return", "import", "@", "while", "do", "break", "continue", "int", "n", "++", "+=", "==", "&&", "||", "Math.random()", "e.keyCode", "stage", "Event.ENTER_FRAME", "removeEventListener", ]; let mut rng = Rng(0x9e37_79b9_7f4a_7c15); let t0 = std::time::Instant::now(); let mut compiled = 0; - for _ in 0..4_000 { + for _ in 0..5_000 { let n = rng.next() as usize % 80; let src: String = (0..n).map(|_| rng.pick(&PIECES)).collect(); - if compile(&src).is_ok() { + if let Ok(c) = compile(&src) { compiled += 1; + // What compiles runs, within its fuel, whatever it is. + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + let _ = run::run_script(&mut m, &c.body, &c.inner, 2_000); + for f in &c.functions { + let _ = run::run_listener(&mut m, f, 2_000); + } } } - // Raw bytes as text, too. for _ in 0..1_000 { let n = rng.next() as usize % 200; let bytes: Vec = (0..n).map(|_| rng.next() as u8).collect(); @@ -286,8 +475,16 @@ fn compiles_once_per_script() { let b: *const crate::CompileResult = s.compiled(); assert!(std::ptr::eq(a, b)); assert!(s.runs()); - // A copy compiles on its own (its text may change); equality ignores the cache. let c = s.clone(); assert_eq!(c, s); assert!(!crate::SourceScript::new(crate::Language::ActionScript1or2, "stop();").runs()); } + +#[test] +fn trace_lines_are_cut_at_whole_characters() { + let long = "é".repeat(2000); + let cut = run::trace_line(long); + assert_eq!(cut.chars().count(), crate::MAX_TRACE_CHARS + 1); + let emoji = format!("{}{}", "a".repeat(crate::MAX_TRACE_CHARS - 1), "😀".repeat(5)); + assert_eq!(run::trace_line(emoji).encode_utf16().count(), crate::MAX_TRACE_CHARS); +} diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index e3170648..b1eb167e 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -14,7 +14,9 @@ //! 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::as3::ir::{Base, Function, ListenEvent, Place, Prop, Value}; +use crate::actions::as3::run::{self, Stop, World}; +use crate::actions::as3::{Compiled, Decls, Problem}; 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; @@ -40,6 +42,13 @@ pub const MAX_OUTPUT_PER_STEP: usize = 1_000; pub const MAX_EVENTS_PER_STEP: usize = 256; /// Most listeners scripts add to one instance. pub const MAX_LISTENERS_PER_INSTANCE: usize = 16; +/// Most listeners scripts add to the stage. +pub const MAX_STAGE_LISTENERS: usize = 64; +/// Script fuel one step may use, all scripts and listeners together (each run has at most +/// [`run::FUEL_PER_RUN`]). +pub const MAX_FUEL_PER_STEP: u64 = 1_000_000; +/// The random generator's seed when none is given. +pub const DEFAULT_SEED: u64 = 0; /// A timeline's playhead. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -108,16 +117,54 @@ 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. +/// A listener a script added to an instance or the stage (ADR 0013 tiers 2 and 2.5): 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 event: ListenEvent, + /// The timeline whose script added it: the function runs there. pub owner: InstancePath, /// The function's name: the same function for the same event is added once. pub function: String, - pub actions: Arc>, + pub func: Arc, + /// When it was added (enter-frame listeners run in this order). + pub seq: u64, +} + +/// The movie's random numbers (`Math.random()`): Marsaglia's xorshift128, seeded, so a movie +/// with the same seed and input always plays the same. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rng(pub [u32; 4]); + +impl Rng { + pub fn seeded(seed: u64) -> Rng { + let lo = (seed & 0xffff_ffff) as u32; + let hi = (seed >> 32) as u32; + let mut s = [lo ^ 0x9e37_79b9, hi ^ 0x243f_6a88, 0xb7e1_5162, 0x3c6e_f372]; + if s == [0; 4] { + s[0] = 1; + } + Rng(s) + } + fn next_u32(&mut self) -> u32 { + let [x, y, z, w] = self.0; + let t = x ^ (x << 11); + let w2 = w ^ (w >> 19) ^ (t ^ (t >> 8)); + self.0 = [y, z, w, w2]; + w2 + } + /// The next number in [0, 1), from 53 random bits. + pub fn next_f64(&mut self) -> f64 { + let a = f64::from(self.next_u32() >> 5); + let b = f64::from(self.next_u32() >> 6); + (a * 67_108_864.0 + b) / 9_007_199_254_740_992.0 + } +} + +impl Default for Rng { + fn default() -> Self { + Rng::seeded(DEFAULT_SEED) + } } /// Everything that changes while a movie plays. @@ -130,8 +177,18 @@ pub struct PlayerState { pub clips: BTreeMap, /// Properties actions have set, per instance. pub props: BTreeMap, - /// Mouse listeners scripts added, per instance, in the order added. + /// Listeners scripts added, per instance, in the order added. pub listeners: BTreeMap>, + /// Listeners on the stage (keyboard and enter-frame), in the order added. + pub stage: Vec, + /// Each timeline instance's variables (ADR 0013 tier 2.5), by name. + pub vars: BTreeMap>, + /// The random generator. + pub rng: Rng, + /// The last pointer position seen (`mouseX`/`mouseY` keep it when the pointer leaves). + pub mouse: Vec2, + /// Listeners added so far (each one's `seq`). + pub seq: u64, /// The pointer in stage space (`None` when it is outside the movie), and whether it is down. pub pointer: Option, pub down: bool, @@ -144,6 +201,11 @@ pub struct PlayerState { } impl PlayerState { + /// A state before the first frame, with the random generator seeded. + pub fn seeded(seed: u64) -> PlayerState { + PlayerState { rng: Rng::seeded(seed), ..PlayerState::default() } + } + /// The frame a movie clip instance shows (`len` frames long). pub fn clip_frame(&self, path: &[ElementId], len: u32) -> u32 { self.clips.get(path).map_or(0, |c| c.frame).min(len.max(1) - 1) @@ -175,6 +237,9 @@ pub enum Event { Up(Vec2), /// The pointer left the movie. Leave, + /// A key went down (or repeats) and came up, by its ActionScript key code. + KeyDown(u32), + KeyUp(u32), } /// The state after a step, what the movie wrote to the Output panel (traces, and why an @@ -215,6 +280,10 @@ pub struct Node { pub frames: u32, /// Local → stage. pub xf: Affine, + /// The instance's own transform and alpha in its parent, as the timeline gives them (before + /// properties scripts set). + pub local: Affine, + pub alpha: f32, /// Pointer events can reach it (visible, not mask artwork). pub hittable: bool, pub events: Vec, @@ -261,8 +330,13 @@ impl ScriptHost for NoScripts { /// The movie at its first frame, with the first frame's actions run. pub fn start(doc: &Document, host: &mut dyn ScriptHost) -> Step { + start_seeded(doc, DEFAULT_SEED, host) +} + +/// [`start`], with `Math.random()` seeded by `seed`. +pub fn start_seeded(doc: &Document, seed: u64, host: &mut dyn ScriptHost) -> Step { host.begin_step(); - let mut r = Run::new(doc, PlayerState::default(), host); + let mut r = Run::new(doc, PlayerState::seeded(seed), host); r.refresh(); r.pending.push_front(Vec::new()); r.settle(); @@ -278,6 +352,9 @@ pub fn step(doc: &Document, state: &PlayerState, events: &[Event], host: &mut dy r.refresh(); r.remember_graphics(); r.advance(); + // Enter-frame listeners hear the new frame before its frame scripts run (as ActionScript + // dispatches `enterFrame` before frame scripts). + r.enter_frame(); r.settle(); for e in events.iter().take(MAX_EVENTS_PER_STEP) { r.event(*e); @@ -303,7 +380,7 @@ pub fn input(doc: &Document, state: &PlayerState, events: &[Event], host: &mut d /// drawing order (parents before their contents). pub fn tree(doc: &Document, st: &PlayerState) -> Vec { let tl = doc.timeline(st.scene); - let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, hittable: true, events: Vec::new(), gain: 1.0 }]; + let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, local: Affine::IDENTITY, alpha: 1.0, hittable: true, events: Vec::new(), gain: 1.0 }]; // The main timeline is seen through its camera (ADR 0027): instances are where the pointer // sees them. let camera = tl.camera_at(st.root.frame, &doc.stage); @@ -358,7 +435,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi }; let idx = out.len(); let node_xf = layer_xf.mul(&e.transform); - out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, hittable: hit && shown, events: events.clone(), gain }); + out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, local: el.transform, alpha: el.color.alpha, hittable: hit && shown, events: events.clone(), gain }); // Names inside a movie clip (or a button's states) are its own; a graphic's // contents belong to the timeline the graphic is on. let inner_owner = if kind == NodeKind::Graphic { owner } else { idx }; @@ -423,11 +500,16 @@ struct Run<'a, 'h> { /// The frame each graphic showed when the step began: one that shows another frame at /// its end has entered it (and starts its sounds). graphics: BTreeMap, + /// Each timeline's declarations (ADR 0013 tier 2.5), made the first time a script there + /// needs them. + decls: BTreeMap>, + /// Script fuel left this step. + fuel: u64, } impl<'a, 'h> Run<'a, 'h> { fn new(doc: &'a Document, st: PlayerState, host: &'h mut dyn ScriptHost) -> Self { - Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new() } + Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new(), decls: BTreeMap::new(), fuel: MAX_FUEL_PER_STEP } } fn remember_graphics(&mut self) { @@ -492,6 +574,9 @@ impl<'a, 'h> Run<'a, 'h> { list.retain(|l| all.contains(&l.owner)); all.contains(p) && !list.is_empty() }); + self.st.stage.retain(|l| all.contains(&l.owner)); + // A timeline's variables go with its instance. + self.st.vars.retain(|p, _| all.contains(p)); for slot in [&mut self.st.hover, &mut self.st.pressed] { if slot.as_ref().is_some_and(|p| !all.contains(p)) { *slot = None; @@ -600,7 +685,7 @@ impl<'a, 'h> Run<'a, 'h> { // than a line every time the playhead passes. FrameScript::Source(src) => { if let Ok(c) = src.compiled() { - self.run_ops(path, &c.ops); + self.run_script(path, frame, c); } } } @@ -630,43 +715,254 @@ impl<'a, 'h> Run<'a, 'h> { } } - /// 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() { + /// The declarations of the timeline node `i` is (the main timeline's span every scene). + fn decls_of(&mut self, i: usize) -> Arc { + let key = match self.nodes.get(i) { + Some(Node { kind: NodeKind::MovieClip, symbol: Some(s), .. }) => TimelineRef::Symbol(*s), + _ => TimelineRef::Root, + }; + let doc = self.doc; + self.decls.entry(key).or_insert_with(|| Arc::new(decls(doc, key))).clone() + } + + /// Runs a compiled frame script on timeline `owner` (ADR 0013 tier 2.5): when every name + /// it takes from other frames is there, its statements run with the fuel the step has left. + fn run_script(&mut self, owner: &[ElementId], frame: u32, c: &'a Compiled) { + let Some(i) = self.index_of(owner) else { return }; + let d = self.decls_of(i); + // A script whose names don't link doesn't run (Test Movie lists why at the start). + if !d.problems(c).is_empty() { + return; + } + let where_ = format!("Script on frame {} of {}", u64::from(frame) + 1, self.timeline_name(i)); + self.run_code(owner, d, None, &where_, |w, fuel| run::run_script(w, &c.body, &c.inner, fuel)); + } + + /// Runs code on timeline `owner` with this step's fuel; writes why it stopped early. + fn run_code(&mut self, owner: &[ElementId], decls: Arc, ev: Option, where_: &str, go: impl FnOnce(&mut dyn World, u64) -> (u64, Result<(), Stop>)) { + if self.halted { + return; + } + if self.fuel == 0 { + self.halt(&format!("scripts ran more than {MAX_FUEL_PER_STEP} steps")); + return; + } + let fuel = self.fuel.min(run::FUEL_PER_RUN); + let mut w = Script { r: self, owner: owner.to_vec(), decls, ev }; + let (used, r) = go(&mut w, fuel); + self.fuel = self.fuel.saturating_sub(used); + match r { + Ok(()) | Err(Stop::Halt) => {} + Err(e) => self.out(format!("{where_} stopped: {}", e.describe())), + } + } + + /// How Output names a timeline: the main timeline, or the instance-name path of a clip. + fn timeline_name(&self, i: usize) -> String { + if i == 0 { + return "the main timeline".into(); + } + let mut names = Vec::new(); + let mut cur = i; + for _ in 0..=MAX_SYMBOL_DEPTH { + let Some(n) = self.nodes.get(cur) else { break }; + if n.kind == NodeKind::Root { + break; + } + names.push(if n.name.is_empty() { "?" } else { n.name.as_str() }); + cur = n.owner; + } + names.reverse(); + names.join(".") + } + + /// Calls listener `l` with the event. + fn call_listener(&mut self, l: &Listening, ev: EventInfo) { + self.refresh(); + let Some(i) = self.index_of(&l.owner) else { return }; + let d = self.decls_of(i); + let f = l.func.clone(); + let where_ = format!("Listener {}", l.function); + self.run_code(&l.owner, d, Some(ev), &where_, |w, fuel| run::run_listener(w, &f, fuel)); + } + + /// Every enter-frame listener, in the order they were added. + fn enter_frame(&mut self) { + self.refresh(); + let mut all: Vec<(Option, Listening)> = self.st.listeners.iter().flat_map(|(p, list)| list.iter().filter(|l| l.event == ListenEvent::EnterFrame).map(|l| (Some(p.clone()), l.clone()))).collect(); + all.extend(self.st.stage.iter().filter(|l| l.event == ListenEvent::EnterFrame).map(|l| (None, l.clone()))); + all.sort_by_key(|(_, l)| l.seq); + for (at, l) in all { + if self.halted { return; } - match op { - ScriptOp::Action(a) => self.exec(owner, a, true), - ScriptOp::Listen(l) => self.listen(owner, l), + self.call_listener(&l, EventInfo { key: None, target: at.clone(), current: at }); + self.settle(); + } + } + + /// A key event: the stage's listeners for it, in the order added. + fn key(&mut self, event: ListenEvent, code: u32) { + let list: Vec = self.st.stage.iter().filter(|l| l.event == event).cloned().collect(); + for l in list { + if self.halted { + return; + } + self.call_listener(&l, EventInfo { key: Some(code), target: None, current: None }); + self.settle(); + } + } + + /// The node an instance name stands for, from timeline node `from` (`Ok(None)`: the stage). + fn place(&self, from: usize, ev: Option<&EventInfo>, at: &Place) -> Result, String> { + let base = match at.base { + Base::This => from, + Base::Stage => { + return if at.path.is_this() { Ok(None) } else { Err("instances on the stage are named from the main timeline (root)".into()) }; + } + Base::Target | Base::Current => { + let Some(ev) = ev else { return Err("there's no event here".into()) }; + let p = if at.base == Base::Target { &ev.target } else { &ev.current }; + match p { + None if at.path.is_this() => return Ok(None), + None => return Err("the event's target is the stage".into()), + Some(p) => self.index_of(p).ok_or("the event's target has left the stage")?, + } + } + }; + self.resolve(base, &at.path).map(Some) + } + + /// The path of the node `base` starts from (for actions on the event's target). + fn base_path(&self, owner: &[ElementId], ev: Option<&EventInfo>, base: Base) -> Result { + match base { + Base::This => Ok(owner.to_vec()), + Base::Stage => Err("the stage has no playhead".into()), + Base::Target | Base::Current => { + let Some(ev) = ev else { return Err("there's no event here".into()) }; + let p = if base == Base::Target { &ev.target } else { &ev.current }; + p.clone().ok_or_else(|| "the event's target is the stage".into()) } } } - /// `addEventListener`: the instance the listener's target names gets it (once per - /// function and event). - fn listen(&mut self, owner: &[ElementId], l: &Listener) { + /// A property of node `i` (`None`: the stage). + fn property(&self, i: Option, p: Prop) -> Result { + let num = |v: f64| Ok(Value::Num(v)); + let Some(i) = i else { + return match p { + Prop::MouseX => num(short(self.st.mouse.x)), + Prop::MouseY => num(short(self.st.mouse.y)), + _ => Err(format!("the stage's `{}` isn't supported here", p.name())), + }; + }; + let Some(n) = self.nodes.get(i) else { return Err("the instance is gone".into()) }; + if n.kind == NodeKind::Root { + return match p { + Prop::X | Prop::Y | Prop::Rotation => num(0.0), + Prop::Alpha | Prop::ScaleX | Prop::ScaleY => num(1.0), + Prop::Visible => Ok(Value::Bool(true)), + Prop::CurrentFrame => num(f64::from(self.st.root.frame) + 1.0), + Prop::TotalFrames => num(self.doc.scenes.iter().map(|s| f64::from(s.timeline.frame_count())).sum()), + Prop::CurrentLabel => Ok(current_label(self.doc.timeline(self.st.scene), self.st.root.frame)), + Prop::MouseX => num(short(self.st.mouse.x)), + Prop::MouseY => num(short(self.st.mouse.y)), + Prop::Name => Ok(Value::str("root1")), + }; + } + let ov = self.st.props.get(&n.path).copied().unwrap_or_default(); + let d = decompose64(&n.local); + let deg = 180.0 / std::f64::consts::PI; + let pick = |o: Option, v: f64| num(o.map_or(fround_short(v), short)); + match p { + Prop::X => pick(ov.x, d[0]), + Prop::Y => pick(ov.y, d[1]), + Prop::ScaleX => pick(ov.scale_x, d[2]), + Prop::ScaleY => pick(ov.scale_y, d[3]), + Prop::Rotation => pick(ov.rotation, d[4] * deg), + Prop::Alpha => num(short(ov.alpha.unwrap_or(n.alpha))), + Prop::Visible => Ok(Value::Bool(ov.visible != Some(false))), + Prop::Name => Ok(Value::str(&n.name)), + Prop::MouseX | Prop::MouseY => { + let m = n.xf.m.map(f64::from); + let det = m[0] * m[3] - m[1] * m[2]; + if det == 0.0 || !det.is_finite() { + return num(0.0); + } + let (x, y) = (f64::from(self.st.mouse.x) - m[4], f64::from(self.st.mouse.y) - m[5]); + let v = if p == Prop::MouseX { (m[3] * x - m[2] * y) / det } else { (m[0] * y - m[1] * x) / det }; + num(fround_short(v)) + } + Prop::CurrentFrame | Prop::TotalFrames | Prop::CurrentLabel => { + if n.kind != NodeKind::MovieClip { + let what = if n.kind == NodeKind::Button { "a button" } else { "a graphic" }; + return Err(format!("“{}” is {what}; only movie clips and the main timeline have frames", n.name)); + } + match p { + Prop::CurrentFrame => num(f64::from(n.frame) + 1.0), + Prop::TotalFrames => num(f64::from(n.frames)), + _ => Ok(n.symbol.and_then(|s| self.doc.symbol(s)).map_or(Value::Null, |s| current_label(&s.timeline, n.frame))), + } + } + } + } + + /// `addEventListener` / `removeEventListener` from timeline `owner`. + fn listen(&mut self, owner: &[ElementId], ev: Option<&EventInfo>, at: &Place, event: ListenEvent, f: &Arc, add: bool) { 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) { + let what = format!("{} for {} ({at})", if add { "Listen" } else { "Stop listening" }, event.key()); + let i = match self.place(from, ev, at) { Ok(i) => i, Err(e) => return self.out(format!("{what}: {e}")), }; + let seq = self.st.seq; + let item = Listening { event, owner: owner.to_vec(), function: f.name.clone(), func: f.clone(), seq }; + let same = |x: &Listening| x.event == event && x.owner == owner && x.function == f.name; + let Some(i) = i else { + // The stage: keyboard and enter-frame listeners. + if add { + if self.st.stage.iter().any(same) { + return; + } + if self.st.stage.len() >= MAX_STAGE_LISTENERS { + return self.out(format!("{what}: the stage already has {MAX_STAGE_LISTENERS} listeners")); + } + self.st.seq += 1; + self.st.stage.push(item); + } else { + self.st.stage.retain(|x| !same(x)); + } + return; + }; let Some(node) = self.nodes.get(i) else { return }; - if !matches!(node.kind, NodeKind::Button | NodeKind::MovieClip) { + let ok = match event { + ListenEvent::EnterFrame => node.kind != NodeKind::Graphic, + _ => matches!(node.kind, NodeKind::Button | NodeKind::MovieClip), + }; + if !ok { 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()); + if !add { + if let Some(list) = self.st.listeners.get_mut(&path) { + list.retain(|x| !same(x)); + if list.is_empty() { + self.st.listeners.remove(&path); + } + } + return; + } 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) { + if list.iter().any(same) { 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() }); + list.push(item); + self.st.seq += 1; } /// The node `target` names, seen from timeline node `from`. @@ -836,6 +1132,8 @@ impl<'a, 'h> Run<'a, 'h> { } } Event::Leave => self.pointer(None), + Event::KeyDown(k) => self.key(ListenEvent::KeyDown, k), + Event::KeyUp(k) => self.key(ListenEvent::KeyUp, k), } } @@ -843,6 +1141,9 @@ impl<'a, 'h> Run<'a, 'h> { fn pointer(&mut self, p: Option) { self.refresh(); self.st.pointer = p; + if let Some(p) = p { + self.st.mouse = p; + } let now = p.and_then(|p| hit_in(self.doc, &self.st, &self.nodes, p)); if now != self.st.hover { let old = std::mem::replace(&mut self.st.hover, now.clone()); @@ -863,15 +1164,16 @@ impl<'a, 'h> Run<'a, 'h> { let Some(n) = self.index_of(path).and_then(|i| self.nodes.get(i)) else { return }; 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>)> = 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(); + let le = ListenEvent::from_mouse(event); + let listeners: Vec = self.st.listeners.get(path).map(|l| l.iter().filter(|l| l.event == le).cloned().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); + for l in listeners { + self.call_listener(&l, EventInfo { key: None, target: Some(path.to_vec()), current: Some(path.to_vec()) }); } self.settle(); } @@ -899,6 +1201,193 @@ impl<'a, 'h> Run<'a, 'h> { } } +/// The event a listener is handling: the key code of a keyboard event, and its target and +/// current target (`None`: the stage). +#[derive(Clone, Debug, PartialEq)] +struct EventInfo { + key: Option, + target: Option, + current: Option, +} + +/// A timeline whose scripts share declarations: the main timeline (every scene) or a movie +/// clip symbol's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum TimelineRef { + Root, + Symbol(SymbolId), +} + +/// The compiled frame scripts of a timeline that plays them, in frame order (top layer first +/// within a frame). +pub fn timeline_scripts(tl: &Timeline) -> Vec<(u32, usize, &Compiled)> { + let mut out = Vec::new(); + for (index, layer) in tl.layers.iter().enumerate() { + if !plays(tl, index) { + continue; + } + for k in &layer.keyframes { + if let Some(FrameScript::Source(src)) = &k.script + && let Ok(c) = src.compiled() + { + out.push((k.start, index, c)); + } + } + } + out.sort_by_key(|(f, l, _)| (*f, *l)); + out +} + +/// A timeline's declarations: every function and variable its frame scripts declare (the main +/// timeline's from every scene, in scene order). +pub fn decls(doc: &Document, which: TimelineRef) -> Decls { + match which { + TimelineRef::Root => Decls::build(doc.scenes.iter().flat_map(|s| timeline_scripts(&s.timeline)).map(|(_, _, c)| c)), + TimelineRef::Symbol(id) => match doc.symbol(id) { + Some(s) if s.kind == SymbolKind::MovieClip => Decls::build(timeline_scripts(&s.timeline).into_iter().map(|(_, _, c)| c)), + _ => Decls::default(), + }, + } +} + +/// Why a compiled script on timeline `which` doesn't run there: names it takes from other +/// frames that the timeline doesn't declare, and declarations that clash. +pub fn link_problems(doc: &Document, which: TimelineRef, c: &Compiled) -> Vec { + decls(doc, which).problems(c) +} + +/// The label at or before `frame` (ActionScript's `currentLabel`), or `null`. +fn current_label(tl: &Timeline, frame: u32) -> Value { + let mut firsts: BTreeMap<&str, u32> = BTreeMap::new(); + for k in tl.layers.iter().flat_map(|l| l.keyframes.iter()).filter(|k| !k.label.is_empty()) { + let e = firsts.entry(k.label.as_str()).or_insert(k.start); + *e = (*e).min(k.start); + } + let mut best: Option<(&str, u32)> = None; + for (l, f) in firsts { + if f <= frame && best.is_none_or(|(_, b)| f > b) { + best = Some((l, f)); + } + } + best.map_or(Value::Null, |(l, _)| Value::str(l)) +} + +/// An `f32` as the shortest decimal that reads back as it (what the HTML player sees after +/// the export writes it as JSON): reads give `0.1`, not `0.10000000149011612`. +fn short(v: f32) -> f64 { + if !v.is_finite() { + return f64::from(v); + } + format!("{v}").parse().unwrap_or(f64::from(v)) +} + +/// A computed value at `f32` precision, written shortest. +fn fround_short(v: f64) -> f64 { + short(v as f32) +} + +/// `[tx, ty, sx, sy, rotation]` of a transform in `f64` (the same steps as `Affine::decompose` +/// and the HTML player's `decompose`), from its components written shortest. +fn decompose64(m: &Affine) -> [f64; 5] { + let [a, b, c, d, e, f] = m.m.map(short); + let sx = (a * a + b * b).sqrt(); + let r = b.atan2(a); + let det = a * d - b * c; + let sy = if sx > 1e-12 { det / sx } else { (c * c + d * d).sqrt() }; + [e, f, sx, sy, r] +} + +/// A running script's view of the movie (ADR 0013 tier 2.5). +struct Script<'r, 'a, 'h> { + r: &'r mut Run<'a, 'h>, + /// The timeline the script belongs to. + owner: InstancePath, + decls: Arc, + ev: Option, +} + +impl Script<'_, '_, '_> { + fn from(&mut self) -> Result { + self.r.refresh(); + self.r.index_of(&self.owner).ok_or_else(|| "the script's timeline has left the stage".into()) + } +} + +impl World for Script<'_, '_, '_> { + fn act(&mut self, base: Base, action: &Action) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let path = self.r.base_path(&self.owner, self.ev.as_ref(), base).map_err(Some)?; + self.r.exec(&path, action, true); + if self.r.halted { Err(None) } else { Ok(()) } + } + + fn get(&mut self, at: &Place, p: Prop) -> Result { + let from = self.from()?; + let i = self.r.place(from, self.ev.as_ref(), at)?; + self.r.property(i, p) + } + + fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option> { + if at.base == Base::Stage { + return Err(Some("the stage's properties can't be set here".into())); + } + // In range (as the property keeps it), and never -0, so messages read the same here + // and in the HTML player. + let (lo, hi) = p.range(); + let v = v.clamp(lo, hi) + 0.0; + self.act(at.base, &Action::SetProperty { target: at.path.clone(), property: p, value: v }) + } + + fn trace(&mut self, line: String) { + if self.r.budget() { + self.r.out(line); + } + } + + fn read(&mut self, name: &str) -> Result { + if let Some(v) = self.r.st.vars.get(&self.owner).and_then(|m| m.get(name)) { + return Ok(v.clone()); + } + self.decls.vars.get(name).map(|t| t.default_value()).ok_or_else(|| format!("`{name}` isn't a variable of this timeline")) + } + + fn write(&mut self, name: &str, v: Value) -> Result<(), String> { + let t = *self.decls.vars.get(name).ok_or_else(|| format!("`{name}` isn't a variable of this timeline"))?; + self.r.st.vars.entry(self.owner.clone()).or_default().insert(name.to_string(), t.coerce(v)); + Ok(()) + } + + fn function(&mut self, name: &str) -> Option> { + self.decls.functions.get(name).cloned() + } + + fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc, add: bool) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let owner = self.owner.clone(); + self.r.listen(&owner, self.ev.as_ref(), at, ev, f, add); + Ok(()) + } + + fn random(&mut self) -> f64 { + self.r.st.rng.next_f64() + } + + fn same(&mut self, a: &Place, b: &Place) -> Result { + let from = self.from()?; + let x = self.r.place(from, self.ev.as_ref(), a)?; + let y = self.r.place(from, self.ev.as_ref(), b)?; + Ok(x == y) + } + + fn key_code(&mut self) -> Result { + self.ev.as_ref().and_then(|e| e.key).map(f64::from).ok_or_else(|| "this isn't a keyboard event".into()) + } +} + #[cfg(test)] #[path = "player_tests.rs"] mod tests; diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 6720e447..b110f013 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -353,7 +353,7 @@ fn as3(k: Arc, src: &str) -> Arc { /// The state without the listeners scripts add (hand-made actions use handlers instead). fn lean(st: &PlayerState) -> PlayerState { - PlayerState { listeners: BTreeMap::new(), ..st.clone() } + PlayerState { listeners: BTreeMap::new(), seq: 0, ..st.clone() } } /// Plays both documents through the same pointer events and asserts the same movie: state and @@ -403,7 +403,7 @@ fn actionscript_and_hand_made_actions_play_the_same_movie() { #[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 d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nswitch (1) { }")])], 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); @@ -448,3 +448,169 @@ fn next_scene_in_a_movie_clip_script_stays_in_its_clip() { 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"]); } + +// ----- ActionScript small logic (ADR 0013 tier 2.5) --------------------------------------------- + +/// A one-layer main timeline of `frames` frames with scripts on some of them, and `extra` layers. +fn scripted(frames: u32, scripts: &[(u32, &str)], extra: Vec>, library: Vec>) -> Document { + let mut keys = Vec::new(); + let mut starts: Vec = scripts.iter().map(|(f, _)| *f).collect(); + starts.push(frames); + for (i, (f, src)) in scripts.iter().enumerate() { + let end = starts.get(i + 1).copied().unwrap_or(frames); + keys.push(if src.is_empty() { kf(*f, end - f, vec![], vec![], "") } else { as3(kf(*f, end - f, vec![], vec![], ""), src) }); + } + let mut layers = vec![layer(1, keys)]; + layers.extend(extra); + doc(layers, library) +} + +fn outputs(d: &Document, steps: usize) -> Vec { + let mut s = start(d, &mut NoScripts); + let mut out = s.output.clone(); + for _ in 0..steps { + s = step(d, &s.state, &[], &mut NoScripts); + out.extend(s.output.iter().cloned()); + } + out +} + +#[test] +fn timeline_variables_and_functions_live_across_frames() { + let d = scripted(4, &[(0, "var score:int = 10;\nfunction bump(k:int):int { score += k; return score; }\ntrace(\"start \" + score + \" \" + level);"), (2, "trace(bump(5), bump(1.9), level);\nlevel = \"two\";"), (3, "trace(level);\nvar level:String = \"one\"; trace(level); stop();")], vec![], vec![]); + // `level` is declared on frame 4 but is the timeline's from the start (null until set). + assert_eq!(outputs(&d, 5), ["start 10 null", "15 16 null", "two", "one"]); + let s = run(&d, 5); + assert_eq!(s.state.vars.get(&Vec::new()).and_then(|v| v.get("score")), Some(&Value::Num(16.0))); + // A script that uses a name no frame declares doesn't run at all. + let d = scripted(3, &[(0, "trace(\"one\");"), (1, "trace(\"two\"); trace(nobody);")], vec![], vec![]); + assert_eq!(outputs(&d, 2), ["one"]); + assert_eq!(link_problems(&d, TimelineRef::Root, d.scenes[0].timeline.layers[0].keyframes[1].script.as_ref().and_then(FrameScript::source).unwrap().compiled().as_ref().unwrap())[0].message, "`nobody` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)"); +} + +#[test] +fn each_movie_clip_instance_keeps_its_own_variables() { + // A two-frame clip counts its loops; two instances count apart, and one that leaves the + // stage and comes back starts again. + 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![], ""), "var n:int; n++; trace(name + \" \" + n);")])]); + let a = layer(2, vec![kf(0, 8, vec![inst(3, 100, "a", 0.0, 0.0, vec![])], vec![], "")]); + let b = layer(3, vec![kf(0, 3, vec![inst(4, 100, "b", 50.0, 0.0, vec![])], vec![], ""), kf(3, 2, vec![], vec![], ""), kf(5, 3, vec![inst(5, 100, "b", 50.0, 0.0, vec![])], vec![], "")]); + let d = scripted(8, &[(0, "")], vec![a, b], vec![clip]); + let out = outputs(&d, 6); + assert_eq!(out, ["a 1", "b 1", "a 2", "b 2", "a 3", "b 1", "a 4"], "{out:?}"); +} + +#[test] +fn enter_frame_listeners_run_every_frame_until_removed() { + let src = "var t:int = 0;\nstop();\naddEventListener(Event.ENTER_FRAME, tick);\nfunction tick(e:Event):void {\n t++;\n trace(\"tick \" + t + \" on \" + currentFrame + \" of \" + totalFrames);\n if (t == 3) { removeEventListener(Event.ENTER_FRAME, tick); gotoAndStop(2); }\n}"; + let d = scripted(3, &[(0, src), (1, "trace(\"frame 2 runs after the listener\");")], vec![], vec![]); + assert_eq!(outputs(&d, 5), ["tick 1 on 1 of 3", "tick 2 on 1 of 3", "tick 3 on 1 of 3", "frame 2 runs after the listener"]); + assert!(run(&d, 5).state.listeners.is_empty()); +} + +#[test] +fn keys_reach_the_stage_listeners_with_their_codes() { + let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 1, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "")])]); + let src = "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, down);\nstage.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent):void { trace(\"up \" + e.keyCode); });\nfunction down(e:KeyboardEvent):void {\n if (e.keyCode == Keyboard.RIGHT) hero.x += 10;\n else if (e.keyCode == Keyboard.LEFT) hero.x -= 10;\n trace(e.keyCode, hero.x, e.target == stage);\n}"; + let d = scripted(2, &[(0, src)], vec![layer(2, vec![kf(0, 2, vec![inst(3, 100, "hero", 30.0, 40.0, vec![])], vec![], "")])], vec![clip]); + let s = start(&d, &mut NoScripts); + assert_eq!(s.state.stage.len(), 2); + let s = step(&d, &s.state, &[Event::KeyDown(39), Event::KeyDown(39), Event::KeyUp(39)], &mut NoScripts); + assert_eq!(s.output, ["39 40 true", "39 50 true", "up 39"]); + // Between frames too. + let s = input(&d, &s.state, &[Event::KeyDown(37)], &mut NoScripts); + assert_eq!(s.output, ["37 40 true"]); + assert_eq!(s.state.props.get(&vec![ElementId(3)]).and_then(|o| o.x), Some(40.0)); +} + +#[test] +fn scripts_read_instance_and_timeline_properties() { + let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 3, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "walk")])]); + let mut hero = (*inst(3, 100, "hero", 30.0, 40.0, vec![])).clone(); + hero.transform = Affine::translate(30.25, 40.0).mul(&Affine::scale(2.0, 0.5)); + hero.color.alpha = 0.3; + let src = "stop();\ntrace(hero.x, hero.y, hero.scaleX, hero.scaleY, hero.rotation, hero.alpha, hero.visible, hero.name);\ntrace(hero.currentFrame, hero.totalFrames, hero.currentLabel, currentFrame, totalFrames, currentLabel, this.name);\nhero.x = 0.1; hero.alpha = hero.alpha + 0.2; hero.visible = false;\ntrace(hero.x, hero.alpha, hero.visible);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { trace(mouseX, mouseY, hero.mouseX, stage.mouseY); });"; + let k = as3(kf(0, 2, vec![], vec![], "intro"), src); + let mut hk = Keyframe::new(0, 2); + hk.elements = vec![Arc::new(hero)]; + let d = doc(vec![layer(1, vec![k]), layer(2, vec![Arc::new(hk)])], vec![clip]); + let s = start(&d, &mut NoScripts); + assert_eq!(s.output, ["30.25 40 2 0.5 0 0.3 true hero", "1 3 walk 1 2 intro root1", "0.1 0.5 false"]); + let s = input(&d, &s.state, &[Event::Move(Vec2::new(50.5, 60.0)), Event::Leave, Event::KeyDown(32)], &mut NoScripts); + // The pointer's last place stays after it leaves; a clip sees it in its own space. + assert_eq!(s.output, ["50.5 60 25.2 60"]); +} + +#[test] +fn random_numbers_are_seeded_and_repeat() { + let src = "trace(Math.random(), Math.floor(Math.random() * 6) + 1);"; + let d = scripted(2, &[(0, src)], vec![], vec![]); + let a = start_seeded(&d, 7, &mut NoScripts).output; + let b = start_seeded(&d, 7, &mut NoScripts).output; + let c = start_seeded(&d, 8, &mut NoScripts).output; + assert_eq!(a, b); + assert_ne!(a, c); + // The generator itself: in [0, 1), and spread out. + let mut r = Rng::seeded(DEFAULT_SEED); + let v: Vec = (0..10_000).map(|_| r.next_f64()).collect(); + assert!(v.iter().all(|x| (0.0..1.0).contains(x))); + let mean = v.iter().sum::() / v.len() as f64; + assert!((mean - 0.5).abs() < 0.02, "{mean}"); + assert_eq!(start(&d, &mut NoScripts).output, start_seeded(&d, DEFAULT_SEED, &mut NoScripts).output); +} + +#[test] +fn an_endless_loop_stops_its_script_and_the_movie_plays_on() { + let d = scripted(3, &[(0, "trace(\"a\");\nwhile (true) { }\ntrace(\"never\");"), (1, "trace(\"frame 2\");")], vec![], vec![]); + let s = start(&d, &mut NoScripts); + assert_eq!(s.output, ["a", "Script on frame 1 of the main timeline stopped: it ran more than 100000 steps (an endless loop?)"]); + let s = step(&d, &s.state, &[], &mut NoScripts); + assert_eq!((s.state.root.frame, s.output.as_slice()), (1, ["frame 2".to_string()].as_slice())); + // A runtime error stops only its script. + let d = scripted(2, &[(0, "trace(\"x\");\ntrace(ghost.x);\ntrace(\"y\");")], vec![], vec![]); + assert_eq!(start(&d, &mut NoScripts).output, ["x", "Script on frame 1 of the main timeline stopped: line 2: no instance named “ghost” here"]); + // Many listeners that each loop share one step's fuel; the step ends with one message. + let mut src = String::from("stop();\n"); + for i in 0..15 { + src.push_str(&format!("addEventListener(Event.ENTER_FRAME, function (e:Event):void {{ var n:int = {i}; while (true) n++; }});\n")); + } + let d = scripted(2, &[(0, &src)], vec![], vec![]); + let s = step(&d, &start(&d, &mut NoScripts).state, &[], &mut NoScripts); + assert_eq!(s.output.iter().filter(|l| l.ends_with("(an endless loop?)")).count(), 10, "{:?}", s.output); + assert!(s.output.last().is_some_and(|l| l.starts_with("Stopped running actions this frame: scripts ran more than 1000000 steps")), "{:?}", s.output); +} + +#[test] +fn listeners_know_their_target_and_current_target() { + let mut d = button_doc(); + { + let tl = d.timeline_mut(0); + let l0 = Arc::make_mut(&mut tl.layers[0]); + l0.keyframes[0] = as3(l0.keyframes[0].clone(), "stop();\ngo.addEventListener(MouseEvent.CLICK, clicked);\nfunction clicked(e:MouseEvent):void { trace(e.target.name, e.currentTarget == go, e.target != stage, e.currentTarget.x); report(e); }\nfunction report(ev:MouseEvent):void { trace(\"from \" + ev.currentTarget.name); }"); + let k = Arc::make_mut(&mut Arc::make_mut(&mut tl.layers[1]).keyframes[0]); + if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind { + events.clear(); + } + } + let p = Vec2::new(150.0, 150.0); + let s = step(&d, &start(&d, &mut NoScripts).state, &[Event::Move(p), Event::Down(p), Event::Up(p)], &mut NoScripts); + assert_eq!(s.output, ["go true true 100", "from go"]); +} + +#[test] +fn scripted_play_is_deterministic() { + let src = "var n:Number = 0;\naddEventListener(Event.ENTER_FRAME, function (e:Event):void { n += Math.random(); if (n > 2) { trace(n); n = 0; } });"; + let d = scripted(4, &[(0, src)], vec![], vec![]); + let play = || { + let mut s = start_seeded(&d, 3, &mut NoScripts); + let mut out = Vec::new(); + for _ in 0..40 { + s = step(&d, &s.state, &[Event::KeyDown(65)], &mut NoScripts); + out.extend(s.output.clone()); + } + (s.state, out) + }; + let (a, b) = (play(), play()); + assert!(!a.1.is_empty()); + assert_eq!(a, b); +} diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index f9dc5dff..9a94a454 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -17,7 +17,7 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y}]} plays the movie with its actions and frame scripts from the first frame; returns the output and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn), + c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y} or {tick, type: key_down|key_up|key, key: code|letter|LEFT…}], seed?: Math.random()'s seed (default 0)} plays the movie with its actions and frame scripts from the first frame; returns the output and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn), c("actions.set", "Set Actions", "", None, "{actions: [{op: stop|play|goto_and_play|goto_and_stop|next_frame|prev_frame|next_scene|prev_scene|trace|set_property, target?, frame?, scene?, message?, property?, value?}] | plugin: id, entry?, symbol?: id (a movie clip's timeline), layer?, frame?} sets what the keyframe at the frame runs; or {element, event: click|press|release|over|out, actions} sets an instance's event handler. An empty list clears it", true, set), c("actions.clear", "Clear Actions", "", None, "{symbol?, layer?, frame?} clears the keyframe's actions; {element, event?} clears an instance's handlers (one event, or all)", true, clear), c("actions.list", "List Actions", "", None, "{} every keyframe with actions or a frame script and every instance with event handlers, in every scene and symbol", false, list), @@ -259,8 +259,9 @@ fn test_movie(s: &mut Session, p: &Value) -> Result { } Some(_) => return Err(EngineError::Param("param 'events' must be a list".into())), } + let seed = opt_u64(p, "seed")?.unwrap_or(anicraft_doc::player::DEFAULT_SEED); let mut runner = ScriptRunner::new(&s.plugins); - let mut movie = Movie::start(&s.doc, &mut runner); + let mut movie = Movie::start_seeded(&s.doc, seed, &mut runner); for tick in 1..=u64::from(frames) { let events: Vec<_> = timed.iter().filter(|(t, _)| *t == tick).flat_map(|(_, e)| e.iter().copied()).collect(); movie.step(&s.doc, &events, &mut runner); diff --git a/crates/engine/src/cmds_script.rs b/crates/engine/src/cmds_script.rs index 8ab992b3..95db0928 100644 --- a/crates/engine/src/cmds_script.rs +++ b/crates/engine/src/cmds_script.rs @@ -13,8 +13,10 @@ use crate::cmds_actions::{Scope, keyframe_in}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::actions::as3::Problem; use anicraft_doc::actions::{self, CompileResult, FrameScript, Language, SourceScript}; -use anicraft_doc::{Linkage, SymbolId}; +use anicraft_doc::player::{TimelineRef, link_problems}; +use anicraft_doc::{Document, Linkage, SymbolId, SymbolKind}; use serde_json::{Value, json}; use std::sync::Arc; @@ -24,7 +26,7 @@ pub fn specs() -> 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); 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, 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.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, the names it takes from other frames of its timeline (`uses`), and what it compiles to (`steps`, `program`); 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), ] } @@ -47,14 +49,33 @@ fn what(script: &Option) -> Value { } /// Whether a script runs, its problems and notes (each `{line, column, message}`; line 0 is -/// the whole script). -fn status(c: &CompileResult) -> Value { +/// the whole script). `links`: why it doesn't run on its timeline although it compiles (a +/// name from another frame that isn't there, ADR 0013 tier 2.5). +fn status(c: &CompileResult, links: &[Problem]) -> Value { match c { - Ok(c) => json!({"runs": true, "problems": [], "notes": c.notes}), + Ok(c) if links.is_empty() => json!({"runs": true, "problems": [], "notes": c.notes}), + Ok(c) => json!({"runs": false, "problems": links, "notes": c.notes}), Err(p) => json!({"runs": false, "problems": p, "notes": []}), } } +/// The timeline a keyframe's script belongs to, for linking (graphic and button timelines +/// don't run scripts: `None`). +fn timeline_of(doc: &Document, symbol: Option) -> Option { + match symbol { + None => Some(TimelineRef::Root), + Some(id) => doc.symbol(id).filter(|s| s.kind == SymbolKind::MovieClip).map(|_| TimelineRef::Symbol(id)), + } +} + +/// Why a compiled script doesn't link on its timeline. +fn links(doc: &Document, which: Option, c: &CompileResult) -> Vec { + match (which, c) { + (Some(w), Ok(c)) => link_problems(doc, w, c), + _ => Vec::new(), + } +} + fn check(_: &mut Session, p: &Value) -> Result { let text = str_req(p, "text")?; if text.len() > actions::MAX_SOURCE_BYTES { @@ -62,10 +83,11 @@ fn check(_: &mut Session, p: &Value) -> Result { } let script = SourceScript::new(language(p)?.unwrap_or_default(), text); let c = script.compiled(); - let mut v = status(c); + 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::>()); + v["steps"] = json!(c.steps); + v["uses"] = json!(c.free); + v["program"] = json!(c); } Ok(v) } @@ -103,10 +125,12 @@ fn set(s: &mut Session, p: &Value) -> Result { let script = SourceScript::new(lang.or(old.map(|o| o.language)).unwrap_or_default(), text); script.check().map_err(EngineError::Param)?; 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())) { + let script = Arc::new(script); + k.script = Some(FrameScript::Source(script.clone())); + let which = timeline_of(&s.doc, opt_u64(p, "symbol")?.map(SymbolId)); + if let (Some(o), Value::Object(st)) = (out.as_object_mut(), status(script.compiled(), &links(&s.doc, which, script.compiled()))) { o.extend(st); } - k.script = Some(FrameScript::Source(Arc::new(script))); Ok(out) } @@ -122,13 +146,14 @@ fn clear(s: &mut Session, p: &Value) -> Result { fn list(s: &mut Session, p: &Value) -> Result { let with_text = opt_bool(p, "text")?.unwrap_or(true); let mut frames = Vec::new(); - let timelines = s.doc.scenes.iter().enumerate().map(|(i, sc)| (json!({"scene": i}), sc.name.as_str(), &sc.timeline)).chain(s.doc.library.iter().map(|sym| (json!({"symbol": sym.id.0}), sym.name.as_str(), &sym.timeline))); - for (at, name, tl) in timelines { + let doc = &s.doc; + let timelines = doc.scenes.iter().enumerate().map(|(i, sc)| (json!({"scene": i}), sc.name.as_str(), &sc.timeline, Some(TimelineRef::Root))).chain(doc.library.iter().map(|sym| (json!({"symbol": sym.id.0}), sym.name.as_str(), &sym.timeline, timeline_of(doc, Some(sym.id))))); + for (at, name, tl, which) in timelines { for l in &tl.layers { 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())) { + if let (Some(o), Value::Object(st)) = (v.as_object_mut(), status(src.compiled(), &links(doc, which, src.compiled()))) { o.extend(st); } if with_text { diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index df41bd67..56281b03 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -9,8 +9,9 @@ //! its scripts, so a script that loops forever costs one frame's budget, then stops with a //! message. +use anicraft_doc::actions::as3::Problem; 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::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step, TimelineRef}; use anicraft_doc::{Document, LayerKind, SymbolKind, Timeline, player}; use anicraft_geom::Vec2; use anicraft_plugins::{Host, Kind, Limits, Registry}; @@ -191,9 +192,14 @@ impl Movie { /// 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 { + Movie::start_seeded(doc, player::DEFAULT_SEED, scripts) + } + + /// [`Movie::start`] with `Math.random()` seeded by `seed`. + pub fn start_seeded(doc: &Document, seed: u64, 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); + let s = player::start_seeded(doc, seed, scripts); m.take(s); m } @@ -233,10 +239,37 @@ impl Movie { } } -/// Parses a pointer event `{type: move|down|up|click|leave, x, y}` (a click is a press and -/// a release at one point). +/// The ActionScript key code a key event names: a number (1-255), a `Keyboard` constant +/// (`"LEFT"`, `"SPACE"`) or one letter or digit. +pub fn parse_key(v: &Value) -> Result { + match v { + Value::Number(n) => n.as_u64().filter(|k| (1..=255).contains(k)).map(|k| k as u32).ok_or_else(|| "a key code is 1-255".to_string()), + Value::String(s) => { + let t = s.trim(); + let one = t.chars().count() == 1 && t.chars().all(|c| c.is_ascii_alphanumeric()); + if one { + let c = t.to_ascii_uppercase(); + return anicraft_doc::actions::as3::ir::key_code(&c).or_else(|| anicraft_doc::actions::as3::ir::key_code(&format!("NUMBER_{c}"))).ok_or_else(|| format!("unknown key '{t}'")); + } + anicraft_doc::actions::as3::ir::key_code(&t.to_ascii_uppercase()).ok_or_else(|| format!("unknown key '{t}' (a key code, a letter, or a Keyboard name such as LEFT or SPACE)")) + } + _ => Err("a key event needs a \"key\": a key code, a letter, or a Keyboard name such as LEFT".into()), + } +} + +/// Parses an event: a pointer event `{type: move|down|up|click|leave, x, y}` (a click is a +/// press and a release at one point) or a key event `{type: key_down|key_up|key, key}` (`key` +/// is a press and a release). pub fn parse_events(v: &Value) -> Result, String> { - let kind = v.get("type").and_then(Value::as_str).ok_or("an event needs a \"type\": move, down, up, click or leave")?; + let kind = v.get("type").and_then(Value::as_str).ok_or("an event needs a \"type\": move, down, up, click, leave, key_down, key_up or key")?; + if matches!(kind, "key_down" | "key_up" | "key") { + let k = parse_key(v.get("key").unwrap_or(&Value::Null))?; + return Ok(match kind { + "key_down" => vec![Event::KeyDown(k)], + "key_up" => vec![Event::KeyUp(k)], + _ => vec![Event::KeyDown(k), Event::KeyUp(k)], + }); + } let num = |k: &str| -> Result { v.get(k).and_then(Value::as_f64).filter(|f| f.is_finite() && f.abs() <= 1e7).map(|f| f as f32).ok_or(format!("a {kind} event needs a finite \"{k}\"")) }; Ok(match kind { "leave" => vec![Event::Leave], @@ -247,7 +280,7 @@ pub fn parse_events(v: &Value) -> Result, String> { let p = Vec2::new(num("x")?, num("y")?); vec![Event::Move(p), Event::Down(p), Event::Up(p)] } - other => return Err(format!("unknown event type '{other}' (move, down, up, click or leave)")), + other => return Err(format!("unknown event type '{other}' (move, down, up, click, leave, key_down, key_up or key)")), }) } @@ -258,12 +291,15 @@ pub struct KeptScript<'a> { /// The timeline runs frame scripts there (a scene or a movie clip, on a layer that plays). pub plays: bool, pub compiled: &'a CompileResult, + /// Why it doesn't run on its timeline although it compiles: names from other frames that + /// aren't there (ADR 0013 tier 2.5). + pub links: Vec, } impl KeptScript<'_> { /// It runs when the movie plays. pub fn runs(&self) -> bool { - self.plays && self.compiled.is_ok() + self.plays && self.compiled.is_ok() && self.links.is_empty() } } @@ -276,17 +312,28 @@ fn layer_plays(tl: &Timeline, index: usize) -> bool { /// Every kept script in the document: the scenes' first, then the symbols'. pub fn kept_scripts(doc: &Document) -> Vec> { - 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 scenes = doc.scenes.iter().map(|s| (s.name.as_str(), &s.timeline, Some(TimelineRef::Root))); + let symbols = doc.library.iter().map(|s| (s.name.as_str(), &s.timeline, (s.kind == SymbolKind::MovieClip).then_some(TimelineRef::Symbol(s.id)))); let mut out = Vec::new(); - for (name, tl, runs) in scenes.chain(symbols) { + let mut root = None; + for (name, tl, which) in scenes.chain(symbols) { + let runs = which.is_some(); + let decls = match which { + Some(TimelineRef::Root) => root.get_or_insert_with(|| player::decls(doc, TimelineRef::Root)).clone(), + Some(w) => player::decls(doc, w), + None => Default::default(), + }; 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() }); + let links = match src.compiled() { + Ok(c) if runs => decls.problems(c), + _ => Vec::new(), + }; + out.push(KeptScript { place: format!("{name} › {}, frame {}", layer.name, u64::from(k.start) + 1), plays: runs && layer_plays(tl, index), compiled: src.compiled(), links }); } } } @@ -300,20 +347,24 @@ pub fn script_summary(doc: &Document) -> Vec { 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)) => { + (true, Ok(c)) if k.links.is_empty() => { 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)); - } + (true, Ok(_)) => lines.push(not_run(&k.place, &k.links)), + (true, Err(problems)) => lines.push(not_run(&k.place, problems)), } } lines } + +/// "Frame script not run: …" with the first problem and how many more there are. +fn not_run(place: &str, problems: &[Problem]) -> String { + 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), + }; + format!("Frame script not run: {place}: {first}{more}") +} diff --git a/crates/engine/src/tests_script.rs b/crates/engine/src/tests_script.rs index e8827631..c34ade8f 100644 --- a/crates/engine/src/tests_script.rs +++ b/crates/engine/src/tests_script.rs @@ -145,14 +145,14 @@ fn scripts_in_the_subset_run_and_the_rest_are_kept_and_said_so() { 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); + assert!(out.html.contains("xyzzy-") && !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(); +var n:int = 1; switch (n) { }"})).unwrap(); assert_eq!(v["runs"], false); - assert_eq!(v["problems"][0], json!({"line": 2, "column": 1, "message": "variables (`var`) aren't supported yet"})); + assert_eq!(v["problems"][0], json!({"line": 2, "column": 16, "message": "`switch` statements 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_eq!(v["output"][0]["line"], "Frame script not run: Scene 1 › Actions, frame 2: line 2, column 16: `switch` statements aren't supported yet"); assert!(v["state"]["frame"].as_u64().unwrap() > 10, "it played on: {}", v["state"]); 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); @@ -174,11 +174,44 @@ 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["steps"], 3); + assert_eq!(v["program"]["body"][1]["s"], "listen"); + assert_eq!(v["program"]["body"][1]["at"]["path"], "btn"); + assert_eq!(v["program"]["functions"][0]["name"], "go"); assert_eq!(v["notes"][0]["line"], 4); + // Names from other frames are listed; the text alone can't say whether they are there. + let v = s.execute("script.check", &json!({"text": "score += bonus(2);"})).unwrap(); + assert_eq!((v["runs"].as_bool(), v["uses"].clone()), (Some(true), json!([{"name": "score", "line": 1, "column": 1, "call": false}, {"name": "bonus", "line": 1, "column": 10, "call": true}]))); 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()); } + +#[test] +fn scripts_link_through_their_timeline_and_test_movie_plays_keys() { + let mut s = Session::new(sample::interactive()); + let layer = s.doc.timeline(0).layers[0].id.0; + // Frame 2 uses a variable and a function that no frame declares yet: it doesn't run. + let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\nfunction onKey(e:KeyboardEvent):void { hits++; trace(\"key \" + e.keyCode + \" \" + hits + \" \" + Math.floor(Math.random() * 1000)); }"})).unwrap(); + assert_eq!(v["runs"], false, "{v}"); + assert_eq!(v["problems"][0]["message"], "`hits` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)"); + let out = s.execute("control.test_movie", &json!({"frames": 5})).unwrap(); + assert!(out["output"][0]["line"].as_str().unwrap().starts_with("Frame script not run: Scene 1 › Actions, frame 2: line 3"), "{}", out["output"]); + // Declaring it on frame 1 links frame 2. + s.execute("script.set", &json!({"layer": layer, "frame": 0, "text": "var hits:int = 0;"})).unwrap(); + let list = s.execute("script.list", &json!({"text": false})).unwrap(); + assert!(list["frames"].as_array().unwrap().iter().all(|f| f["runs"] == true), "{list}"); + let play = |s: &mut Session, seed: u64| { + let v = s.execute("control.test_movie", &json!({"frames": 6, "seed": seed, "events": [{"tick": 3, "type": "key_down", "key": "LEFT"}, {"tick": 4, "type": "key", "key": "a"}, {"tick": 5, "type": "key_down", "key": 32}]})).unwrap(); + v["output"].as_array().unwrap().iter().filter_map(|l| l["line"].as_str().map(str::to_string)).filter(|l| l.starts_with("key ")).collect::>() + }; + let a = play(&mut s, 1); + assert_eq!(a.len(), 3, "{a:?}"); + assert!(a[0].starts_with("key 37 1 ") && a[1].starts_with("key 65 2 ") && a[2].starts_with("key 32 3 "), "{a:?}"); + assert_eq!(play(&mut s, 1), a, "the same seed plays the same"); + assert_ne!(play(&mut s, 2), a, "another seed draws other numbers"); + for bad in [json!({"tick": 1, "type": "key_down"}), json!({"tick": 1, "type": "key_down", "key": 0}), json!({"tick": 1, "type": "key_up", "key": "WIGGLE"})] { + assert!(s.execute("control.test_movie", &json!({"events": [bad]})).is_err()); + } +} diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 21cb4b25..5b69d04f 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -15,12 +15,14 @@ //! //! What doesn't carry across is counted in the report: filters, Subtract and Invert blending, //! 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. +//! outside the ActionScript subset. Scripts in the subset (ADR 0013 tiers 2 and 2.5) come +//! across as the same script IR the Rust player runs (as JSON), with each timeline's functions +//! and variable types, and `player.js` evaluates it the same way. use crate::stroke::stroke_outline; -use anicraft_doc::actions::as3::ScriptOp; +use anicraft_doc::actions::as3::Decls; use anicraft_doc::actions::{Action, FrameRef, Seg, Target}; +use anicraft_doc::player::TimelineRef; 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}; @@ -257,27 +259,6 @@ 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. @@ -505,7 +486,9 @@ impl<'a> Bake<'a> { /// `nm`, labels `lb`, and per frame the scripts `a` and sounds `snd` of keyframes starting /// there (top layer first). A scene's frames seen through its camera (ADR 0027) carry the /// camera's tint (`cc`) and each layer its view (`v`: the camera and the layer's depth). - fn timeline(&mut self, tl: &Timeline, scene: bool) -> Value { + /// `decls`: the declarations its frame scripts share (ADR 0013 tier 2.5), for timelines that + /// run scripts; their functions go out as `fn` and their variables' types as `vt`. + fn timeline(&mut self, tl: &Timeline, scene: bool, decls: Option<&Decls>) -> Value { let n = tl.frame_count(); // One clip slot per visible mask layer, top first (as the evaluator numbers them). let slots: HashMap = tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible).enumerate().map(|(i, l)| (l.id.0, i)).collect(); @@ -574,14 +557,19 @@ impl<'a> Bake<'a> { // 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)})); + match (src.compiled(), decls) { + // It runs where its names from other frames are all there. + (Ok(c), Some(d)) if d.problems(c).is_empty() => { + let mut o = json!({"b": c.body}); + if !c.inner.is_empty() { + o["i"] = json!(c.inner); + } + a.push(json!({"as": o})); if !c.notes.is_empty() { self.notes.entry(OUTSIDE_CALLS).or_default().insert(key); } } - Err(_) => { + _ => { self.notes.entry(KEPT_SCRIPTS).or_default().insert(key); } } @@ -643,6 +631,14 @@ impl<'a> Bake<'a> { if !sounds.is_empty() { o["snd"] = Value::Object(sounds); } + if let Some(d) = decls { + if !d.functions.is_empty() { + o["fn"] = json!(d.functions); + } + if !d.vars.is_empty() { + o["vt"] = json!(d.vars); + } + } o } } @@ -692,15 +688,18 @@ pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie { let scenes = doc.scenes.len(); let mut timelines = Vec::with_capacity(scenes + used.len()); let mut frames = 0usize; + // The main timeline's scripts share one set of declarations over every scene. + let root = anicraft_doc::player::decls(doc, TimelineRef::Root); for s in &doc.scenes { frames += s.timeline.frame_count() as usize; - timelines.push(b.timeline(&s.timeline, true)); + timelines.push(b.timeline(&s.timeline, true, Some(&root))); } let mut symbols = Vec::with_capacity(used.len()); for (i, id) in used.iter().enumerate() { let Some(sym) = doc.symbol(*id) else { continue }; frames += sym.timeline.frame_count() as usize; - timelines.push(b.timeline(&sym.timeline, false)); + let decls = (sym.kind == SymbolKind::MovieClip).then(|| anicraft_doc::player::decls(doc, TimelineRef::Symbol(*id))); + timelines.push(b.timeline(&sym.timeline, false, decls.as_ref())); if b.sound && sym.kind == SymbolKind::Button && sym.timeline.layers.iter().any(|l| l.has_sounds()) { b.notes.entry(BUTTON_SOUNDS).or_default().insert(sym.id.0); } diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index 6cda20cf..6e45cfbb 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -40,7 +40,9 @@ return scratch.isPointInStroke(stagePath(path, m), x, y); }, }; - const player = new AniCraft.Player(movie, host); + // Each page load gets its own Math.random() sequence; the player itself is deterministic. + const seed = window.crypto && window.crypto.getRandomValues ? window.crypto.getRandomValues(new Uint32Array(1))[0] : Math.floor(Math.random() * 4294967296); + const player = new AniCraft.Player(movie, host, seed); function stagePath(path, m) { const out = new Path2D(); @@ -327,7 +329,19 @@ report(player.input([{ type: "leave" }])); draw(); }); - window.addEventListener("keydown", audioOn); + // Keys go to the movie's keyboard listeners (ActionScript key codes are the browser's). + function key(type, e) { + if (e.repeat && type === "keyup") return; + report(player.input([{ type: type, code: e.keyCode }])); + // Arrows and space would scroll the page; a movie that listens for keys keeps them. + if (player.st.stage.some((l) => l.ev === "key_down" || l.ev === "key_up") && [32, 37, 38, 39, 40].indexOf(e.keyCode) >= 0) e.preventDefault(); + draw(); + } + window.addEventListener("keydown", (e) => { + audioOn(); + key("keydown", e); + }); + window.addEventListener("keyup", (e) => key("keyup", e)); window.addEventListener("resize", resize); const dt = 1000 / movie.stage.fps; diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index ceb92473..adc59d4d 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -2,7 +2,8 @@ // // Plays a movie exported by File > Export > HTML Canvas: the instance tree, movie clip // 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 +// (compiled by AniCraft to a small script IR: variables, expressions, conditions, loops, +// functions and listeners, ADR 0013). 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. @@ -142,8 +143,19 @@ var AniCraft = (function () { // ----- the player state ------------------------------------------------------------------------ - function newState() { - 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 }; + function newState(seed) { + return { scene: 0, root: { frame: 0, playing: true }, clips: new Dict(), props: new Dict(), listeners: new Dict(), stage: [], vars: new Dict(), rng: seededRng(seed || 0), mouse: { x: 0, y: 0 }, seq: 0, pointer: null, down: false, hover: null, pressed: null, tick: 0 }; + } + // The label at or before `frame` (ActionScript's `currentLabel`), or null. + function currentLabel(tl, frame) { + let best = null, at = -1; + for (const [l, f] of tl.lb || []) { + if (f <= frame && f > at) { + best = l; + at = f; + } + } + return best; } // Each clip entry: { path, frame, playing }; each props entry: { path, ...overrides }; each // listeners entry: [{ ev, owner, k, h, path }] in the order added. @@ -165,7 +177,7 @@ var AniCraft = (function () { if (!r || !Number.isFinite(value)) return; const v = Math.min(Math.max(value, r[0]), r[1]); if (p === "visible") ov.visible = v !== 0; - else ov[p] = v; + else ov[p] = Math.fround(v); } // Overrides::apply: the element's transform and alpha with the set properties in place. function override(ov, m, fx) { @@ -191,7 +203,7 @@ var AniCraft = (function () { function tree(M, st) { const tl = M.scenes[st.scene] ? M.scenes[st.scene].tl : 0; - const out = [{ path: [], key: "", parent: -1, owner: 0, name: "", sym: -1, kind: ROOT, frame: st.root.frame, frames: M.timelines[tl].n, xf: I, hittable: true, events: null, gain: 1 }]; + const out = [{ path: [], key: "", parent: -1, owner: 0, name: "", sym: -1, kind: ROOT, frame: st.root.frame, frames: M.timelines[tl].n, xf: I, local: I, alpha: 1, hittable: true, events: null, gain: 1 }]; walk(M, st, tl, st.root.frame, 0, 0, I, 1, true, out); return out; } @@ -219,7 +231,7 @@ var AniCraft = (function () { const local = kind === GRAPHIC ? e.g || 0 : kind === CLIP ? clipFrame(st, key, len) : buttonFrame(st, path, len); const idx = out.length; const nxf = mul(lxf, m); - out.push({ path: path, key: key, parent: parent, owner: owner, name: e.n || "", sym: e.y, kind: kind, frame: local, frames: len, xf: nxf, hittable: hit && shown, events: e.ev || null, gain: gain }); + out.push({ path: path, key: key, parent: parent, owner: owner, name: e.n || "", sym: e.y, kind: kind, frame: local, frames: len, xf: nxf, local: e.m || I, alpha: e.c ? e.c[0] : 1, hittable: hit && shown, events: e.ev || null, gain: gain }); // A graphic's contents belong to the timeline the graphic is on. walk(M, st, sym.tl, local, idx, kind === GRAPHIC ? owner : idx, nxf, depth + 1, hit && shown, out); } @@ -361,20 +373,628 @@ var AniCraft = (function () { return null; } + // ----- frame scripts in the ActionScript subset (ADR 0013 tiers 2 and 2.5) ----------------------- + // + // A line-by-line port of crates/actions/src/as3/run.rs (the evaluator) and the script side of + // player.rs (`Script`, `run_code`, `listen`, `property`). Values are JavaScript's own + // primitives, whose operators are ECMAScript's, as the Rust evaluator implements them. + + const FUEL_PER_RUN = 100000; + const MAX_CALL_DEPTH = 16; + const MAX_TEXT = 16384; + const MAX_TRACE_CHARS = 1000; + const MAX_FUEL_PER_STEP = 1000000; + const MAX_STAGE_LISTENERS = 64; + const MAX_FRAME = 100000; + const MAX_LABEL_CHARS = 256; + const PROP_NAMES = { x: "x", y: "y", alpha: "alpha", visible: "visible", rotation: "rotation", scale_x: "scaleX", scale_y: "scaleY" }; + const PROP_LABELS = { x: "x", y: "y", alpha: "alpha", visible: "visible", rotation: "rotation", scale_x: "scale x", scale_y: "scale y" }; + const READ_NAMES = { current_frame: "currentFrame", total_frames: "totalFrames", current_label: "currentLabel", mouse_x: "mouseX", mouse_y: "mouseY", name: "name" }; + + // Marsaglia's xorshift128, seeded as player.rs `Rng::seeded`. + function seededRng(seed) { + const lo = seed % 4294967296 >>> 0, hi = Math.floor(seed / 4294967296) >>> 0; + const s = [(lo ^ 0x9e3779b9) >>> 0, (hi ^ 0x243f6a88) >>> 0, 0xb7e15162, 0x3c6ef372]; + if (s[0] === 0 && s[1] === 0 && s[2] === 0 && s[3] === 0) s[0] = 1; + return s; + } + function nextU32(s) { + const x = s[0], w = s[3]; + const t = (x ^ (x << 11)) >>> 0; + const w2 = (w ^ (w >>> 19) ^ (t ^ (t >>> 8))) >>> 0; + s[0] = s[1]; + s[1] = s[2]; + s[2] = w; + s[3] = w2; + return w2; + } + function nextF64(s) { + const a = nextU32(s) >>> 5, b = nextU32(s) >>> 6; + return (a * 67108864 + b) / 9007199254740992; + } + + // A literal of the IR's JSON: "u", "null", "nan", {b}, {n}, {s}, {inf}. + function lit(v) { + if (typeof v === "string") return v === "null" ? null : v === "nan" ? NaN : undefined; + if ("b" in v) return v.b; + if ("n" in v) return v.n; + if ("s" in v) return v.s; + if ("inf" in v) return v.inf ? -Infinity : Infinity; + return undefined; + } + function defaultOf(t) { + switch (t) { + case "number": + return NaN; + case "int": + case "uint": + return 0; + case "boolean": + return false; + case "string": + return null; + default: + return undefined; + } + } + function coerce(t, v) { + switch (t) { + case "number": + return +v; + case "int": + return +v | 0; + case "uint": + return +v >>> 0; + case "boolean": + return !!v; + case "string": + return v === null || v === undefined ? null : String(v); + default: + return v; + } + } + // Math.round as the Rust evaluator computes it. + function round(x) { + if (!Number.isFinite(x)) return x; + const f = Math.floor(x); + return x - f >= 0.5 ? f + 1 : f; + } + function minMax(vals, max) { + let out = max ? -Infinity : Infinity; + for (const v of vals) { + if (Number.isNaN(v)) return NaN; + if ((max && v > out) || (!max && v < out)) out = v; + } + return out; + } + function traceLine(s) { + if (s.length <= MAX_TRACE_CHARS) return s; + let n = MAX_TRACE_CHARS; + const u = s.charCodeAt(n - 1); + if (u >= 0xd800 && u < 0xdc00) n -= 1; + return s.slice(0, n) + "…"; + } + // Rust's `char::is_whitespace` and `is_control`, for labels. + function rustSpace(c) { + const u = c.codePointAt(0); + return (u >= 9 && u <= 13) || u === 32 || u === 0x85 || u === 0xa0 || u === 0x1680 || (u >= 0x2000 && u <= 0x200a) || u === 0x2028 || u === 0x2029 || u === 0x202f || u === 0x205f || u === 0x3000; + } + function rustControl(c) { + const u = c.codePointAt(0); + return u < 0x20 || (u >= 0x7f && u <= 0x9f); + } + function labelOk(s) { + const cs = Array.from(s); + return cs.length >= 1 && cs.length <= MAX_LABEL_CHARS && !cs.some(rustControl) && cs.some((c) => !rustSpace(c)); + } + function shown(v) { + return typeof v === "string" ? '"' + Array.from(v).slice(0, 40).join("") + '"' : String(v); + } + // A number as Rust's `Display` writes it (no exponent), for action descriptions. + function rustNum(v) { + if (v === 0 || !Number.isFinite(v)) return String(v); + const a = Math.abs(v); + if (a >= 1e-6 && a < 1e21) return String(v); + const [m, e] = v.toExponential().split("e"); + const neg = m[0] === "-"; + const digits = m.replace("-", "").replace(".", ""); + const exp = parseInt(e, 10); + let out; + if (exp < 0) out = "0." + "0".repeat(-exp - 1) + digits; + else out = digits + "0".repeat(Math.max(exp - (digits.length - 1), 0)); + return (neg ? "-" : "") + out; + } + // A name path as the exported actions' `t` steps (Target::segments). + function segsOf(path) { + const s = (path || "").trim(); + const out = []; + if (s === "") return out; + s.split(".").forEach((part, i) => { + const p = part.trim(); + if (p === "this" && i === 0) return; + if ((p === "root" || p === "_root") && i === 0) out.push("^"); + else if (p === "parent" || p === "_parent") out.push(".."); + else out.push(p); + }); + return out; + } + function placeText(at) { + const base = { stage: "stage", target: "e.target", current: "e.currentTarget" }[at.base] || ""; + const path = (at.path || "").trim(); + const p = path === "" || path === "this" ? "this" : path; + if (base === "") return p; + return p === "this" ? base : base + "." + path; + } + // An action the evaluator builds, in the exported form, with Action::describe's text. + function makeAction(m, path, frame, scene) { + const ops = { stop: "stop", play: "play", goto_and_play: "goto_and_play", goto_and_stop: "goto_and_stop", next_frame: "next_frame", prev_frame: "prev_frame", next_scene: "next_scene", prev_scene: "prev_scene" }; + const t = (path || "").trim(); + const on = t === "" || t === "this" ? "" : " (" + t + ")"; + const a = { op: ops[m], t: segsOf(path) }; + const fr = typeof frame === "number" ? "frame " + (frame + 1) : "“" + frame + "”"; + const sc = scene === null ? "" : " in “" + scene + "”"; + switch (m) { + case "stop": + a.d = "Stop" + on; + break; + case "play": + a.d = "Play" + on; + break; + case "goto_and_play": + case "goto_and_stop": + a.f = frame; + if (scene !== null) a.s = scene; + a.d = "Go to " + fr + sc + (m === "goto_and_play" ? " and play" : " and stop") + on; + break; + case "next_frame": + a.d = "Next frame" + on; + break; + case "prev_frame": + a.d = "Previous frame" + on; + break; + case "next_scene": + a.d = "Next scene"; + break; + case "prev_scene": + a.d = "Previous scene"; + break; + } + return a; + } + // The shortest decimal that reads back as the same f32 (player.rs `short`). + function short(v) { + const f = Math.fround(v); + if (!Number.isFinite(f) || f === 0) return f; + for (let p = 1; p <= 9; p++) { + const s = Number(f.toPrecision(p)); + if (Math.fround(s) === f) return s; + } + return f; + } + + function Stop(kind, line, message) { + this.kind = kind; + this.line = line; + this.message = message; + } + Stop.prototype.describe = function () { + if (this.kind === "fuel") return "it ran more than " + FUEL_PER_RUN + " steps (an endless loop?)"; + if (this.kind === "halt") return "the frame's budget ran out"; + return this.line > 0 ? "line " + this.line + ": " + this.message : this.message; + }; + + const NORMAL = { k: 0 }, BREAK = { k: 1 }, CONTINUE = { k: 2 }; + + // The evaluator over a world `w` (see Script below). + function Vm(w, fuel) { + this.w = w; + this.fuel = fuel; + this.depth = 0; + this.line = 0; + } + Vm.prototype.tick = function (n) { + if (this.fuel < n) { + this.fuel = 0; + throw new Stop("fuel"); + } + this.fuel -= n; + }; + Vm.prototype.err = function (message) { + throw new Stop("error", this.line, message); + }; + // A world call's failure: a message stops the run there; null means the world halted. + Vm.prototype.lift = function (line, r) { + if (r === undefined) return; + if (r === null) throw new Stop("halt"); + throw new Stop("error", line, r); + }; + Vm.prototype.wrap = function (r) { + if (r.err !== undefined) throw new Stop("error", this.line, r.err); + return r.ok; + }; + Vm.prototype.block = function (list, fr) { + for (const s of list) { + const f = this.stmt(s, fr); + if (f.k !== 0) return f; + } + return NORMAL; + }; + Vm.prototype.stmt = function (st, fr) { + this.tick(1); + this.line = st.l; + switch (st.s) { + case "do": + this.expr(st.x, fr); + return NORMAL; + case "if": + return this.block(this.expr(st.c, fr) ? st.a : st.b, fr); + case "loop": { + let test = st.first; + for (;;) { + if (test && st.c !== undefined && st.c !== null) { + this.line = st.l; + if (!this.expr(st.c, fr)) break; + } + test = true; + this.tick(1); + const f = this.block(st.body, fr); + if (f.k === 1) break; + if (f.k === 3) return f; + if (st.next !== undefined && st.next !== null) { + this.line = st.l; + this.expr(st.next, fr); + } + } + return NORMAL; + } + case "break": + return BREAK; + case "continue": + return CONTINUE; + case "return": + return { k: 3, v: st.v !== undefined && st.v !== null ? this.expr(st.v, fr) : undefined }; + case "act": { + const fv = st.args.length > 0 ? this.expr(st.args[0], fr) : undefined; + const has = st.args.length > 0; + const sv = st.args.length > 1 ? this.expr(st.args[1], fr) : undefined; + const hasScene = st.args.length > 1; + this.line = st.l; + let frame = 0; + if (has) { + if (typeof fv === "string" && labelOk(fv)) frame = fv; + else if (typeof fv === "number" && Number.isInteger(fv) && fv >= 1 && fv <= MAX_FRAME + 1) frame = fv - 1; + else this.err("`" + methodName(st.m) + "` needs a frame number from 1 or a label, not " + shown(fv)); + } + let scene = null; + if (hasScene && sv !== null && sv !== undefined) { + if (typeof sv === "string" && labelOk(sv)) scene = sv; + else this.err("the scene is its name, not " + shown(sv)); + } + this.lift(st.l, this.w.act(st.at.base || "this", makeAction(st.m, st.at.path, frame, scene))); + return NORMAL; + } + case "trace": { + const parts = []; + for (const a of st.args) parts.push(String(this.expr(a, fr))); + this.w.trace(traceLine(parts.join(" "))); + return NORMAL; + } + case "listen": { + let func; + if (st.f.named !== undefined) { + func = this.w.fn(st.f.named); + if (func === undefined) this.err("there's no function `" + st.f.named + "` on this timeline"); + } else { + func = fr.inner[st.f.inline]; + if (func === undefined) this.err("the listener's function is missing"); + } + this.lift(st.l, this.w.listen(st.at, st.ev, func, st.add)); + return NORMAL; + } + } + return NORMAL; + }; + function methodName(m) { + return { stop: "stop", play: "play", goto_and_play: "gotoAndPlay", goto_and_stop: "gotoAndStop", next_frame: "nextFrame", prev_frame: "prevFrame", next_scene: "nextScene", prev_scene: "prevScene" }[m] || m; + } + Vm.prototype.text = function (s) { + const n = s.length; + if (n > MAX_TEXT) this.err("this text would be longer than " + MAX_TEXT + " characters"); + this.tick(Math.floor(n / 64)); + return s; + }; + Vm.prototype.binary = function (op, a, b) { + switch (op) { + case "add": + if (typeof a === "string" || typeof b === "string") return this.text(String(a) + String(b)); + return +a + +b; + case "sub": + return +a - +b; + case "mul": + return +a * +b; + case "div": + return +a / +b; + case "mod": + return +a % +b; + case "lt": + return a < b; + case "gt": + return a > b; + case "le": + return a <= b; + case "ge": + return a >= b; + case "eq": + return a == b; + case "ne": + return a != b; + case "strict_eq": + return a === b; + case "strict_ne": + return a !== b; + } + return undefined; + }; + Vm.prototype.load = function (to, fr) { + if (to.k === "local") return fr.locals[to.i]; + if (to.k === "var") return this.wrap(this.w.read(to.n)); + return this.wrap(this.w.get(to.at, to.p)); + }; + Vm.prototype.store = function (to, v, fr) { + if (to.k === "local") { + const c = coerce(fr.types[to.i] || "any", v); + if (to.i < fr.locals.length) fr.locals[to.i] = c; + return c; + } + if (to.k === "var") { + this.wrap(this.w.write(to.n, v)); + return this.wrap(this.w.read(to.n)); + } + const n = +v; + if (!Number.isFinite(n)) this.err("`" + PROP_NAMES[to.p] + "` is set to a number, not " + shown(v)); + this.lift(this.line, this.w.set(to.at, to.p, n)); + return v; + }; + Vm.prototype.expr = function (e, fr) { + this.tick(1); + switch (e.e) { + case "lit": + return lit(e.v); + case "local": + return fr.locals[e.i]; + case "var": + return this.wrap(this.w.read(e.n)); + case "get": + return this.wrap(this.w.get(e.at, e.p)); + case "key": + return this.wrap(this.w.keyCode()); + case "event": + return this.err("the event can only be passed to a function's event parameter"); + case "un": { + const v = this.expr(e.x, fr); + return e.op === "neg" ? -v : e.op === "plus" ? +v : !v; + } + case "bin": { + const a = this.expr(e.a, fr); + const b = this.expr(e.b, fr); + return this.binary(e.op, a, b); + } + case "and": { + const a = this.expr(e.a, fr); + return a ? this.expr(e.b, fr) : a; + } + case "or": { + const a = this.expr(e.a, fr); + return a ? a : this.expr(e.b, fr); + } + case "cond": + return this.expr(e.c, fr) ? this.expr(e.a, fr) : this.expr(e.b, fr); + case "math": { + const v = []; + for (const a of e.args) v.push(+this.expr(a, fr)); + const x = v.length > 0 ? v[0] : NaN; + switch (e.f) { + case "min": + return minMax(v, false); + case "max": + return minMax(v, true); + case "abs": + return Math.abs(x); + case "floor": + return Math.floor(x); + case "ceil": + return Math.ceil(x); + case "round": + return round(x); + case "random": + return this.w.random(); + } + return NaN; + } + case "call": { + const f = this.w.fn(e.f); + if (f === undefined) this.err("there's no function `" + e.f + "` on this timeline"); + const line = this.line; + const v = this.call(f, e.args, fr); + this.line = line; + return v; + } + case "same": + return this.wrap(this.w.same(e.a, e.b)) !== e.ne; + case "set": { + let nv; + if (e.op === null || e.op === undefined) nv = this.expr(e.v, fr); + else { + const old = this.load(e.to, fr); + const rhs = this.expr(e.v, fr); + nv = this.binary(e.op, old, rhs); + } + return this.store(e.to, nv, fr); + } + case "step": { + const old = +this.load(e.to, fr); + const stored = this.store(e.to, old + e.d, fr); + return e.post ? old : stored; + } + case "cast": + return coerce(e.t, this.expr(e.x, fr)); + } + return undefined; + }; + Vm.prototype.call = function (f, args, caller) { + if (this.depth >= MAX_CALL_DEPTH) this.err("functions call each other more than " + MAX_CALL_DEPTH + " deep"); + const params = f.params; + const required = params.filter((p) => p.d === undefined).length; + if (args.length < required || args.length > params.length) { + const want = required === params.length ? String(required) : required + " to " + params.length; + this.err("`" + f.name + "` takes " + want + " argument" + (params.length === 1 ? "" : "s") + ", not " + args.length); + } + const locals = f.locals.map(defaultOf); + for (let i = 0; i < params.length; i++) { + const p = params[i]; + let v; + if (i < args.length) { + const a = args[i]; + if (a.e === "event") { + if (p.ev || p.t === "any") v = null; + else this.err("the event can only be passed to a function's event parameter"); + } else v = this.expr(a, caller); + } else v = p.d !== undefined ? lit(p.d) : undefined; + if (i < locals.length) locals[i] = coerce(p.t, v); + } + this.depth += 1; + this.line = f.line; + const fr = { locals: locals, types: f.locals, inner: f.inner || [] }; + let flow; + try { + flow = this.block(f.body, fr); + } finally { + this.depth -= 1; + } + const v = flow.k === 3 ? flow.v : undefined; + return f.ret !== undefined && f.ret !== null ? coerce(f.ret, v) : undefined; + }; + // Runs `go(vm)`; [fuel used, null or the Stop]. + function runVm(w, fuel, go) { + const vm = new Vm(w, fuel); + try { + go(vm); + return [fuel - vm.fuel, null]; + } catch (e) { + if (e instanceof Stop) return [fuel - vm.fuel, e]; + throw e; + } + } + function runScriptCode(w, code, fuel) { + return runVm(w, fuel, (vm) => vm.block(code.b, { locals: [], types: [], inner: code.i || [] })); + } + function runListenerCode(w, f, fuel) { + return runVm(w, fuel, (vm) => { + vm.line = f.line; + vm.call(f, [{ e: "event" }], { locals: [], types: [], inner: [] }); + }); + } + + // ----- a running script's view of the movie (player.rs `Script`) --------------------------- + + // A script running on timeline `owner` (an instance path), handling event `ev` (or null). + function Script(run, owner, tl, ev) { + this.r = run; + this.owner = owner; + this.tl = tl; + this.ev = ev; + } + Script.prototype.from = function () { + this.r.refresh(); + const i = this.r.indexOf(this.owner); + return i < 0 ? { err: "the script's timeline has left the stage" } : { ok: i }; + }; + Script.prototype.act = function (base, a) { + if (!this.r.budget()) return null; + const p = this.r.basePath(this.owner, this.ev, base); + if (p.err !== undefined) return p.err; + this.r.exec(p.ok, a, true); + return this.r.halted ? null : undefined; + }; + Script.prototype.get = function (at, p) { + const f = this.from(); + if (f.err !== undefined) return f; + const i = this.r.place(f.ok, this.ev, at); + if (i.err !== undefined) return i; + return this.r.property(i.ok, p); + }; + Script.prototype.set = function (at, p, v) { + if (at.base === "stage") return "the stage's properties can't be set here"; + const r = RANGES[p]; + v = Math.min(Math.max(v, r[0]), r[1]) + 0; + const t = (at.path || "").trim(); + const on = t === "" || t === "this" ? "" : " (" + t + ")"; + const a = { op: "set_property", t: segsOf(at.path), p: p, v: v, pl: PROP_LABELS[p], d: "Set " + PROP_LABELS[p] + " to " + rustNum(v) + on }; + return this.act(at.base || "this", a); + }; + Script.prototype.trace = function (line) { + if (this.r.budget()) this.r.out(line); + }; + Script.prototype.read = function (name) { + const vars = this.r.st.vars.get(keyOf(this.owner)); + if (vars && name in vars.v) return { ok: vars.v[name] }; + const vt = this.tl.vt || {}; + if (Object.prototype.hasOwnProperty.call(vt, name)) return { ok: defaultOf(vt[name]) }; + return { err: "`" + name + "` isn't a variable of this timeline" }; + }; + Script.prototype.write = function (name, v) { + const vt = this.tl.vt || {}; + if (!Object.prototype.hasOwnProperty.call(vt, name)) return { err: "`" + name + "` isn't a variable of this timeline" }; + const k = keyOf(this.owner); + let vars = this.r.st.vars.get(k); + if (!vars) { + vars = { path: this.owner, v: Object.create(null) }; + this.r.st.vars.set(k, vars); + } + vars.v[name] = coerce(vt[name], v); + return { ok: undefined }; + }; + Script.prototype.fn = function (name) { + const fns = this.tl.fn || {}; + return Object.prototype.hasOwnProperty.call(fns, name) ? fns[name] : undefined; + }; + Script.prototype.listen = function (at, ev, f, add) { + if (!this.r.budget()) return null; + this.r.listenTo(this.owner, this.ev, at, ev, f, add); + return undefined; + }; + Script.prototype.random = function () { + return nextF64(this.r.st.rng); + }; + Script.prototype.same = function (a, b) { + const f = this.from(); + if (f.err !== undefined) return f; + const x = this.r.place(f.ok, this.ev, a); + if (x.err !== undefined) return x; + const y = this.r.place(f.ok, this.ev, b); + if (y.err !== undefined) return y; + return { ok: x.ok === y.ok }; + }; + Script.prototype.keyCode = function () { + return this.ev && this.ev.key !== null ? { ok: this.ev.key } : { err: "this isn't a keyboard event" }; + }; + // ----- the player (player.rs `Run`) ------------------------------------------------------------ // A player for `movie` (the exported data, as parsed JSON). `host` answers hit tests (see // hitIn). `start()` shows the first frame, `step(events)` moves one frame on, `input(events)` // routes pointer events between frames; each returns { output, sounds }: the lines the movie // wrote (traces, and why an action could not run) and the sounds of the keyframes entered. - // Events: { type: "move" | "down" | "up", x, y } (stage pixels) or { type: "leave" }. - function Player(movie, host) { + // Events: { type: "move" | "down" | "up", x, y } (stage pixels), { type: "leave" }, or + // { type: "keydown" | "keyup", code } (an ActionScript key code). `seed` seeds Math.random(). + function Player(movie, host, seed) { this.M = load(movie); this.host = host; - this.st = newState(); + this.seed = seed || 0; + this.st = newState(this.seed); } Player.prototype.start = function () { - this.st = newState(); + this.st = newState(this.seed); const r = new Run(this); r.refresh(); r.pending.unshift([]); @@ -387,6 +1007,7 @@ var AniCraft = (function () { r.refresh(); r.rememberGraphics(); r.advance(); + r.enterFrame(); r.settle(); for (const e of (events || []).slice(0, MAX_EVENTS_PER_STEP)) r.event(e); return r.finish(); @@ -412,7 +1033,10 @@ var AniCraft = (function () { return [p.path, o]; }); 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 }; + const kind = (v) => (v === undefined ? "u" : v === null ? "null" : typeof v === "boolean" ? "b" : typeof v === "number" ? "n" : "s"); + const vars = Array.from(st.vars.values()).sort((a, b) => comparePaths(a.path, b.path)).map((x) => [x.path, Object.keys(x.v).sort().map((k) => [k, kind(x.v[k]) + ":" + String(x.v[k])])]); + const stage = st.stage.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, stage: stage, vars: vars, hover: st.hover, pressed: st.pressed, down: st.down }; }; function Run(player) { @@ -428,6 +1052,7 @@ var AniCraft = (function () { this.output = []; this.dropped = 0; this.sounds = []; + this.fuel = MAX_FUEL_PER_STEP; // The frame each graphic showed when the step began: one on another frame at its end has // entered it (and starts its sounds). this.graphics = new Dict(); @@ -487,6 +1112,8 @@ var AniCraft = (function () { if (!all.has(k) || kept.length === 0) st.listeners.delete(k); else st.listeners.set(k, kept); } + st.stage = st.stage.filter((l) => all.has(keyOf(l.owner))); + for (const k of Array.from(st.vars.keys())) if (!all.has(k)) st.vars.delete(k); if (st.hover !== null && !all.has(keyOf(st.hover))) st.hover = null; if (st.pressed !== null && !all.has(keyOf(st.pressed))) st.pressed = null; }; @@ -570,7 +1197,7 @@ var AniCraft = (function () { 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, false); - else if (script.as) this.runOps(path, script.as); + else if (script.as) this.runScript(path, frame, script.as); else this.out("Frame script " + script.plugin + " not run: frame scripts are not exported"); } }; @@ -591,35 +1218,219 @@ var AniCraft = (function () { 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 timeline node `i` is, for its scripts' functions and variable types (the main + // timeline's span every scene, so any scene's carries them). + Run.prototype.declsOf = function (i) { + const n = this.nodes[i]; + if (n && n.kind === CLIP) { + const s = this.M.symbols[n.sym]; + if (s) return this.M.timelines[s.tl]; + } + return this.sceneTimeline(this.st.scene); + }; + // A frame script in the subset, on timeline `owner` (the export keeps only those that link). + Run.prototype.runScript = function (owner, frame, code) { + const i = this.indexOf(owner); + if (i < 0) return; + const where = "Script on frame " + (frame + 1) + " of " + this.timelineName(i); + this.runCode(owner, this.declsOf(i), null, where, (w, fuel) => runScriptCode(w, code, fuel)); + }; + Run.prototype.runCode = function (owner, tl, ev, where, go) { + if (this.halted) return; + if (this.fuel === 0) { + this.halt("scripts ran more than " + MAX_FUEL_PER_STEP + " steps"); + return; + } + const fuel = Math.min(this.fuel, FUEL_PER_RUN); + const [used, stop] = go(new Script(this, owner, tl, ev), fuel); + this.fuel = Math.max(this.fuel - used, 0); + if (stop !== null && stop.kind !== "halt") this.out(where + " stopped: " + stop.describe()); + }; + Run.prototype.timelineName = function (i) { + if (i === 0) return "the main timeline"; + const names = []; + let cur = i; + for (let k = 0; k <= MAX_SYMBOL_DEPTH; k++) { + const n = this.nodes[cur]; + if (!n || n.kind === ROOT) break; + names.push(n.name === "" ? "?" : n.name); + cur = n.owner; + } + return names.reverse().join("."); + }; + Run.prototype.callListener = function (l, ev) { + this.refresh(); + const i = this.indexOf(l.owner); + if (i < 0) return; + this.runCode(l.owner, this.declsOf(i), ev, "Listener " + l.k, (w, fuel) => runListenerCode(w, l.f, fuel)); + }; + // Every enter-frame listener, in the order they were added. + Run.prototype.enterFrame = function () { + this.refresh(); + const all = []; + for (const [, list] of this.st.listeners.entries()) for (const l of list) if (l.ev === "enter_frame") all.push([l.path, l]); + for (const l of this.st.stage) if (l.ev === "enter_frame") all.push([null, l]); + all.sort((a, b) => a[1].seq - b[1].seq); + for (const [at, l] of all) { + if (this.halted) return; + this.callListener(l, { key: null, target: at, current: at }); + this.settle(); } }; - // The instance the listener's target names gets it (once per function and event). - Run.prototype.listen = function (owner, a) { + Run.prototype.key = function (ev, code) { + const list = this.st.stage.filter((l) => l.ev === ev); + for (const l of list) { + if (this.halted) return; + this.callListener(l, { key: code, target: null, current: null }); + this.settle(); + } + }; + // The node a script names from timeline node `from`: {ok: index or null (the stage)} or {err}. + Run.prototype.place = function (from, ev, at) { + let base = from; + const path = at.path || ""; + const empty = path.trim() === "" || path.trim() === "this"; + switch (at.base) { + case "stage": + return empty ? { ok: null } : { err: "instances on the stage are named from the main timeline (root)" }; + case "target": + case "current": { + if (!ev) return { err: "there's no event here" }; + const p = at.base === "target" ? ev.target : ev.current; + if (p === null) return empty ? { ok: null } : { err: "the event's target is the stage" }; + base = this.indexOf(p); + if (base < 0) return { err: "the event's target has left the stage" }; + } + } + const [i, err] = this.resolve(base, { t: segsOf(path) }); + return i < 0 ? { err: err } : { ok: i }; + }; + Run.prototype.basePath = function (owner, ev, base) { + if (base === "this") return { ok: owner }; + if (base === "stage") return { err: "the stage has no playhead" }; + if (!ev) return { err: "there's no event here" }; + const p = base === "target" ? ev.target : ev.current; + return p === null ? { err: "the event's target is the stage" } : { ok: p }; + }; + // A property of node `i` (null: the stage), as player.rs `property` reads it. + Run.prototype.property = function (i, p) { + const st = this.st; + if (i === null) { + if (p === "mouse_x") return { ok: short(st.mouse.x) }; + if (p === "mouse_y") return { ok: short(st.mouse.y) }; + return { err: "the stage's `" + (READ_NAMES[p] || PROP_NAMES[p]) + "` isn't supported here" }; + } + const n = this.nodes[i]; + if (!n) return { err: "the instance is gone" }; + if (n.kind === ROOT) { + switch (p) { + case "x": + case "y": + case "rotation": + return { ok: 0 }; + case "alpha": + case "scale_x": + case "scale_y": + return { ok: 1 }; + case "visible": + return { ok: true }; + case "current_frame": + return { ok: st.root.frame + 1 }; + case "total_frames": + return { ok: this.M.scenes.reduce((s, sc) => s + this.M.timelines[sc.tl].n, 0) }; + case "current_label": + return { ok: currentLabel(this.sceneTimeline(st.scene), st.root.frame) }; + case "mouse_x": + return { ok: short(st.mouse.x) }; + case "mouse_y": + return { ok: short(st.mouse.y) }; + case "name": + return { ok: "root1" }; + } + } + const ov = st.props.get(n.key) || {}; + const m = n.local; + const a = m[0], b = m[1], c = m[2], d = m[3]; + const sx = Math.sqrt(a * a + b * b); + const r = Math.atan2(b, a); + const det = a * d - b * c; + const sy = sx > 1e-12 ? det / sx : Math.sqrt(c * c + d * d); + const pick = (o, v) => ({ ok: short(o !== undefined ? o : v) }); + switch (p) { + case "x": + return pick(ov.x, m[4]); + case "y": + return pick(ov.y, m[5]); + case "scale_x": + return pick(ov.scale_x, sx); + case "scale_y": + return pick(ov.scale_y, sy); + case "rotation": + return pick(ov.rotation, r * (180 / Math.PI)); + case "alpha": + return { ok: short(ov.alpha !== undefined ? ov.alpha : n.alpha) }; + case "visible": + return { ok: ov.visible !== false }; + case "name": + return { ok: n.name }; + case "mouse_x": + case "mouse_y": { + const x = n.xf; + const dt = x[0] * x[3] - x[1] * x[2]; + if (dt === 0 || !Number.isFinite(dt)) return { ok: 0 }; + const px = st.mouse.x - x[4], py = st.mouse.y - x[5]; + return { ok: short(p === "mouse_x" ? (x[3] * px - x[2] * py) / dt : (x[0] * py - x[1] * px) / dt) }; + } + } + if (n.kind !== CLIP) return { err: "“" + n.name + "” is " + (n.kind === BUTTON ? "a button" : "a graphic") + "; only movie clips and the main timeline have frames" }; + if (p === "current_frame") return { ok: n.frame + 1 }; + if (p === "total_frames") return { ok: n.frames }; + const s = this.M.symbols[n.sym]; + return { ok: s ? currentLabel(this.M.timelines[s.tl], n.frame) : null }; + }; + // addEventListener / removeEventListener (player.rs `listen`). + Run.prototype.listenTo = function (owner, ev, at, event, f, add) { 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); + const what = (add ? "Listen" : "Stop listening") + " for " + event + " (" + placeText(at) + ")"; + const pl = this.place(from, ev, at); + if (pl.err !== undefined) return this.out(what + ": " + pl.err); + const st = this.st; + const same = (x) => x.ev === event && samePath(x.owner, owner) && x.k === f.name; + if (pl.ok === null) { + if (add) { + if (st.stage.some(same)) return; + if (st.stage.length >= MAX_STAGE_LISTENERS) return this.out(what + ": the stage already has " + MAX_STAGE_LISTENERS + " listeners"); + st.stage.push({ ev: event, owner: owner, k: f.name, f: f, seq: st.seq, path: null }); + st.seq += 1; + } else st.stage = st.stage.filter((x) => !same(x)); + return; } - 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"); + const node = this.nodes[pl.ok]; + if (!node) return; + const ok = event === "enter_frame" ? node.kind !== GRAPHIC : node.kind === BUTTON || node.kind === CLIP; + if (!ok) { + 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(what + ": " + why); + } + let list = st.listeners.get(node.key); + if (!add) { + if (list) { + list = list.filter((x) => !same(x)); + if (list.length === 0) st.listeners.delete(node.key); + else st.listeners.set(node.key, list); + } + return; + } + if (list && list.some(same)) return; + if (list && list.length >= MAX_LISTENERS_PER_INSTANCE) return this.out(what + ": “" + node.name + "” already has " + MAX_LISTENERS_PER_INSTANCE + " listeners"); if (!list) { list = []; - this.st.listeners.set(node.key, list); + st.listeners.set(node.key, list); } - list.push({ ev: a.ev, owner: owner, k: a.k, h: a.h, path: node.path }); + list.push({ ev: event, owner: owner, k: f.name, f: f, seq: st.seq, path: node.path }); + st.seq += 1; }; // The node `a`'s target names, seen from timeline node `from`: [index] or [-1, why]. Run.prototype.resolve = function (from, a) { @@ -789,6 +1600,12 @@ var AniCraft = (function () { case "leave": this.pointer(null); break; + case "keydown": + this.key("key_down", e.code); + break; + case "keyup": + this.key("key_up", e.code); + break; } }; // Moves the pointer: what it leaves gets Out, what it reaches gets Over. @@ -796,6 +1613,7 @@ var AniCraft = (function () { this.refresh(); const st = this.st; st.pointer = p ? { x: p.x, y: p.y } : null; + if (p) st.mouse = { x: p.x, y: p.y }; const now = p ? hitIn(this.M, st, this.nodes, this.host, p.x, p.y) : null; const same = now === null ? st.hover === null : samePath(now, st.hover); if (!same) { @@ -818,7 +1636,7 @@ var AniCraft = (function () { if (!h && ls.length === 0) return; const owner = this.nodes[n.owner]; if (h && owner) this.runList(owner.path, h[1], false); - for (const l of ls) this.runList(l.owner, l.h, true); + for (const l of ls) this.callListener(l, { key: null, target: path, current: path }); this.settle(); }; Run.prototype.finish = function () { diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 84b22ce7..5d5b2ee8 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -186,6 +186,8 @@ fn js_events(events: &[Event]) -> String { Event::Down(p) => json!({"type": "down", "x": p.x, "y": p.y}), Event::Up(p) => json!({"type": "up", "x": p.x, "y": p.y}), Event::Leave => json!({"type": "leave"}), + Event::KeyDown(k) => json!({"type": "keydown", "code": k}), + Event::KeyUp(k) => json!({"type": "keyup", "code": k}), }) .collect(); Value::Array(list).to_string() @@ -201,10 +203,24 @@ fn snapshot(st: &PlayerState) -> Value { "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::>(), "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::>()])).collect::>(), + "stage": st.stage.iter().map(|x| json!([x.event.key(), ids(&x.owner), x.function])).collect::>(), + "vars": st.vars.iter().map(|(p, v)| json!([ids(p), v.iter().map(|(k, v)| json!([k, format!("{}:{}", kind(v), v.text())])).collect::>()])).collect::>(), "hover": st.hover.as_deref().map(ids), "pressed": st.pressed.as_deref().map(ids), "down": st.down, }) } +/// A script value's kind, as the JS snapshot tags it. +fn kind(v: &anicraft_doc::actions::as3::ir::Value) -> &'static str { + use anicraft_doc::actions::as3::ir::Value as V; + match v { + V::Undefined => "u", + V::Null => "null", + V::Bool(_) => "b", + V::Num(_) => "n", + V::Str(_) => "s", + } +} + fn props_of_rust(st: &PlayerState) -> Vec { let mut out = Vec::new(); for (p, o) in &st.props { @@ -611,9 +627,10 @@ fn hostile_documents_export_without_panicking() { let fine = Element { id: ElementId(6), transform: Affine::IDENTITY, ..bad.clone() }; let missing = inst(7, 12345, "ghost", Affine::IDENTITY, vec![]); Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = vec![Arc::new(bad), Arc::new(fine), missing]; - let e = to_html(&doc, &HtmlOptions::default()).unwrap(); - assert!(!e.html.contains("NaN") && !e.html.contains("inf"), "numbers stay finite"); + to_html(&doc, &HtmlOptions::default()).unwrap(); let m = movie(&doc, &HtmlOptions::default()); + let data = m.json.to_string(); + assert!(!data.contains("NaN") && !data.contains("inf") && !data.contains("null,"), "numbers stay finite: {data}"); assert_eq!(m.json["paths"][0], "", "a path with a NaN point is left empty"); let mut js = Js::new(&m); js.eval("P.start()"); @@ -652,7 +669,7 @@ fn scripted() -> Document { 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();"); + as3(&mut l1.keyframes[2], "var n:int = 3; stop(); switch (n) { }"); 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(); @@ -700,6 +717,91 @@ fn actionscript_plays_the_movie_its_hand_made_actions_play() { assert_eq!(x.output.iter().collect::>(), ys, "step {}: output", i + 1); let mut st = y.state.clone(); st.listeners.clear(); + st.seq = 0; assert_eq!(x.state, st, "step {}: state", i + 1); } } + +/// A movie that uses the small-logic tier (ADR 0013 tier 2.5): typed variables kept per +/// timeline and per clip instance, expressions, `if`, loops, `Math.random()`, functions from +/// another frame, property reads, enter-frame and keyboard listeners that add and remove +/// themselves, `e.target`, a runtime error and a loop that runs out of fuel. +fn logic() -> Document { + let mut d = fixture(); + let main = "import flash.events.*;\n\ + var score:int = 0;\n\ + var label:String = \"go\";\n\ + var ticks:uint;\n\ + var total:Number = 0;\n\ + trace(\"start \" + score + \" \" + label + \" \" + ticks + \" \" + currentFrame + \"/\" + totalFrames + \" \" + currentLabel);\n\ + for (var i:int = 0; i < 5; i++) { if (i % 2 == 0) continue; total += i * 1.5; }\n\ + var k:int = 3; while (k > 0) { k--; } do { k += 2; } while (k < 5);\n\ + trace(total, k, Math.max(1, 7, 3), Math.min(), Math.round(-2.5), Math.abs(-0.25), int(\"42\") + uint(-1), 7 / 2, \"10\" < \"9\", 1 == \"1\", null == undefined);\n\ + trace(Math.floor(Math.random() * 100), Math.random() < 1, knob.x, knob.y, knob.alpha, knob.visible, knob.name, panel.currentFrame, panel.totalFrames);\n\ + addEventListener(Event.ENTER_FRAME, onTick);\n\ + stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\n\ + stage.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent):void { trace(\"up \" + e.keyCode + \" \" + (e.currentTarget == stage)); });\n\ + knob.addEventListener(MouseEvent.CLICK, function (e:MouseEvent):void { score += 10; trace(\"click \" + e.target.name + \" \" + (e.currentTarget == knob) + \" \" + score); door.x = door.x + 0.1; trace(door.x); });\n\ + function onTick(e:Event):void {\n\ + ticks++;\n\ + if (ticks % 4 == 0) trace(\"tick \" + ticks + \" frame \" + currentFrame + \" mouse \" + mouseX + \",\" + mouseY);\n\ + if (ticks >= 12) { removeEventListener(Event.ENTER_FRAME, onTick); trace(\"stopped ticking\"); }\n\ + }\n\ + function onKey(e:KeyboardEvent):void {\n\ + if (e.keyCode == Keyboard.RIGHT) { knob.x += 5; } else if (e.keyCode == Keyboard.SPACE) { trace(\"space \" + bump(2)); } else { trace(\"key \" + e.keyCode); }\n\ + trace(\"knob at \" + knob.x + \" \" + label);\n\ + }"; + 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], "function bump(n:int):int { score += n; return score % 3 + 1; }\nlabel = label + \"!\";\ntrace(\"frame 2: \" + bump(1) + \" \" + label);\ntrace(ghost.x);\ntrace(\"never\");"); + as3(&mut l1.keyframes[2], "var spin:int = 0; while (true) { spin++; }"); + 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(); + } + // The door clip keeps its own count across its loops. + let door = Arc::make_mut(&mut d.library[0]); + let dl = Arc::make_mut(&mut door.timeline.layers[0]); + as3(&mut dl.keyframes[0], "var laps:int; laps++; if (laps > 1) trace(\"door lap \" + laps);"); + d +} + +#[test] +fn the_js_player_runs_small_logic_like_the_rust_player() { + let doc = logic(); + let m = movie(&doc, &HtmlOptions::default()); + assert_eq!(m.report.get(KEPT_SCRIPTS), None, "every script links: {:?}", m.report); + assert!(m.json["timelines"][0]["fn"]["bump"].is_object() && m.json["timelines"][0]["vt"]["score"] == "int", "{}", m.json["timelines"][0]["vt"]); + let none = || (vec![], vec![]); + let mut script: Vec<(Vec, Vec)> = vec![none()]; + script.push((vec![Event::Move(at(100.0, 100.0))], vec![])); + script.push((vec![Event::Down(at(101.0, 99.0))], vec![Event::Up(at(101.0, 99.0))])); + script.push((vec![Event::KeyDown(39), Event::KeyUp(39)], vec![Event::KeyDown(65)])); + script.push((vec![Event::KeyDown(32)], vec![])); + script.extend((0..14).map(|_| none())); + script.push((vec![Event::Move(at(10.0, 10.0)), Event::Leave], vec![Event::KeyDown(39)])); + script.extend((0..20).map(|_| none())); + let lines = compare(&doc, &script); + for want in ["start 0 go 0 1/33 null", "6 6 7 Infinity -2 0.25 4294967337 3.5 true true true", "10 true 100 100 1 true knob 1 4", "frame 2: 2 go!", "Script on frame 4 of the main timeline stopped: line 4: no instance named “ghost” here", "stopped ticking", "up 39 true", "key 65"] { + assert!(lines.iter().any(|l| l == want), "the logic fixture never wrote {want:?}: {lines:?}"); + } + assert!(lines.iter().any(|l| l == "click knob true 11"), "{lines:?}"); + assert!(lines.iter().any(|l| l.ends_with("ran more than 100000 steps (an endless loop?)")), "{lines:?}"); + assert!(!lines.iter().any(|l| l == "never")); +} + +#[test] +fn the_js_player_draws_random_numbers_like_the_rust_player() { + // The seeded generator, number for number, at several seeds. + for seed in [0u64, 1, 7, 0xdead_beef, u64::from(u32::MAX) + 5] { + let mut d = Document::default(); + let k = Arc::make_mut(&mut Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes[0]); + k.script = Some(FrameScript::Source(Arc::new(anicraft_doc::actions::SourceScript::new(anicraft_doc::actions::Language::ActionScript3, "for (var i:int = 0; i < 20; i++) trace(Math.random());")))); + let m = movie(&d, &HtmlOptions::default()); + let rust = anicraft_doc::player::start_seeded(&d, seed, &mut NoScripts).output; + let mut js = Js::new(&m); + js.eval(&format!("(P = new AniCraft.Player({}, host, {seed}), 0)", m.json)); + assert_eq!(js.eval("P.start().output"), json!(rust), "seed {seed}"); + } +} diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 8e0e1fb7..f01b10e6 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -446,7 +446,8 @@ trace(n);]]>"); let (d, report) = import(&files).unwrap(); assert!(d.document_class.is_empty() && !report.kept.contains_key("document class")); - assert!(report.kept.contains_key("frame scripts in ActionScript 3.0")); + // Read as ActionScript 3.0, its variable and `?:` are in the subset now (ADR 0013 tier 2.5). + assert!(report.runs.contains_key("frame scripts in ActionScript 3.0")); } #[test] From fa5144fb7f788474eda0142b1eb83a3f835de282 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:46:08 -0700 Subject: [PATCH 003/192] feat(test-movie): keyboard input to the movie's listeners, seeded runs, small-logic samples (M6) --- src/actions_panel.rs | 48 +++++++----- src/app.rs | 20 +++-- src/test_movie.rs | 174 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 215 insertions(+), 27 deletions(-) diff --git a/src/actions_panel.rs b/src/actions_panel.rs index 28c7a5b7..61d499c9 100644 --- a/src/actions_panel.rs +++ b/src/actions_panel.rs @@ -300,10 +300,10 @@ fn char_index(text: &str, line: u32, column: u32) -> usize { index } -/// Under the editor: whether the script runs (ADR 0013 tier 2), what in it is ignored, and -/// each problem that keeps it from running, where it is. Clicking a problem puts the cursor -/// there. -fn script_status(ui: &mut egui::Ui, src: &SourceScript, text_shown: &str, editor: egui::Id) { +/// Under the editor: whether the script runs (ADR 0013 tiers 2 and 2.5), what in it is +/// ignored, and each problem that keeps it from running, where it is (`links`: names it takes +/// from other frames that its timeline doesn't have). Clicking a problem puts the cursor there. +fn script_status(ui: &mut egui::Ui, src: &SourceScript, links: &[anicraft_engine::doc::actions::as3::Problem], text_shown: &str, editor: egui::Id) { let row = |ui: &mut egui::Ui, p: &anicraft_engine::doc::actions::as3::Problem, color: egui::Color32| { // The engine marks code with backticks (for the CLI and agents); here it reads plainly. let message = p.message.replace('`', ""); @@ -323,26 +323,27 @@ fn script_status(ui: &mut egui::Ui, src: &SourceScript, text_shown: &str, editor ui.ctx().memory_mut(|m| m.request_focus(editor)); } }; - match src.compiled() { - Ok(c) => { + let problems = match src.compiled() { + Ok(c) if links.is_empty() => { ui.horizontal(|ui| { ui.label(text(Type::Body, tr!("Runs in Test Movie and the HTML canvas export")).color(T.ok)); - ui.label(text(Type::Data, trn!("{n} step", "{n} steps", c.ops.len())).color(T.text_dim)); + ui.label(text(Type::Data, trn!("{n} step", "{n} steps", c.steps)).color(T.text_dim)); }); for n in &c.notes { row(ui, n, T.text_dim); } + return; } - Err(problems) => { - ui.label(text(Type::Body, trn!("Doesn't run: {n} problem", "Doesn't run: {n} problems", problems.len())).color(T.error)); - // A few rows tall, so the code stays in view however many there are. - egui::ScrollArea::vertical().id_salt("act_script_problems").max_height(96.0).auto_shrink([false, true]).show(ui, |ui| { - for p in problems { - row(ui, p, T.error); - } - }); + Ok(_) => links, + Err(problems) => problems.as_slice(), + }; + ui.label(text(Type::Body, trn!("Doesn't run: {n} problem", "Doesn't run: {n} problems", problems.len())).color(T.error)); + // A few rows tall, so the code stays in view however many there are. + egui::ScrollArea::vertical().id_salt("act_script_problems").max_height(96.0).auto_shrink([false, true]).show(ui, |ui| { + for p in problems { + row(ui, p, T.error); } - } + }); } /// The Script view: the kept script's language, and its text in a monospace editor with line @@ -378,11 +379,22 @@ fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&S let code = font(Type::Path); let rows = shown.split('\n').count().max(1); let editor_id = ui.make_persistent_id("act_script_editor"); + // Names it takes from other frames of its timeline that aren't there (ADR 0013 tier 2.5). + let links = match src.map(|s| s.compiled()) { + Some(Ok(c)) if t.runs => { + let which = t.base.get("symbol").and_then(Value::as_u64).map_or(anicraft_engine::doc::player::TimelineRef::Root, |id| anicraft_engine::doc::player::TimelineRef::Symbol(SymbolId(id))); + anicraft_engine::doc::player::link_problems(&app.s.doc, which, c) + } + _ => Vec::new(), + }; // The lines that hold a problem, marked in the gutter. - let bad: std::collections::BTreeSet = src.and_then(|s| s.compiled().as_ref().err()).map(|p| p.iter().map(|p| p.line).collect()).unwrap_or_default(); + let bad: std::collections::BTreeSet = match src.map(|s| s.compiled()) { + Some(Err(p)) => p.iter().map(|p| p.line).collect(), + _ => links.iter().map(|p| p.line).collect(), + }; // Whether it runs, and what keeps it from running, above the code. if let Some(s) = src { - script_status(ui, s, &shown, editor_id); + script_status(ui, s, &links, &shown, editor_id); } let changed = egui::ScrollArea::both() .id_salt("act_script") diff --git a/src/app.rs b/src/app.rs index 37151273..bc625165 100644 --- a/src/app.rs +++ b/src/app.rs @@ -943,15 +943,16 @@ impl App { // The interactive sample as an imported Animate document might bring it: a // frame script kept on the Actions layer's first keyframe (in place of its // Stop action), a linkage class and a document class; the Actions panel shows - // the Script view (ADR 0013). `script` runs (tier 2); `scriptproblems` uses - // what the subset doesn't, and shows where; `testscript` plays the one that - // runs in Test Movie, its Play button clicked. + // the Script view (ADR 0013). `script` runs (tiers 2 and 2.5: a typed variable, + // `if`, a keyboard listener); `scriptproblems` uses what the subset doesn't, and + // shows where; `testscript` plays the one that runs in Test Movie, its Play + // button clicked. self.perform("file.new_sample", json!({"which": "interactive"})); self.run("layer.select", json!({"index": 0})); // i18n-exempt: script source, document content - let runs = "import flash.events.MouseEvent;\n\nstop();\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(event:MouseEvent):void {\n\ttrace(\"Play clicked\");\n\tgotoAndPlay(\"show\");\n}\n"; + let runs = "import flash.events.*;\n\nstop();\nvar clicks:int = 0;\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\n\nfunction onPlay(event:MouseEvent):void {\n\tclicks++;\n\ttrace(\"Play clicked \" + clicks + (clicks == 1 ? \" time\" : \" times\"));\n\tgotoAndPlay(\"show\");\n}\n\nfunction onKey(event:KeyboardEvent):void {\n\tif (event.keyCode == Keyboard.SPACE) {\n\t\tgotoAndPlay(\"show\");\n\t}\n}\n"; // i18n-exempt: script source, document content - let problems = "import flash.events.MouseEvent;\n\nstop();\nvar clicks:int = 0;\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(event:MouseEvent):void {\n\tclicks++;\n\tif (clicks > 1) {\n\t\tgotoAndPlay(\"show\");\n\t}\n}\n"; + let problems = "import flash.events.MouseEvent;\n\nstop();\nvar labels:Array = [\"show\", \"menu\"];\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(event:MouseEvent):void {\n\tswitch (labels.length) {\n\t\tcase 2: gotoAndPlay(labels[0]);\n\t}\n}\n"; let code = if which == "scriptproblems" { problems } else { runs }; self.run("script.set", json!({"frame": 0, "text": code, "language": "actionscript3"})); self.run("script.set_class", json!({"class": "com.example.Menu"})); @@ -1873,6 +1874,15 @@ impl App { if keys == crate::a11y::Keyboard::Text || self.palette.is_some() { return; } + // The Test Movie window's movie has the keyboard (ADR 0013 tier 2.5): its keys are the + // movie's; only shortcuts with Ctrl (⌘) or Alt reach the app (Restart is Ctrl+Enter). + if self.test_movie.is_some() && crate::test_movie::has_keys(ctx) { + let fire: Vec<&'static str> = ctx.input_mut(|i| self.shortcuts.iter().filter(|(m, _, _)| m.command || m.ctrl || m.alt).filter_map(|(m, k, id)| i.consume_key(*m, *k).then_some(*id)).collect()); + for id in fire.into_iter().filter(|id| !id.starts_with("view.") && !id.starts_with("tool.")) { + self.invoke(id); + } + return; + } let control = keys == crate::a11y::Keyboard::Control; if !control { crate::motion_path::consume_keys(self, ctx); diff --git a/src/test_movie.rs b/src/test_movie.rs index d9bb45ea..d7121a03 100644 --- a/src/test_movie.rs +++ b/src/test_movie.rs @@ -9,6 +9,11 @@ //! Its sound (ADR 0039): each step's entered keyframes start their sounds //! (`doc::sound::trigger`), movie clips' and graphics' included, and while sound plays the //! movie keeps time with it, as the stage does. +//! +//! Its keyboard (ADR 0013 tier 2.5): while the movie has the focus (it takes it when the window +//! opens and when clicked), keys go to the movie's keyboard listeners as ActionScript key +//! codes, Tab and the arrows included; shortcuts with Ctrl (⌘ on macOS) still reach the app, +//! and Esc closes the window. use crate::app::App; use crate::icons::Icon; @@ -29,6 +34,68 @@ const MAX_CATCH_UP: u32 = 4; /// Largest picture edge rendered, in pixels. const MAX_EDGE: f32 = 2048.0; +/// The movie surface's id: while it has the focus, keys go to the movie. +pub fn surface_id() -> egui::Id { + egui::Id::new("test_movie_surface") +} + +/// Whether the movie has the keyboard. +pub fn has_keys(ctx: &egui::Context) -> bool { + ctx.memory(|m| m.focused()) == Some(surface_id()) +} + +/// The ActionScript key code (`flash.ui.Keyboard`) of a key, for the movie's listeners. +pub fn key_code(k: egui::Key) -> Option { + use egui::Key as K; + let name = k.name(); + let mut chars = name.chars(); + if let (Some(c), None) = (chars.next(), chars.next()) + && (c.is_ascii_uppercase() || c.is_ascii_digit()) + { + return Some(u32::from(c)); + } + Some(match k { + K::ArrowLeft => 37, + K::ArrowUp => 38, + K::ArrowRight => 39, + K::ArrowDown => 40, + K::Space => 32, + K::Enter => 13, + K::Tab => 9, + K::Backspace => 8, + K::Delete => 46, + K::Insert => 45, + K::Home => 36, + K::End => 35, + K::PageUp => 33, + K::PageDown => 34, + K::Minus => 189, + K::Equals | K::Plus => 187, + K::Comma => 188, + K::Period => 190, + K::Slash => 191, + K::Semicolon => 186, + K::Quote => 222, + K::OpenBracket => 219, + K::CloseBracket => 221, + K::Backslash => 220, + K::Backtick => 192, + K::F1 => 112, + K::F2 => 113, + K::F3 => 114, + K::F4 => 115, + K::F5 => 116, + K::F6 => 117, + K::F7 => 118, + K::F8 => 119, + K::F9 => 120, + K::F10 => 121, + K::F11 => 122, + K::F12 => 123, + _ => return None, + }) +} + pub struct TestMovie { doc: Document, movie: Movie, @@ -49,6 +116,8 @@ pub struct TestMovie { audio: bool, /// Kept scripts that don't run (ADR 0013), counted when it opened. skipped: usize, + /// The movie takes the keyboard the next time it is drawn. + focus: bool, } impl TestMovie { @@ -84,10 +153,12 @@ pub fn open(app: &mut App) { app.sound.stop(); let doc = app.s.doc.clone(); let mut runner = ScriptRunner::new(&app.s.plugins); - let movie = Movie::start(&doc, &mut runner); + // Each run draws its own Math.random() numbers; the player itself stays deterministic. + let seed = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as u64); + let movie = Movie::start_seeded(&doc, if app.shot.is_some() { 0 } else { seed }, &mut runner); let name = app.s.path.as_ref().and_then(|p| p.file_stem()).map(|n| n.to_string_lossy().into_owned()); let skipped = anicraft_engine::player::kept_scripts(&doc).iter().filter(|k| !k.runs()).count(); - let mut tm = TestMovie { doc, movie, paused: false, acc: 0.0, texture: None, shown: None, pointer: None, down: false, name, ms: 0.0, voices: Vec::new(), audio: false, skipped }; + let mut tm = TestMovie { doc, movie, paused: false, acc: 0.0, texture: None, shown: None, pointer: None, down: false, name, ms: 0.0, voices: Vec::new(), audio: false, skipped, focus: true }; // Sound only when there is some, and never in screenshot runs or tests. if sound::has_sounds(&tm.doc) && app.shot.is_none() { tm.resume(&mut app.sound); @@ -144,6 +215,11 @@ pub fn show(app: &mut App, ctx: &egui::Context) { ui.label(text(Type::Data, format!("{:>4} / {frames}", st.root.frame + 1))).on_hover_text(tr!("Main timeline frame")); let what = if tm.paused { tr!("paused") } else if st.root.playing { tr!("playing") } else { tr!("stopped") }; ui.label(text(Type::Caption, what)); + // A movie that listens for keys says where they go. + if tm.movie.state.stage.iter().any(|l| l.event.is_key()) { + let keys = if has_keys(ctx) { tr!("Keys go to the movie") } else { tr!("Click the movie to give it the keyboard") }; + ui.label(text(Type::Caption, keys).color(T.text_dim)); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // i18n-exempt: numbers and units (data) ui.label(text(Type::Data, format!("{:.0} fps · {:.1} ms", tm.doc.stage.fps, tm.ms)).color(T.text_faint)).on_hover_text(tr!("Frame rate, and the time the last picture took to draw")); @@ -155,8 +231,17 @@ pub fn show(app: &mut App, ctx: &egui::Context) { let avail = egui::vec2(ui.available_width(), (ui.available_height() - output_h - 40.0).max(60.0)); let k = (avail.x / sw.max(1.0)).min(avail.y / sh.max(1.0)).max(0.01); let size = egui::vec2(sw * k, sh * k); - let (outer, resp) = ui.allocate_exact_size(egui::vec2(avail.x, size.y), egui::Sense::click_and_drag()); - crate::a11y::surface(ui, &resp, tr!("The movie: point and click its buttons")); + let (outer, _) = ui.allocate_exact_size(egui::vec2(avail.x, size.y), egui::Sense::hover()); + let resp = ui.interact(outer, surface_id(), egui::Sense::click_and_drag()); + crate::a11y::surface(ui, &resp, tr!("The movie: point, click and type to play it")); + if tm.focus || resp.is_pointer_button_down_on() { + resp.request_focus(); + tm.focus = false; + } + // Tab and the arrows are the movie's keys while it has them, not focus moves. + if resp.has_focus() { + ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false })); + } let rect = egui::Rect::from_center_size(outer.center(), size); // The pointer, in stage coordinates, to the player. let mut events = Vec::new(); @@ -181,6 +266,20 @@ pub fn show(app: &mut App, ctx: &egui::Context) { tm.pointer = inside.then_some(p); } tm.down = down && (tm.down || inside); + // The keyboard, while the movie has it (Ctrl/⌘ shortcuts stay the app's). + if resp.has_focus() { + ui.input(|i| { + for e in &i.events { + if let egui::Event::Key { key, pressed, modifiers, .. } = e + && !modifiers.command + && *key != egui::Key::Escape + && let Some(code) = key_code(*key) + { + events.push(if *pressed { Event::KeyDown(code) } else { Event::KeyUp(code) }); + } + } + }); + } let mut runner = ScriptRunner::new(plugins); tm.movie.input(&tm.doc, &events, &mut runner); tm.feed(out); @@ -294,3 +393,70 @@ pub fn demo_pointer(app: &mut App) { tm.movie.input(&tm.doc, &[Event::Move(Vec2::new(700.0, 410.0))], &mut r); tm.paused = true; } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn frame(ctx: &egui::Context, app: &mut App, events: Vec) { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + } + + fn key(key: egui::Key, pressed: bool) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE } + } + + fn lines(app: &App) -> Vec { + app.test_movie.as_ref().map(|t| t.movie.output.iter().map(|(_, l)| l.clone()).collect()).unwrap_or_default() + } + + #[test] + fn keys_go_to_the_movie_while_it_has_them() { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::interactive()); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + app.run("layer.select", json!({"index": 0})); + // i18n-exempt: script source, document content + let script = "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { trace(\"down \" + e.keyCode); });\nstage.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent):void { trace(\"up \" + e.keyCode); });"; + assert!(app.run("script.set", json!({"frame": 0, "text": script})).is_some_and(|v| v["runs"] == true)); + open(&mut app); + for _ in 0..3 { + frame(&ctx, &mut app, vec![]); + } + assert!(has_keys(&ctx), "the movie takes the keyboard when Test Movie opens"); + let tool = app.tool; + // A letter that is a tool shortcut on the stage goes to the movie instead. + frame(&ctx, &mut app, vec![key(egui::Key::R, true)]); + frame(&ctx, &mut app, vec![key(egui::Key::R, false), key(egui::Key::ArrowLeft, true), key(egui::Key::Space, true)]); + assert_eq!(app.tool, tool, "R didn't change the tool"); + let out = lines(&app); + for want in ["down 82", "up 82", "down 37", "down 32"] { + assert!(out.iter().any(|l| l == want), "{want} not in {out:?}"); + } + assert!(has_keys(&ctx), "the arrows didn't move the focus away"); + // Esc still closes the window. + frame(&ctx, &mut app, vec![key(egui::Key::Escape, true)]); + assert!(app.test_movie.is_none()); + } + + #[test] + fn key_codes_are_actionscript_s() { + use egui::Key as K; + for (k, code) in [(K::A, 65), (K::Z, 90), (K::Num0, 48), (K::Num9, 57), (K::ArrowLeft, 37), (K::ArrowUp, 38), (K::ArrowRight, 39), (K::ArrowDown, 40), (K::Space, 32), (K::Enter, 13), (K::Tab, 9), (K::Backspace, 8), (K::F1, 112), (K::F12, 123), (K::Comma, 188)] { + assert_eq!(key_code(k), Some(code), "{k:?}"); + assert!(anicraft_engine::doc::actions::as3::ir::key_code(match k { + K::ArrowLeft => "LEFT", + K::Space => "SPACE", + K::A => "A", + K::Num0 => "NUMBER_0", + _ => "F1", + }) + .is_some()); + } + assert_eq!(anicraft_engine::doc::actions::as3::ir::key_code("LEFT"), key_code(K::ArrowLeft)); + assert_eq!(anicraft_engine::doc::actions::as3::ir::key_code("NUMBER_7"), key_code(K::Num7)); + } +} From cdc3d77da1c09d93312b3895c40b13ed6cec4688 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:47:30 -0700 Subject: [PATCH 004/192] docs: ActionScript tier 2.5 as built in ADR 0013, roadmap, changelog, attribution (M6) --- ATTRIBUTION.md | 3 +- CHANGELOG.md | 19 ++++++ crates/actions/src/as3/tests.rs | 12 ++++ docs/adr/0013-actionscript.md | 111 +++++++++++++++++++++++++++++++- docs/roadmap.md | 6 +- 5 files changed, 146 insertions(+), 5 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7cc10202..8b6fbe8b 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -91,7 +91,8 @@ OR Apache-2.0) is noted in the table. | Bevel and Gradient Bevel by offset differences of the blurred opacity; Gradient Glow and Gradient Bevel through a colour ramp | `crates/render/src/filters.rs` | Standard image processing: embossing as the difference of an image offset along the light direction (a directional derivative; e.g. R. C. Gonzalez & R. E. Woods, *Digital Image Processing*); parameters and behaviour from Adobe's public Animate user guide and ActionScript 3.0 reference (`BevelFilter`, `GradientGlowFilter`, `GradientBevelFilter`) | Public descriptions only; no Adobe code or assets (ADR 0025). | | Bevel and gradient filters in SVG export (`feComposite` arithmetic, `feComponentTransfer` tables) | `crates/render/src/svg.rs` | W3C Filter Effects Module Level 1 / SVG 1.1 filters | W3C Royalty-Free Patent Policy. | | Timeline playback semantics for actions (stop, play, go to frame or label, next/previous frame and scene; button Up/Over/Down/Hit states; mouse events) | `crates/actions`, `crates/doc/src/player.rs` | Behaviour learned from Adobe's public *ActionScript 3.0 Reference* (`MovieClip`, `SimpleButton`, `MouseEvent`) and the public Animate user guide on buttons, plus observation (ADR 0013, ADR 0024) | Clean room: no Adobe code, SDKs or players; names used nominatively. | -| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the action IR | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `EventDispatcher.addEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. | +| Seeded `Math.random()` for the player (xorshift128) | `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | G. Marsaglia, "Xorshift RNGs", *Journal of Statistical Software* 8(14), 2003 (public paper); 53-bit doubles from two 32-bit outputs as the common construction | Our own implementation of a published algorithm. | +| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the script IR, the evaluator (types, coercions, operators, `Math`, listeners for enter-frame and keys) | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `Event`, `KeyboardEvent`, `flash.ui.Keyboard`, `Math`, `EventDispatcher.addEventListener` and `removeEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. | | Cubic-Bézier easing (CSS model) | `crates/doc/src/easing.rs` | W3C CSS Easing Functions Level 1 | W3C Royalty-Free Patent Policy. | | SVG path data syntax (file format v2) | `crates/geom/src/path.rs` | W3C SVG 1.1 / 2 | W3C Royalty-Free Patent Policy. | | Marching-squares contour tracing (Paint Bucket regions, Brush outlines) | `crates/geom/src/trace.rs` | Lorensen & Cline (1987); public algorithm | Ported from PhotoCraft's mask tracer (same project family and licence) and reviewed. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f4393c8..997e8b3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ ## Unreleased +* **Frame scripts in ActionScript 3.0 run small logic** (ADR 0013 tier 2.5, M6). + * Typed variables (`var score:int = 0;` as Number, int, uint, Boolean, String or untyped), + kept per timeline instance across its frame scripts as Animate timelines keep them; + expressions (arithmetic, comparison, logic, joining text, `Math.min/max/abs/floor/ceil/ + round/random`, casts); `if`/`else`, `for`, `while` and `do` loops; functions with + parameters and results, callable from any frame of the same timeline. + * Scripts read properties of instances and timelines (`x`, `y`, `alpha`, `visible`, + `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), + remove listeners, and listen for `Event.ENTER_FRAME` and for keys on the stage + (`KeyboardEvent.KEY_DOWN`/`KEY_UP`, `e.keyCode`); `e.target` and `e.currentTarget` work. + * Test Movie sends your keys to the movie (it says so in its bar); `Math.random()` is + seeded, so a headless `control.test_movie` with the same `seed` and events always plays the + same; key events and `seed` there too. + * An endless loop or an error stops only its script, with a line in Output, and the movie + plays on. A script that uses a name no frame of its timeline declares doesn't run, and the + Actions panel shows the name in place. + * The HTML canvas export runs the same scripts, keys included, checked against Test Movie + step by step. + * **Library and Properties polish** (ADR 0053, M2). * **Drag Library items onto the stage**: symbols and bitmaps land at the pointer on the active layer at the playhead, a sound goes onto that layer's keyframe; drag several at once. diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs index dd2254d7..08accc66 100644 --- a/crates/actions/src/as3/tests.rs +++ b/crates/actions/src/as3/tests.rs @@ -488,3 +488,15 @@ fn trace_lines_are_cut_at_whole_characters() { let emoji = format!("{}{}", "a".repeat(crate::MAX_TRACE_CHARS - 1), "😀".repeat(5)); assert_eq!(run::trace_line(emoji).encode_utf16().count(), crate::MAX_TRACE_CHARS); } + +#[test] +fn a_full_budget_runs_quickly() { + let c = ok("var n:int = 0; var s:Number = 0; while (true) { n++; s += Math.abs(n % 7 - 3) * 0.5; }"); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + let t0 = std::time::Instant::now(); + let (used, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + eprintln!("{used} fuel in {ms:.2} ms"); + assert_eq!(r, Err(Stop::Fuel)); + assert!(ms < 500.0, "{ms} ms"); +} diff --git a/docs/adr/0013-actionscript.md b/docs/adr/0013-actionscript.md index b200b416..eb4c2438 100644 --- a/docs/adr/0013-actionscript.md +++ b/docs/adr/0013-actionscript.md @@ -1,7 +1,8 @@ # ADR 0013: ActionScript compatibility * Status: accepted (2026-11-08) as scope and placement. **Tier 1 built** (2026-11-09, see - "Tier 1 as built" below). **Tier 2 built** (2026-11-10, see "Tier 2 as built") + "Tier 1 as built" below). **Tier 2 built** (2026-11-10, see "Tier 2 as built"). **Tier 2.5, + small logic, built** (2026-11-11, see "Tier 2.5 as built") * Relates to: requirements U2 (scripting surface), roadmap M6, ADR 0009 (XFL import), `docs/legal/compliance.md` @@ -240,3 +241,111 @@ Tier 2 follows the decision above. Where the build refines it: event bubbling from a clip's children to its listeners, `e.target`, `getChildByName`, sound and `stage`, and ActionScript 1.0 and 2.0. Each is reported where it is, so the subset can grow from what users' files actually use. + +## Tier 2.5 as built (2026-11-11): small logic + +Item 2 of the context ("variables, `if`, loops, `trace`, setting instance properties, simple +functions"), which tier 2 left out. Where the build refines the decision: + +* **A script IR, run by an evaluator, instead of a flat action list.** Small logic can't be + lowered to actions ahead of time (a loop's count, a condition, a computed frame depend on + the movie), so a compiled script is now a small typed tree of statements and expressions + (`anicraft_actions::as3::ir`: `Stmt`, `Expr`, `LValue`, `Place`, `Function`) and + `as3::run` evaluates it against a `World` trait that the player implements. It is data, not + code: no dynamic evaluation, no `eval`, no reflection. Timeline control still ends in the + same `Action`s (an `Act` statement builds one with the frame and scene computed), so hand-made + actions, plug-in frame scripts and ActionScript keep one runtime. The tier-2 `ScriptOp` + list is gone; `script.check` returns `steps` (a count), `program` (the IR as JSON) and + `uses`. Both the evaluator and its interface stay in the L0 crate: it knows values and + names, not documents. +* **Values and types.** ActionScript's primitives (`undefined`, `null`, Boolean, Number, + String), with ECMA-262's operators exactly: `+` joins when either side is text, `==` and + `<` as §11.8–11.9 (text compares by UTF-16 units), ToNumber as browsers read text (decimal, + `Infinity`, `0x`/`0o`/`0b`), ToString as `Number.toString`. Typed variables coerce on every + write: `int` and `uint` as ToInt32/ToUint32 (so `2147483647 + 1` wraps), Number, Boolean, + String (`null` stays `null`), untyped keeps anything; each starts at its type's default (0, + NaN, false, null, undefined). `int(…)`, `uint(…)`, `Number(…)`, `String(…)`, `Boolean(…)` + cast. Other types (`Array`, `MovieClip`, objects) are problems. +* **Where variables live, as ActionScript 3.0 timelines keep them.** A `var` at a frame + script's top level is a member of the timeline: one table per timeline *instance* + (`PlayerState.vars`, by instance path), shared by every frame script of that timeline, kept + while the instance stays on the stage and gone when it leaves (a clip that comes back starts + afresh), as an instance is constructed again. Every variable any frame of the timeline + declares exists from the start with its default, so frame 1 can read what frame 5 declares + (`null` until it runs). `var` inside a function is that call's (hoisted, numbered slots). + The main timeline's scenes share one table, as they are one timeline. +* **Linking across frames.** A script compiles on its own (the cached compile stays a pure + function of its text) and lists the names it takes from elsewhere (`Compiled::free`). A + timeline's **declarations** (`Decls`: its scripts' functions and variable types, the first + of each name in frame order, top layer first) are built from its compiled scripts; a script + whose free names the timeline doesn't declare, or that declares a function or a variable + type another frame already declares differently, doesn't run (whole, as before), and Test + Movie's first lines, the Script view, `script.set` and `script.list` say which name and + where. So functions on **any** frame of the same timeline can be called (ActionScript makes + them methods of the timeline), not only earlier ones. Calls go by name through the + declarations at run time. +* **Statements.** `if`/`else`, `for (init; cond; next)`, `while`, `do … while`, `break` and + `continue` (no labels), `return` with a value (coerced to the declared result type), calls + with parameters (typed, defaults written out) and recursion, `++`/`--` and `+= -= *= /= %=` + on variables and instance properties, `&&`/`||`/`?:`, `Math.min/max/abs/floor/ceil/round/ + random`, `Math.PI` and `Math.E`, the `Keyboard` key constants. Not yet: `switch`, `for in`/ + `for each`, arrays and objects, `new`, bitwise operators, string methods, nested function + declarations, closures, `try`/`throw`. +* **Reading properties.** `x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `name`, + `mouseX/Y` of named instances, the timeline (`this`, `parent`, `root`) and the event's + targets; `currentFrame` (1-based), `totalFrames` (every scene's for the main timeline), + `currentLabel` (the label at or before the playhead, or `null`) of movie clips and the main + timeline. A value a script set reads back as set; one the timeline gives is decomposed from + its transform. Values are the transform's `f32` numbers written shortest (`0.1`, not + `0.10000000149011612`), which is also what the HTML page reads from its JSON, so both say + the same. `mouseX/Y` keep the pointer's last place after it leaves, as in ActionScript. + Reading an instance that isn't there **stops the script there** (ActionScript throws), unlike + an action on a missing instance, which still writes an Output line and goes on (tier 2). +* **Listeners.** `removeEventListener` (by event, timeline and function name; an inline + function can't be removed). `Event.ENTER_FRAME` on the timeline, a movie clip, a button or + the stage: every frame, playing or stopped, **after playheads move and before that frame's + scripts run** (ActionScript dispatches `enterFrame` before frame scripts), in the order the + listeners were added. `KeyboardEvent.KEY_DOWN` and `KEY_UP` on the **stage** (where keys go + when nothing has focus, as in a published movie) with `e.keyCode`; elsewhere they would + never fire, so they are ignored and noted. `e.target` and `e.currentTarget` are the instance + listened to (the stage for keys); with no bubbling yet, a part inside a clip is not a + target of its own. `e == …` between instances compares them (`e.currentTarget == btn_a`). + The event passes on to a function whose parameter is typed `…Event`. Mouse listeners on + the stage and other event fields (`stageX`, `charCode`, `type`) are not yet. +* **Deterministic random.** `Math.random()` draws from a seeded generator in the player state + (Marsaglia's xorshift128, 53 bits per number), so the same document, seed and events give + the same movie, tested. `start_seeded(doc, seed, …)`; `control.test_movie` takes `seed` + (default 0); the app's Test Movie seeds from the clock on each start (screenshots use 0), and + the HTML page from `crypto.getRandomValues`. +* **Fuel, and how a script stops.** Every statement and expression costs one unit of fuel, a + loop's turn one more, and making text one more per 64 characters. A frame script or one + listener call gets 100,000; a step 1,000,000 over all of them. A script that runs out stops + where it is with one Output line ("Script on frame 3 of the main timeline stopped: it ran + more than 100000 steps (an endless loop?)"), and so does one that hits a run-time error + ("… stopped: line 4: no instance named “ghost” here"); what it did before stays done, as an + ActionScript error leaves it, and the movie plays on. When the step's fuel is used up, the + step stops running actions with the existing message. Calls nest at most 16 deep, text is + at most 16,384 UTF-16 units, an Output line 1,000 (cut at a whole character); a binary + operator chain counts toward the 64-level nesting limit, so evaluating never recurses + without bound (a test runs the deepest allowed code on a 512 KiB stack). Measured (this + build's optimised dev profile): a 100,000-fuel loop runs in about 2 ms, so a step's whole + budget is about 20 ms. +* **Test Movie keyboard.** The movie surface takes the keyboard when the window opens and when + it is clicked; its keys (letters, digits, arrows, Space, Enter, Tab, Backspace, F1–F12, …) + go to the movie as ActionScript key codes, Tab and the arrows included; shortcuts with Ctrl + (⌘) or Alt still reach the app (Restart is Ctrl+Enter) and Esc closes the window. The window + says "Keys go to the movie" (or "Click the movie to give it the keyboard") when the movie + listens for keys. `control.test_movie` events take `{type: key_down|key_up|key, key}` with a + code, a letter or a `Keyboard` name. +* **HTML canvas export.** A script that runs goes out as its IR (`{"as": {"b": body, "i": + inline functions}}`), each timeline that runs scripts with its declarations (`fn`, `vt`), + and `player.js` mirrors the evaluator line for line, using JavaScript's own operators for + ECMAScript's. Parity tests play the same scripted documents in both, step by step, comparing + output, state (variables and stage listeners included) and display list, and compare + `Math.random()` number for number at several seeds. Keys reach the page's movie from the + window (arrows and Space stop scrolling the page when the movie listens for keys). +* **Not in tier 2.5:** `switch`, `for in`/`for each`, arrays, objects and `new`, string + methods, bitwise operators, closures and nested functions, event bubbling and `e.target` + inside a clip, mouse listeners on the stage, other event fields, `getChildByName`, `stage` + properties, sound, timers, `navigateToURL` (still noted), and ActionScript 1.0 and 2.0. The + XFL import report counts a script that compiles as running before the timeline is linked. diff --git a/docs/roadmap.md b/docs/roadmap.md index 9e5bdb81..893869f8 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -13,7 +13,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | -| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). Not yet: ActionScript variables, conditions, reading properties, `removeEventListener`, enter-frame and keyboard events, functions from other frames, event bubbling, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | +| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0013 tier 2.5): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | @@ -37,7 +37,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | -| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | +| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. | @@ -58,7 +58,7 @@ titled with its milestone. | M3 | GPU stage: GPU binning inside masks and groups, filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032, GPU binning and hairlines ✅ ADR 0048) | CPU oracle, tiled stage, GPU stage slices 1–4 | | M4 | Text from Animate files | XFL import, text engine (M5 first slice) | | M5 | Audio layers: import, waveform, playback sync | timeline, layers | -| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); next: command macros, or growing the ActionScript subset (variables and conditions) | command registry, plug-in host, action IR and player | +| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0013); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | | M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | From e00b02f7d9ec1ed930280e26d336c2656b600864 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:01:29 -0700 Subject: [PATCH 005/192] fix(html): seed the page's random numbers from the clock; tidy player.js for the analysers (M6) --- crates/render/src/html/canvas.js | 5 +++-- crates/render/src/html/player.js | 16 ++++++++-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index 6e45cfbb..e91c692e 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -40,8 +40,9 @@ return scratch.isPointInStroke(stagePath(path, m), x, y); }, }; - // Each page load gets its own Math.random() sequence; the player itself is deterministic. - const seed = window.crypto && window.crypto.getRandomValues ? window.crypto.getRandomValues(new Uint32Array(1))[0] : Math.floor(Math.random() * 4294967296); + // Each page load gets its own Math.random() sequence (a movie's, not for security); the + // player itself is deterministic. + const seed = Date.now() % 4294967296; const player = new AniCraft.Player(movie, host, seed); function stagePath(path, m) { diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index adc59d4d..7e488cdc 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -415,7 +415,7 @@ var AniCraft = (function () { // A literal of the IR's JSON: "u", "null", "nan", {b}, {n}, {s}, {inf}. function lit(v) { - if (typeof v === "string") return v === "null" ? null : v === "nan" ? NaN : undefined; + if (typeof v === "string") return v === "null" ? null : v === "nan" ? Number.NaN : undefined; if ("b" in v) return v.b; if ("n" in v) return v.n; if ("s" in v) return v.s; @@ -425,7 +425,7 @@ var AniCraft = (function () { function defaultOf(t) { switch (t) { case "number": - return NaN; + return Number.NaN; case "int": case "uint": return 0; @@ -442,7 +442,7 @@ var AniCraft = (function () { case "number": return +v; case "int": - return +v | 0; + return +v >> 0; case "uint": return +v >>> 0; case "boolean": @@ -462,7 +462,7 @@ var AniCraft = (function () { function minMax(vals, max) { let out = max ? -Infinity : Infinity; for (const v of vals) { - if (Number.isNaN(v)) return NaN; + if (Number.isNaN(v)) return Number.NaN; if ((max && v > out) || (!max && v < out)) out = v; } return out; @@ -498,7 +498,7 @@ var AniCraft = (function () { const [m, e] = v.toExponential().split("e"); const neg = m[0] === "-"; const digits = m.replace("-", "").replace(".", ""); - const exp = parseInt(e, 10); + const exp = Number.parseInt(e, 10); let out; if (exp < 0) out = "0." + "0".repeat(-exp - 1) + digits; else out = digits + "0".repeat(Math.max(exp - (digits.length - 1), 0)); @@ -792,7 +792,7 @@ var AniCraft = (function () { case "math": { const v = []; for (const a of e.args) v.push(+this.expr(a, fr)); - const x = v.length > 0 ? v[0] : NaN; + const x = v.length > 0 ? v[0] : Number.NaN; switch (e.f) { case "min": return minMax(v, false); @@ -809,7 +809,7 @@ var AniCraft = (function () { case "random": return this.w.random(); } - return NaN; + return Number.NaN; } case "call": { const f = this.w.fn(e.f); @@ -1034,7 +1034,7 @@ var AniCraft = (function () { }); 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])]); const kind = (v) => (v === undefined ? "u" : v === null ? "null" : typeof v === "boolean" ? "b" : typeof v === "number" ? "n" : "s"); - const vars = Array.from(st.vars.values()).sort((a, b) => comparePaths(a.path, b.path)).map((x) => [x.path, Object.keys(x.v).sort().map((k) => [k, kind(x.v[k]) + ":" + String(x.v[k])])]); + const vars = Array.from(st.vars.values()).sort((a, b) => comparePaths(a.path, b.path)).map((x) => [x.path, Object.keys(x.v).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).map((k) => [k, kind(x.v[k]) + ":" + String(x.v[k])])]); const stage = st.stage.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, stage: stage, vars: vars, hover: st.hover, pressed: st.pressed, down: st.down }; }; From b71abc4b5ee2e4997ee26118fef70cf238778a9d Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:18:37 -0700 Subject: [PATCH 006/192] chore: re-run the pull request checks (M6) From 9d9377bbf7d541d787c664a276b4062bebbf625f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 04:33:45 -0700 Subject: [PATCH 007/192] docs: ActionScript small logic as ADR 0052 (M6) --- CHANGELOG.md | 2 +- crates/actions/src/as3/ir.rs | 2 +- crates/actions/src/as3/run.rs | 2 +- crates/doc/src/player.rs | 8 +- crates/doc/src/player_tests.rs | 2 +- crates/engine/src/cmds_script.rs | 2 +- crates/engine/src/player.rs | 2 +- crates/render/src/html.rs | 2 +- crates/render/src/html_tests.rs | 2 +- crates/xfl/src/tests.rs | 2 +- docs/adr/0013-actionscript.md | 110 +----------------- docs/adr/0052-actionscript-small-logic.md | 130 ++++++++++++++++++++++ docs/roadmap.md | 6 +- src/actions_panel.rs | 2 +- src/app.rs | 2 +- src/test_movie.rs | 2 +- 16 files changed, 150 insertions(+), 128 deletions(-) create mode 100644 docs/adr/0052-actionscript-small-logic.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 997e8b3a..a20f4c97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -* **Frame scripts in ActionScript 3.0 run small logic** (ADR 0013 tier 2.5, M6). +* **Frame scripts in ActionScript 3.0 run small logic** (ADR 0052, M6). * Typed variables (`var score:int = 0;` as Number, int, uint, Boolean, String or untyped), kept per timeline instance across its frame scripts as Animate timelines keep them; expressions (arithmetic, comparison, logic, joining text, `Math.min/max/abs/floor/ceil/ diff --git a/crates/actions/src/as3/ir.rs b/crates/actions/src/as3/ir.rs index eeaac074..327e4aa3 100644 --- a/crates/actions/src/as3/ir.rs +++ b/crates/actions/src/as3/ir.rs @@ -1,4 +1,4 @@ -//! The script IR (ADR 0013 tier 2.5): a small, typed form of statements and expressions that a +//! The script IR (ADR 0052): a small, typed form of statements and expressions that a //! compiled script runs as, evaluated by [`super::run`]. It is data, not code: the player (and //! the HTML canvas player, which reads the same IR as JSON) walks it with a fuel budget. //! diff --git a/crates/actions/src/as3/run.rs b/crates/actions/src/as3/run.rs index a2a8f164..29900460 100644 --- a/crates/actions/src/as3/run.rs +++ b/crates/actions/src/as3/run.rs @@ -1,4 +1,4 @@ -//! Running the script IR (ADR 0013 tier 2.5): a small tree-walking evaluator over a +//! Running the script IR (ADR 0052): a small tree-walking evaluator over a //! [`World`] (the player, which knows the movie). It is deterministic (the only random numbers //! come from the world's seeded generator) and bounded: every statement and expression costs //! fuel, text has a length limit, calls a depth limit. When fuel runs out or something can't diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index b1eb167e..b156b70a 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -181,7 +181,7 @@ pub struct PlayerState { pub listeners: BTreeMap>, /// Listeners on the stage (keyboard and enter-frame), in the order added. pub stage: Vec, - /// Each timeline instance's variables (ADR 0013 tier 2.5), by name. + /// Each timeline instance's variables (ADR 0052), by name. pub vars: BTreeMap>, /// The random generator. pub rng: Rng, @@ -500,7 +500,7 @@ struct Run<'a, 'h> { /// The frame each graphic showed when the step began: one that shows another frame at /// its end has entered it (and starts its sounds). graphics: BTreeMap, - /// Each timeline's declarations (ADR 0013 tier 2.5), made the first time a script there + /// Each timeline's declarations (ADR 0052), made the first time a script there /// needs them. decls: BTreeMap>, /// Script fuel left this step. @@ -725,7 +725,7 @@ impl<'a, 'h> Run<'a, 'h> { self.decls.entry(key).or_insert_with(|| Arc::new(decls(doc, key))).clone() } - /// Runs a compiled frame script on timeline `owner` (ADR 0013 tier 2.5): when every name + /// Runs a compiled frame script on timeline `owner` (ADR 0052): when every name /// it takes from other frames is there, its statements run with the fuel the step has left. fn run_script(&mut self, owner: &[ElementId], frame: u32, c: &'a Compiled) { let Some(i) = self.index_of(owner) else { return }; @@ -1297,7 +1297,7 @@ fn decompose64(m: &Affine) -> [f64; 5] { [e, f, sx, sy, r] } -/// A running script's view of the movie (ADR 0013 tier 2.5). +/// A running script's view of the movie (ADR 0052). struct Script<'r, 'a, 'h> { r: &'r mut Run<'a, 'h>, /// The timeline the script belongs to. diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index b110f013..d31840a0 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -449,7 +449,7 @@ fn next_scene_in_a_movie_clip_script_stays_in_its_clip() { assert_eq!(s.output, ["Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"]); } -// ----- ActionScript small logic (ADR 0013 tier 2.5) --------------------------------------------- +// ----- ActionScript small logic (ADR 0052) --------------------------------------------- /// A one-layer main timeline of `frames` frames with scripts on some of them, and `extra` layers. fn scripted(frames: u32, scripts: &[(u32, &str)], extra: Vec>, library: Vec>) -> Document { diff --git a/crates/engine/src/cmds_script.rs b/crates/engine/src/cmds_script.rs index 95db0928..0ddb7de1 100644 --- a/crates/engine/src/cmds_script.rs +++ b/crates/engine/src/cmds_script.rs @@ -50,7 +50,7 @@ fn what(script: &Option) -> Value { /// Whether a script runs, its problems and notes (each `{line, column, message}`; line 0 is /// the whole script). `links`: why it doesn't run on its timeline although it compiles (a -/// name from another frame that isn't there, ADR 0013 tier 2.5). +/// name from another frame that isn't there, ADR 0052). fn status(c: &CompileResult, links: &[Problem]) -> Value { match c { Ok(c) if links.is_empty() => json!({"runs": true, "problems": [], "notes": c.notes}), diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index 56281b03..e57000ed 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -292,7 +292,7 @@ pub struct KeptScript<'a> { pub plays: bool, pub compiled: &'a CompileResult, /// Why it doesn't run on its timeline although it compiles: names from other frames that - /// aren't there (ADR 0013 tier 2.5). + /// aren't there (ADR 0052). pub links: Vec, } diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 5b69d04f..18011879 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -486,7 +486,7 @@ impl<'a> Bake<'a> { /// `nm`, labels `lb`, and per frame the scripts `a` and sounds `snd` of keyframes starting /// there (top layer first). A scene's frames seen through its camera (ADR 0027) carry the /// camera's tint (`cc`) and each layer its view (`v`: the camera and the layer's depth). - /// `decls`: the declarations its frame scripts share (ADR 0013 tier 2.5), for timelines that + /// `decls`: the declarations its frame scripts share (ADR 0052), for timelines that /// run scripts; their functions go out as `fn` and their variables' types as `vt`. fn timeline(&mut self, tl: &Timeline, scene: bool, decls: Option<&Decls>) -> Value { let n = tl.frame_count(); diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 5d5b2ee8..39b91926 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -722,7 +722,7 @@ fn actionscript_plays_the_movie_its_hand_made_actions_play() { } } -/// A movie that uses the small-logic tier (ADR 0013 tier 2.5): typed variables kept per +/// A movie that uses the small-logic tier (ADR 0052): typed variables kept per /// timeline and per clip instance, expressions, `if`, loops, `Math.random()`, functions from /// another frame, property reads, enter-frame and keyboard listeners that add and remove /// themselves, `e.target`, a runtime error and a loop that runs out of fuel. diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index f01b10e6..b521f172 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -446,7 +446,7 @@ trace(n);]]>"); let (d, report) = import(&files).unwrap(); assert!(d.document_class.is_empty() && !report.kept.contains_key("document class")); - // Read as ActionScript 3.0, its variable and `?:` are in the subset now (ADR 0013 tier 2.5). + // Read as ActionScript 3.0, its variable and `?:` are in the subset now (ADR 0052). assert!(report.runs.contains_key("frame scripts in ActionScript 3.0")); } diff --git a/docs/adr/0013-actionscript.md b/docs/adr/0013-actionscript.md index eb4c2438..07f0b3a0 100644 --- a/docs/adr/0013-actionscript.md +++ b/docs/adr/0013-actionscript.md @@ -2,7 +2,7 @@ * Status: accepted (2026-11-08) as scope and placement. **Tier 1 built** (2026-11-09, see "Tier 1 as built" below). **Tier 2 built** (2026-11-10, see "Tier 2 as built"). **Tier 2.5, - small logic, built** (2026-11-11, see "Tier 2.5 as built") + small logic, built** (2026-11-11, ADR 0052) * Relates to: requirements U2 (scripting surface), roadmap M6, ADR 0009 (XFL import), `docs/legal/compliance.md` @@ -241,111 +241,3 @@ Tier 2 follows the decision above. Where the build refines it: event bubbling from a clip's children to its listeners, `e.target`, `getChildByName`, sound and `stage`, and ActionScript 1.0 and 2.0. Each is reported where it is, so the subset can grow from what users' files actually use. - -## Tier 2.5 as built (2026-11-11): small logic - -Item 2 of the context ("variables, `if`, loops, `trace`, setting instance properties, simple -functions"), which tier 2 left out. Where the build refines the decision: - -* **A script IR, run by an evaluator, instead of a flat action list.** Small logic can't be - lowered to actions ahead of time (a loop's count, a condition, a computed frame depend on - the movie), so a compiled script is now a small typed tree of statements and expressions - (`anicraft_actions::as3::ir`: `Stmt`, `Expr`, `LValue`, `Place`, `Function`) and - `as3::run` evaluates it against a `World` trait that the player implements. It is data, not - code: no dynamic evaluation, no `eval`, no reflection. Timeline control still ends in the - same `Action`s (an `Act` statement builds one with the frame and scene computed), so hand-made - actions, plug-in frame scripts and ActionScript keep one runtime. The tier-2 `ScriptOp` - list is gone; `script.check` returns `steps` (a count), `program` (the IR as JSON) and - `uses`. Both the evaluator and its interface stay in the L0 crate: it knows values and - names, not documents. -* **Values and types.** ActionScript's primitives (`undefined`, `null`, Boolean, Number, - String), with ECMA-262's operators exactly: `+` joins when either side is text, `==` and - `<` as §11.8–11.9 (text compares by UTF-16 units), ToNumber as browsers read text (decimal, - `Infinity`, `0x`/`0o`/`0b`), ToString as `Number.toString`. Typed variables coerce on every - write: `int` and `uint` as ToInt32/ToUint32 (so `2147483647 + 1` wraps), Number, Boolean, - String (`null` stays `null`), untyped keeps anything; each starts at its type's default (0, - NaN, false, null, undefined). `int(…)`, `uint(…)`, `Number(…)`, `String(…)`, `Boolean(…)` - cast. Other types (`Array`, `MovieClip`, objects) are problems. -* **Where variables live, as ActionScript 3.0 timelines keep them.** A `var` at a frame - script's top level is a member of the timeline: one table per timeline *instance* - (`PlayerState.vars`, by instance path), shared by every frame script of that timeline, kept - while the instance stays on the stage and gone when it leaves (a clip that comes back starts - afresh), as an instance is constructed again. Every variable any frame of the timeline - declares exists from the start with its default, so frame 1 can read what frame 5 declares - (`null` until it runs). `var` inside a function is that call's (hoisted, numbered slots). - The main timeline's scenes share one table, as they are one timeline. -* **Linking across frames.** A script compiles on its own (the cached compile stays a pure - function of its text) and lists the names it takes from elsewhere (`Compiled::free`). A - timeline's **declarations** (`Decls`: its scripts' functions and variable types, the first - of each name in frame order, top layer first) are built from its compiled scripts; a script - whose free names the timeline doesn't declare, or that declares a function or a variable - type another frame already declares differently, doesn't run (whole, as before), and Test - Movie's first lines, the Script view, `script.set` and `script.list` say which name and - where. So functions on **any** frame of the same timeline can be called (ActionScript makes - them methods of the timeline), not only earlier ones. Calls go by name through the - declarations at run time. -* **Statements.** `if`/`else`, `for (init; cond; next)`, `while`, `do … while`, `break` and - `continue` (no labels), `return` with a value (coerced to the declared result type), calls - with parameters (typed, defaults written out) and recursion, `++`/`--` and `+= -= *= /= %=` - on variables and instance properties, `&&`/`||`/`?:`, `Math.min/max/abs/floor/ceil/round/ - random`, `Math.PI` and `Math.E`, the `Keyboard` key constants. Not yet: `switch`, `for in`/ - `for each`, arrays and objects, `new`, bitwise operators, string methods, nested function - declarations, closures, `try`/`throw`. -* **Reading properties.** `x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `name`, - `mouseX/Y` of named instances, the timeline (`this`, `parent`, `root`) and the event's - targets; `currentFrame` (1-based), `totalFrames` (every scene's for the main timeline), - `currentLabel` (the label at or before the playhead, or `null`) of movie clips and the main - timeline. A value a script set reads back as set; one the timeline gives is decomposed from - its transform. Values are the transform's `f32` numbers written shortest (`0.1`, not - `0.10000000149011612`), which is also what the HTML page reads from its JSON, so both say - the same. `mouseX/Y` keep the pointer's last place after it leaves, as in ActionScript. - Reading an instance that isn't there **stops the script there** (ActionScript throws), unlike - an action on a missing instance, which still writes an Output line and goes on (tier 2). -* **Listeners.** `removeEventListener` (by event, timeline and function name; an inline - function can't be removed). `Event.ENTER_FRAME` on the timeline, a movie clip, a button or - the stage: every frame, playing or stopped, **after playheads move and before that frame's - scripts run** (ActionScript dispatches `enterFrame` before frame scripts), in the order the - listeners were added. `KeyboardEvent.KEY_DOWN` and `KEY_UP` on the **stage** (where keys go - when nothing has focus, as in a published movie) with `e.keyCode`; elsewhere they would - never fire, so they are ignored and noted. `e.target` and `e.currentTarget` are the instance - listened to (the stage for keys); with no bubbling yet, a part inside a clip is not a - target of its own. `e == …` between instances compares them (`e.currentTarget == btn_a`). - The event passes on to a function whose parameter is typed `…Event`. Mouse listeners on - the stage and other event fields (`stageX`, `charCode`, `type`) are not yet. -* **Deterministic random.** `Math.random()` draws from a seeded generator in the player state - (Marsaglia's xorshift128, 53 bits per number), so the same document, seed and events give - the same movie, tested. `start_seeded(doc, seed, …)`; `control.test_movie` takes `seed` - (default 0); the app's Test Movie seeds from the clock on each start (screenshots use 0), and - the HTML page from `crypto.getRandomValues`. -* **Fuel, and how a script stops.** Every statement and expression costs one unit of fuel, a - loop's turn one more, and making text one more per 64 characters. A frame script or one - listener call gets 100,000; a step 1,000,000 over all of them. A script that runs out stops - where it is with one Output line ("Script on frame 3 of the main timeline stopped: it ran - more than 100000 steps (an endless loop?)"), and so does one that hits a run-time error - ("… stopped: line 4: no instance named “ghost” here"); what it did before stays done, as an - ActionScript error leaves it, and the movie plays on. When the step's fuel is used up, the - step stops running actions with the existing message. Calls nest at most 16 deep, text is - at most 16,384 UTF-16 units, an Output line 1,000 (cut at a whole character); a binary - operator chain counts toward the 64-level nesting limit, so evaluating never recurses - without bound (a test runs the deepest allowed code on a 512 KiB stack). Measured (this - build's optimised dev profile): a 100,000-fuel loop runs in about 2 ms, so a step's whole - budget is about 20 ms. -* **Test Movie keyboard.** The movie surface takes the keyboard when the window opens and when - it is clicked; its keys (letters, digits, arrows, Space, Enter, Tab, Backspace, F1–F12, …) - go to the movie as ActionScript key codes, Tab and the arrows included; shortcuts with Ctrl - (⌘) or Alt still reach the app (Restart is Ctrl+Enter) and Esc closes the window. The window - says "Keys go to the movie" (or "Click the movie to give it the keyboard") when the movie - listens for keys. `control.test_movie` events take `{type: key_down|key_up|key, key}` with a - code, a letter or a `Keyboard` name. -* **HTML canvas export.** A script that runs goes out as its IR (`{"as": {"b": body, "i": - inline functions}}`), each timeline that runs scripts with its declarations (`fn`, `vt`), - and `player.js` mirrors the evaluator line for line, using JavaScript's own operators for - ECMAScript's. Parity tests play the same scripted documents in both, step by step, comparing - output, state (variables and stage listeners included) and display list, and compare - `Math.random()` number for number at several seeds. Keys reach the page's movie from the - window (arrows and Space stop scrolling the page when the movie listens for keys). -* **Not in tier 2.5:** `switch`, `for in`/`for each`, arrays, objects and `new`, string - methods, bitwise operators, closures and nested functions, event bubbling and `e.target` - inside a clip, mouse listeners on the stage, other event fields, `getChildByName`, `stage` - properties, sound, timers, `navigateToURL` (still noted), and ActionScript 1.0 and 2.0. The - XFL import report counts a script that compiles as running before the timeline is linked. diff --git a/docs/adr/0052-actionscript-small-logic.md b/docs/adr/0052-actionscript-small-logic.md new file mode 100644 index 00000000..cd74ad5e --- /dev/null +++ b/docs/adr/0052-actionscript-small-logic.md @@ -0,0 +1,130 @@ +# ADR 0052: ActionScript small logic (tier 2.5) + +* Status: accepted (2026-11-11), built +* Relates to: ADR 0013 (ActionScript compatibility: tiers 1 and 2, the plan), ADR 0024 (the + action IR and the pure player), ADR 0028 (HTML canvas export and `player.js`), roadmap M6 + +## Context + +ADR 0013's tier 2 runs the ActionScript 3.0 timeline subset by lowering scripts to a flat list +of timeline actions ahead of time. Item 2 of that ADR's context, "small logic" (variables, +`if`, loops, `trace`, setting and reading instance properties, simple functions), can't be said +that way: a loop's count, a condition or a computed frame depend on the movie as it plays. +Tier 2 left out variables and conditions, reading properties, `removeEventListener`, +enter-frame and keyboard events, functions on other frames, `e.target` and `Math.random`. + +## Decision + +* **A script IR, run by an evaluator, instead of a flat action list.** Small logic can't be + lowered to actions ahead of time (a loop's count, a condition, a computed frame depend on + the movie), so a compiled script is now a small typed tree of statements and expressions + (`anicraft_actions::as3::ir`: `Stmt`, `Expr`, `LValue`, `Place`, `Function`) and + `as3::run` evaluates it against a `World` trait that the player implements. It is data, not + code: no dynamic evaluation, no `eval`, no reflection. Timeline control still ends in the + same `Action`s (an `Act` statement builds one with the frame and scene computed), so hand-made + actions, plug-in frame scripts and ActionScript keep one runtime. The tier-2 `ScriptOp` + list is gone; `script.check` returns `steps` (a count), `program` (the IR as JSON) and + `uses`. Both the evaluator and its interface stay in the L0 crate: it knows values and + names, not documents. +* **Values and types.** ActionScript's primitives (`undefined`, `null`, Boolean, Number, + String), with ECMA-262's operators exactly: `+` joins when either side is text, `==` and + `<` as §11.8–11.9 (text compares by UTF-16 units), ToNumber as browsers read text (decimal, + `Infinity`, `0x`/`0o`/`0b`), ToString as `Number.toString`. Typed variables coerce on every + write: `int` and `uint` as ToInt32/ToUint32 (so `2147483647 + 1` wraps), Number, Boolean, + String (`null` stays `null`), untyped keeps anything; each starts at its type's default (0, + NaN, false, null, undefined). `int(…)`, `uint(…)`, `Number(…)`, `String(…)`, `Boolean(…)` + cast. Other types (`Array`, `MovieClip`, objects) are problems. +* **Where variables live, as ActionScript 3.0 timelines keep them.** A `var` at a frame + script's top level is a member of the timeline: one table per timeline *instance* + (`PlayerState.vars`, by instance path), shared by every frame script of that timeline, kept + while the instance stays on the stage and gone when it leaves (a clip that comes back starts + afresh), as an instance is constructed again. Every variable any frame of the timeline + declares exists from the start with its default, so frame 1 can read what frame 5 declares + (`null` until it runs). `var` inside a function is that call's (hoisted, numbered slots). + The main timeline's scenes share one table, as they are one timeline. +* **Linking across frames.** A script compiles on its own (the cached compile stays a pure + function of its text) and lists the names it takes from elsewhere (`Compiled::free`). A + timeline's **declarations** (`Decls`: its scripts' functions and variable types, the first + of each name in frame order, top layer first) are built from its compiled scripts; a script + whose free names the timeline doesn't declare, or that declares a function or a variable + type another frame already declares differently, doesn't run (whole, as before), and Test + Movie's first lines, the Script view, `script.set` and `script.list` say which name and + where. So functions on **any** frame of the same timeline can be called (ActionScript makes + them methods of the timeline), not only earlier ones. Calls go by name through the + declarations at run time. +* **Statements.** `if`/`else`, `for (init; cond; next)`, `while`, `do … while`, `break` and + `continue` (no labels), `return` with a value (coerced to the declared result type), calls + with parameters (typed, defaults written out) and recursion, `++`/`--` and `+= -= *= /= %=` + on variables and instance properties, `&&`/`||`/`?:`, `Math.min/max/abs/floor/ceil/round/ + random`, `Math.PI` and `Math.E`, the `Keyboard` key constants. Not yet: `switch`, `for in`/ + `for each`, arrays and objects, `new`, bitwise operators, string methods, nested function + declarations, closures, `try`/`throw`. +* **Reading properties.** `x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `name`, + `mouseX/Y` of named instances, the timeline (`this`, `parent`, `root`) and the event's + targets; `currentFrame` (1-based), `totalFrames` (every scene's for the main timeline), + `currentLabel` (the label at or before the playhead, or `null`) of movie clips and the main + timeline. A value a script set reads back as set; one the timeline gives is decomposed from + its transform. Values are the transform's `f32` numbers written shortest (`0.1`, not + `0.10000000149011612`), which is also what the HTML page reads from its JSON, so both say + the same. `mouseX/Y` keep the pointer's last place after it leaves, as in ActionScript. + Reading an instance that isn't there **stops the script there** (ActionScript throws), unlike + an action on a missing instance, which still writes an Output line and goes on (tier 2). +* **Listeners.** `removeEventListener` (by event, timeline and function name; an inline + function can't be removed). `Event.ENTER_FRAME` on the timeline, a movie clip, a button or + the stage: every frame, playing or stopped, **after playheads move and before that frame's + scripts run** (ActionScript dispatches `enterFrame` before frame scripts), in the order the + listeners were added. `KeyboardEvent.KEY_DOWN` and `KEY_UP` on the **stage** (where keys go + when nothing has focus, as in a published movie) with `e.keyCode`; elsewhere they would + never fire, so they are ignored and noted. `e.target` and `e.currentTarget` are the instance + listened to (the stage for keys); with no bubbling yet, a part inside a clip is not a + target of its own. `e == …` between instances compares them (`e.currentTarget == btn_a`). + The event passes on to a function whose parameter is typed `…Event`. Mouse listeners on + the stage and other event fields (`stageX`, `charCode`, `type`) are not yet. +* **Deterministic random.** `Math.random()` draws from a seeded generator in the player state + (Marsaglia's xorshift128, 53 bits per number), so the same document, seed and events give + the same movie, tested. `start_seeded(doc, seed, …)`; `control.test_movie` takes `seed` + (default 0); the app's Test Movie seeds from the clock on each start (screenshots use 0), and + the HTML page from `crypto.getRandomValues`. +* **Fuel, and how a script stops.** Every statement and expression costs one unit of fuel, a + loop's turn one more, and making text one more per 64 characters. A frame script or one + listener call gets 100,000; a step 1,000,000 over all of them. A script that runs out stops + where it is with one Output line ("Script on frame 3 of the main timeline stopped: it ran + more than 100000 steps (an endless loop?)"), and so does one that hits a run-time error + ("… stopped: line 4: no instance named “ghost” here"); what it did before stays done, as an + ActionScript error leaves it, and the movie plays on. When the step's fuel is used up, the + step stops running actions with the existing message. Calls nest at most 16 deep, text is + at most 16,384 UTF-16 units, an Output line 1,000 (cut at a whole character); a binary + operator chain counts toward the 64-level nesting limit, so evaluating never recurses + without bound (a test runs the deepest allowed code on a 512 KiB stack). Measured (this + build's optimised dev profile): a 100,000-fuel loop runs in about 2 ms, so a step's whole + budget is about 20 ms. +* **Test Movie keyboard.** The movie surface takes the keyboard when the window opens and when + it is clicked; its keys (letters, digits, arrows, Space, Enter, Tab, Backspace, F1–F12, …) + go to the movie as ActionScript key codes, Tab and the arrows included; shortcuts with Ctrl + (⌘) or Alt still reach the app (Restart is Ctrl+Enter) and Esc closes the window. The window + says "Keys go to the movie" (or "Click the movie to give it the keyboard") when the movie + listens for keys. `control.test_movie` events take `{type: key_down|key_up|key, key}` with a + code, a letter or a `Keyboard` name. +* **HTML canvas export.** A script that runs goes out as its IR (`{"as": {"b": body, "i": + inline functions}}`), each timeline that runs scripts with its declarations (`fn`, `vt`), + and `player.js` mirrors the evaluator line for line, using JavaScript's own operators for + ECMAScript's. Parity tests play the same scripted documents in both, step by step, comparing + output, state (variables and stage listeners included) and display list, and compare + `Math.random()` number for number at several seeds. Keys reach the page's movie from the + window (arrows and Space stop scrolling the page when the movie listens for keys). +* **Not in tier 2.5:** `switch`, `for in`/`for each`, arrays, objects and `new`, string + methods, bitwise operators, closures and nested functions, event bubbling and `e.target` + inside a clip, mouse listeners on the stage, other event fields, `getChildByName`, `stage` + properties, sound, timers, `navigateToURL` (still noted), and ActionScript 1.0 and 2.0. The + XFL import report counts a script that compiles as running before the timeline is linked. + +## Consequences + +* Scripts from Animate files that count, branch, loop, read where things are or answer the + keyboard now play in Test Movie and the HTML page; the rest are still kept, not run, with + the reason in place. +* The player and `player.js` now share an evaluator's semantics, not just a list of actions: + every change to the IR or the evaluator needs both sides and a parity test. +* Exports other than HTML canvas, the stage and `evaluate` are unchanged: scripts never touch + the document (ADR 0013's "time stays a function"). + diff --git a/docs/roadmap.md b/docs/roadmap.md index 893869f8..96341eea 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -13,7 +13,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | -| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0013 tier 2.5): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | +| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | @@ -37,7 +37,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | -| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | +| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. | @@ -58,7 +58,7 @@ titled with its milestone. | M3 | GPU stage: GPU binning inside masks and groups, filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032, GPU binning and hairlines ✅ ADR 0048) | CPU oracle, tiled stage, GPU stage slices 1–4 | | M4 | Text from Animate files | XFL import, text engine (M5 first slice) | | M5 | Audio layers: import, waveform, playback sync | timeline, layers | -| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0013); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | +| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | | M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | diff --git a/src/actions_panel.rs b/src/actions_panel.rs index 61d499c9..77a5f3aa 100644 --- a/src/actions_panel.rs +++ b/src/actions_panel.rs @@ -379,7 +379,7 @@ fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&S let code = font(Type::Path); let rows = shown.split('\n').count().max(1); let editor_id = ui.make_persistent_id("act_script_editor"); - // Names it takes from other frames of its timeline that aren't there (ADR 0013 tier 2.5). + // Names it takes from other frames of its timeline that aren't there (ADR 0052). let links = match src.map(|s| s.compiled()) { Some(Ok(c)) if t.runs => { let which = t.base.get("symbol").and_then(Value::as_u64).map_or(anicraft_engine::doc::player::TimelineRef::Root, |id| anicraft_engine::doc::player::TimelineRef::Symbol(SymbolId(id))); diff --git a/src/app.rs b/src/app.rs index bc625165..ba0bab2c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1874,7 +1874,7 @@ impl App { if keys == crate::a11y::Keyboard::Text || self.palette.is_some() { return; } - // The Test Movie window's movie has the keyboard (ADR 0013 tier 2.5): its keys are the + // The Test Movie window's movie has the keyboard (ADR 0052): its keys are the // movie's; only shortcuts with Ctrl (⌘) or Alt reach the app (Restart is Ctrl+Enter). if self.test_movie.is_some() && crate::test_movie::has_keys(ctx) { let fire: Vec<&'static str> = ctx.input_mut(|i| self.shortcuts.iter().filter(|(m, _, _)| m.command || m.ctrl || m.alt).filter_map(|(m, k, id)| i.consume_key(*m, *k).then_some(*id)).collect()); diff --git a/src/test_movie.rs b/src/test_movie.rs index d7121a03..816096b3 100644 --- a/src/test_movie.rs +++ b/src/test_movie.rs @@ -10,7 +10,7 @@ //! (`doc::sound::trigger`), movie clips' and graphics' included, and while sound plays the //! movie keeps time with it, as the stage does. //! -//! Its keyboard (ADR 0013 tier 2.5): while the movie has the focus (it takes it when the window +//! Its keyboard (ADR 0052): while the movie has the focus (it takes it when the window //! opens and when clicked), keys go to the movie's keyboard listeners as ActionScript key //! codes, Tab and the arrows included; shortcuts with Ctrl (⌘ on macOS) still reach the app, //! and Esc closes the window. From e25919662188df6890868c6809c671fa1ffba567 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:01:56 -0700 Subject: [PATCH 008/192] docs: reserve ADR 0055 for 9-slice scaling (M2) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..0bb33150 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0055 | m2/nine-slice | 9-slice scaling for symbols | From 94ad425c7134eda1bf999f44b08e8df062b4f797 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:10:55 -0700 Subject: [PATCH 009/192] feat(doc): 9-slice guides on symbols, sliced evaluation and XFL scaleGrid import (M2) --- crates/doc/src/armature_tests.rs | 2 +- crates/doc/src/camera_tests.rs | 2 +- crates/doc/src/eval.rs | 83 ++++-- crates/doc/src/eval_tests.rs | 6 +- crates/doc/src/lib.rs | 46 +++ crates/doc/src/library.rs | 2 +- crates/doc/src/library_tests.rs | 2 +- crates/doc/src/nine_slice.rs | 78 ++++++ crates/doc/src/nine_slice_tests.rs | 173 ++++++++++++ crates/doc/src/player_tests.rs | 2 +- crates/doc/src/sample.rs | 8 +- crates/doc/src/sound_tests.rs | 2 +- crates/engine/src/cmds_draw.rs | 2 +- crates/engine/src/editing.rs | 2 +- crates/engine/src/tests_bone.rs | 2 +- crates/engine/src/tests_sound.rs | 2 +- crates/geom/src/lib.rs | 1 + crates/geom/src/slice.rs | 430 +++++++++++++++++++++++++++++ crates/render/src/html_tests.rs | 8 +- crates/xfl/src/import.rs | 30 +- 20 files changed, 835 insertions(+), 48 deletions(-) create mode 100644 crates/doc/src/nine_slice.rs create mode 100644 crates/doc/src/nine_slice_tests.rs create mode 100644 crates/geom/src/slice.rs diff --git a/crates/doc/src/armature_tests.rs b/crates/doc/src/armature_tests.rs index 56067e98..b385f977 100644 --- a/crates/doc/src/armature_tests.rs +++ b/crates/doc/src/armature_tests.rs @@ -173,7 +173,7 @@ fn every_export_sees_the_pose() { let mut k = Keyframe::new(0, 1); k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) })); seg.keyframes = vec![Arc::new(k)]; - d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(seg)] } })); + d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(seg)] } })); d.timeline_mut(0).layers = vec![Arc::new(armature_layer(Easing::Linear))]; d.sanitize(); let dl = evaluate(&d, 10); diff --git a/crates/doc/src/camera_tests.rs b/crates/doc/src/camera_tests.rs index 7854e915..75889596 100644 --- a/crates/doc/src/camera_tests.rs +++ b/crates/doc/src/camera_tests.rs @@ -141,7 +141,7 @@ fn the_camera_stays_on_top_alone_and_old_files_read_without_one() { // A symbol's camera layer is a normal layer. let mut sl = Layer::new(LayerId(80), "in symbol"); sl.kind = LayerKind::Camera; - d.library.push(Arc::new(Symbol { id: SymbolId(81), name: "S".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(sl)] } })); + d.library.push(Arc::new(Symbol { id: SymbolId(81), name: "S".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(sl)] } })); d.sanitize(); assert_eq!(d.library[0].timeline.layers[0].kind, LayerKind::Normal); // Depth round-trips, is left out when 0, and an old file reads at 0; hostile depths clamp. diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 8fb0a447..c348937e 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1,6 +1,7 @@ //! Timeline evaluation: `(document, frame) -> DisplayList`. Pure, deterministic, no caching. use crate::camera::Camera; +use crate::nine_slice::Slicing; use crate::player::PlayerState; use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind}; use anicraft_geom::walk::PathWalk; @@ -309,11 +310,14 @@ struct Ctx { /// The camera the scene's layers are seen through (main timeline only; each layer's /// transform comes from it and the layer's depth, and `xf` is ignored). camera: Option, + /// The 9-slice scaling of the instance whose timeline this is (ADR 0055): its own shapes go + /// through it, in place of the scale in `xf`. Not passed on to nested symbols. + slice: Option, } impl Ctx { fn top(xf: Affine) -> Ctx { - Ctx { xf, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None } + Ctx { xf, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } } /// A main timeline seen through `camera`: its tint colours everything. @@ -435,29 +439,38 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut let xf = layer_xf.mul(&el.transform); let color = cx.color.concat(&el.color); match &el.kind { - ElementKind::Shape(s) => out.items.push(DisplayItem { - path: s.path.clone(), - transform: xf, - fill: s.fill.clone(), - stroke: s.stroke.clone(), - fill_rule: s.fill_rule, - color, - layer: root_layer, - element: root_el, - outline: layer_outline, - clip, - masks, - guide, - group: cx.group, - image: match &s.fill { - Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels), - _ => None, - }, - smooth: match &s.fill { - Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing), - _ => true, - }, - }), + ElementKind::Shape(s) => { + // Inside a 9-slice instance, the shape's outline is cut and mapped (bitmap + // fills scale normally, as in Animate). + let sliced = cx.slice.filter(|_| !matches!(s.fill, Some(Paint::Bitmap { .. }))).map(|sl| sliced_shape(s, &el.transform, &sl)); + let (path, transform, fill, stroke) = match sliced { + Some(x) => x, + None => (s.path.clone(), xf, s.fill.clone(), s.stroke.clone()), + }; + out.items.push(DisplayItem { + path, + transform, + fill, + stroke, + fill_rule: s.fill_rule, + color, + layer: root_layer, + element: root_el, + outline: layer_outline, + clip, + masks, + guide, + group: cx.group, + image: match &s.fill { + Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels), + _ => None, + }, + smooth: match &s.fill { + Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing), + _ => true, + }, + }); + } ElementKind::Text(t) => out.items.push(DisplayItem { path: t.outline.clone(), transform: xf, @@ -503,7 +516,9 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut } else { (color, cx.group) }; - let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, clip, masks, guide, group, camera: None }; + // A symbol with 9-slice guides, scaled: its shapes are sliced (ADR 0055). + let slice = crate::nine_slice::slicing(doc, sym, &el.transform).map(|s| Slicing { post: layer_xf.mul(&s.post), ..s }); + let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, clip, masks, guide, group, camera: None, slice }; eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref()); } } @@ -511,6 +526,24 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut } } +/// A shape inside a 9-slice instance (ADR 0055): its outline placed by its own transform, then +/// cut at the guides and mapped piecewise; drawn by the instance's transform without its scale. +/// The stroke keeps its width (times the shape's own scale inside the symbol); gradients follow +/// the map, their size the shape's own scale times the instance's. +fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc, Affine, Option, Option) { + let path = Arc::new(anicraft_geom::slice::slice_path(&s.path, own, &sl.map)); + let k = own.mean_scale(); + let stroke = s.stroke.as_ref().map(|st| if (k - 1.0).abs() > 1e-6 { st.scaled(k) } else { st.clone() }); + let at = |p: anicraft_geom::Vec2| sl.map.map(own.apply(p)); + let size = k * sl.scale.mean_scale(); + let fill = s.fill.as_ref().map(|f| match f { + Paint::Linear { start, end, stops } => Paint::Linear { start: at(*start), end: at(*end), stops: stops.clone() }, + Paint::Radial { center, radius, stops } => Paint::Radial { center: at(*center), radius: radius * size, stops: stops.clone() }, + Paint::Solid(_) | Paint::Bitmap { .. } => f.clone(), + }); + (path, sl.post, fill, stroke) +} + #[cfg(test)] #[path = "eval_tests.rs"] mod tests; diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index e2d27250..8f080194 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -85,7 +85,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { }, ); tl.layers.push(Arc::new(layer)); - d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, timeline: tl })); + d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: tl })); push( layer0(&mut d), 0, @@ -140,7 +140,7 @@ fn masks_inside_symbols_nest_in_the_instance_clip() { // The main timeline's masked layer holds an instance of a symbol that has its own mask. let mut d = mask_doc(); let sid = SymbolId(99); - d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, timeline: mask_doc().timeline(0).clone() })); + d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: mask_doc().timeline(0).clone() })); let inst = Element { id: ElementId(60), name: String::new(), @@ -295,7 +295,7 @@ fn movie_clips_play_their_own_timeline_graphics_keep_step_buttons_hold_up() { }) .collect(); let mut d = Document::default(); - d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, timeline: Timeline { layers: vec![Arc::new(st)] } })); + d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(st)] } })); // The same instance on two keyframes back to back (frames 0–4 and 5–11), moved on the second. let inst = |x: f32| Element { id: ElementId(60), diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 258e5431..58573767 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -14,6 +14,7 @@ mod filter; mod easing; mod eval; mod hints; +pub mod nine_slice; pub mod library; pub mod motion; pub mod path_table; @@ -33,6 +34,7 @@ pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, Soun pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle}; pub use camera::Camera; +pub use nine_slice::symbol_box; pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose}; pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; @@ -1019,9 +1021,49 @@ pub struct Symbol { /// The class scripts know the symbol by (Animate's "linkage"), kept as text (ADR 0013). #[serde(default, skip_serializing_if = "Option::is_none")] pub linkage: Option, + /// Guides for 9-slice scaling (ADR 0055): an instance scaled keeps the corners outside them + /// unscaled. `None`: the symbol scales as a whole. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_grid: Option, pub timeline: Timeline, } +/// The four 9-slice guides of a symbol (ADR 0055), in the symbol's own space: two vertical +/// lines at `x = left` and `x = right`, two horizontal ones at `y = top` and `y = bottom`. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ScaleGrid { + pub left: f32, + pub right: f32, + pub top: f32, + pub bottom: f32, +} + +impl ScaleGrid { + /// Guides a quarter of the way in from each edge of `bounds` (what turning guides on gives). + pub fn inset(bounds: &Rect) -> ScaleGrid { + let (w, h) = (bounds.width() * 0.25, bounds.height() * 0.25); + ScaleGrid { left: bounds.min.x + w, right: bounds.max.x - w, top: bounds.min.y + h, bottom: bounds.max.y - h } + } + + /// Whether the guides are usable: finite, within the format's range, and in order. + pub fn check(&self) -> Result<(), String> { + let v = [self.left, self.right, self.top, self.bottom]; + if !v.iter().all(|x| x.is_finite() && x.abs() <= MAX_GRID_COORD) { + return Err(format!("9-slice guides must be numbers within ±{MAX_GRID_COORD}")); + } + if self.left > self.right { + return Err("the left 9-slice guide must not be right of the right one".into()); + } + if self.top > self.bottom { + return Err("the top 9-slice guide must not be below the bottom one".into()); + } + Ok(()) + } +} + +/// Largest 9-slice guide coordinate accepted from files and commands. +pub const MAX_GRID_COORD: f32 = 1_000_000.0; + /// A symbol's script class: what scripts create it by, and the class it extends. Kept with /// the document and shown, never run (ADR 0013 tier 1). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -1271,6 +1313,10 @@ impl Document { if sym.linkage.as_ref().is_some_and(|l| l.check().is_err()) { Arc::make_mut(sym).linkage = None; } + // 9-slice guides that aren't usable are dropped: the symbol scales as a whole. + if sym.scale_grid.as_ref().is_some_and(|g| g.check().is_err()) { + Arc::make_mut(sym).scale_grid = None; + } let tl = &mut Arc::make_mut(sym).timeline; for l in &mut tl.layers { Arc::make_mut(l).normalize(); diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index 6d5f6b6e..9a3c6763 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -388,7 +388,7 @@ impl Document { let src = self.library.get(at)?.clone(); let new_id = SymbolId(self.alloc_id()); let timeline = fresh_ids(&src.timeline, &mut || self.alloc_id()); - let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, timeline }; + let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, scale_grid: src.scale_grid, timeline }; self.library.insert(at + 1, Arc::new(copy)); if let Some(f) = self.library_tree.placed.get(&LibraryItem::Symbol(id)).copied() { Arc::make_mut(&mut self.library_tree).placed.insert(LibraryItem::Symbol(new_id), f); diff --git a/crates/doc/src/library_tests.rs b/crates/doc/src/library_tests.rs index f5a66bbe..5fefbbd1 100644 --- a/crates/doc/src/library_tests.rs +++ b/crates/doc/src/library_tests.rs @@ -19,7 +19,7 @@ fn add_symbol(d: &mut Document, name: &str, inside: &[SymbolId]) -> SymbolId { if let Some(k) = layer.keyframe_mut(0) { k.elements = els; } - d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); + d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); id } diff --git a/crates/doc/src/nine_slice.rs b/crates/doc/src/nine_slice.rs new file mode 100644 index 00000000..63947dc1 --- /dev/null +++ b/crates/doc/src/nine_slice.rs @@ -0,0 +1,78 @@ +//! 9-slice scaling of symbol instances (ADR 0055), as part of evaluation. +//! +//! A symbol with a [`ScaleGrid`] is drawn so that scaling an instance keeps the corners outside +//! its guides unscaled: the instance's transform is decomposed (`T · R · Skew · S`), and instead +//! of `S` the symbol's own shapes go through the 9-slice map of its box scaled by `S` +//! ([`anicraft_geom::slice`]); translation, rotation and skew apply after. Strokes keep their +//! width. Nested symbols, text and bitmap fills inside scale normally, as in Animate. + +use crate::{Document, ElementKind, LayerKind, ScaleGrid, Symbol}; +use anicraft_geom::slice::{Axis, Slice9}; +use anicraft_geom::{Affine, Rect}; + +/// How a sliced instance's shapes are drawn (see the module docs). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Slicing { + /// Symbol space to sliced space. + pub map: Slice9, + /// The instance's transform without its scale: sliced space to the parent's space. + pub post: Affine, + /// The scale left out of `post` (what plain scaling would have applied). + pub scale: Affine, +} + +/// Instance scale this close to 1 on both axes draws the symbol as it is. +const UNSCALED: f32 = 1e-4; + +/// The box 9-slice scaling divides: the control-point bounds of everything on the symbol's +/// keyframes (guide layers left out), so the box doesn't move as the symbol plays. Strokes don't +/// widen it: they keep their width. +pub fn symbol_box(doc: &Document, sym: &Symbol) -> Rect { + let mut r = Rect::EMPTY; + for layer in sym.timeline.layers.iter().filter(|l| !matches!(l.kind, LayerKind::Guide | LayerKind::Folder | LayerKind::Camera)) { + for k in &layer.keyframes { + for e in &k.elements { + let b = match &e.kind { + ElementKind::Shape(s) => s.path.bounds().transformed(&e.transform), + _ => e.bounds(doc), + }; + if b.min.x.is_finite() && b.max.x.is_finite() && b.min.y.is_finite() && b.max.y.is_finite() { + r = r.union(&b); + } + } + } + } + r +} + +/// The slicing of an instance of `sym` placed by `transform`, or `None` when it draws normally: +/// no guides, no scale to absorb, or nothing to divide. +pub(crate) fn slicing(doc: &Document, sym: &Symbol, transform: &Affine) -> Option { + let grid = sym.scale_grid.filter(|g| g.check().is_ok())?; + let d = transform.decompose(); + let (sx, sy) = (d.sx, d.sy.abs()); + if ((sx - 1.0).abs() < UNSCALED && (sy - 1.0).abs() < UNSCALED) || !sx.is_finite() || !sy.is_finite() { + return None; + } + let b = symbol_box(doc, sym); + if b.is_empty() { + return None; + } + map_for(&grid, &b, sx, sy).map(|map| { + // `transform` is T·R·K·S; S = scale(sx, ±sy). Keep a flip in `post` (sliced magnitudes). + let flip = if d.sy < 0.0 { -1.0 } else { 1.0 }; + let rest = anicraft_geom::Decomposed { sx: 1.0, sy: flip, ..d }.compose(); + Slicing { map, post: rest, scale: Affine::scale(sx, sy) } + }) +} + +/// The 9-slice map of box `b` with guides `grid`, scaled by `sx`, `sy` (both at least 0). An +/// axis with no extent (a symbol only a line high) scales plainly. +pub fn map_for(grid: &ScaleGrid, b: &Rect, sx: f32, sy: f32) -> Option { + let axis = |lo: f32, a: f32, c: f32, hi: f32, k: f32| if hi > lo { Axis::new(lo, a, c, hi, k) } else { Axis::new(lo, lo, lo + 1.0, lo + 1.0, k) }; + Some(Slice9 { x: axis(b.min.x, grid.left, grid.right, b.max.x, sx)?, y: axis(b.min.y, grid.top, grid.bottom, b.max.y, sy)? }) +} + +#[cfg(test)] +#[path = "nine_slice_tests.rs"] +mod tests; diff --git a/crates/doc/src/nine_slice_tests.rs b/crates/doc/src/nine_slice_tests.rs new file mode 100644 index 00000000..e9a87b47 --- /dev/null +++ b/crates/doc/src/nine_slice_tests.rs @@ -0,0 +1,173 @@ +//! 9-slice scaling (ADR 0055), analytically: what evaluation draws for a scaled instance. + +use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, ScaleGrid, Shape, Symbol, SymbolId, SymbolKind, Timeline, evaluate}; +use anicraft_geom::{Affine, Path, Vec2}; +use std::sync::Arc; + +const SYM: SymbolId = SymbolId(900); + +fn el(id: u64, transform: Affine, kind: ElementKind) -> Element { + Element { id: ElementId(id), name: String::new(), transform, color: ColorEffect::default(), kind } +} + +fn instance(of: SymbolId, transform: Affine) -> Element { + el(1, transform, ElementKind::Symbol { symbol: of, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }) +} + +/// A 100×40 rounded rectangle (corner radius 10) at the symbol's origin, guides 10 in from each +/// edge, with `extra` inside it, and one instance of it on the stage placed by `xf`. +fn doc(xf: Affine, grid: Option, extra: Vec) -> Document { + let mut d = Document::default(); + let mut shape = Shape::filled(Path::rounded_rect(0.0, 0.0, 100.0, 40.0, 10.0), Paint::Solid(Rgba::BLACK)); + shape.stroke = Some(crate::Stroke::new(Rgba::WHITE, 2.0)); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(el(2, Affine::IDENTITY, ElementKind::Shape(shape)))); + k.elements.extend(extra.into_iter().map(Arc::new)); + let mut layer = Layer::new(LayerId(901), "art"); + layer.keyframes = vec![Arc::new(k)]; + d.library.push(Arc::new(Symbol { id: SYM, name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(layer)] } })); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(instance(SYM, xf))); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k)]; + d +} + +const GRID: ScaleGrid = ScaleGrid { left: 10.0, right: 90.0, top: 10.0, bottom: 30.0 }; + +/// The stage-space outline of the first item, finely flattened. +fn outline(d: &Document) -> Vec { + let dl = evaluate(d, 0); + let it = &dl.items[0]; + it.path.flatten(&it.transform, 0.005).into_iter().flat_map(|l| l.points).collect() +} + +/// How far `p` is from the polyline `pts` (closed). +fn dist(pts: &[Vec2], p: Vec2) -> f32 { + let n = pts.len(); + (0..n).map(|i| anicraft_geom::segment_distance(p, pts[i], pts[(i + 1) % n])).fold(f32::INFINITY, f32::min) +} + +/// A point on the source corner arc of the rounded rectangle, `a` radians round the corner +/// centred at `c`. +fn arc(c: Vec2, a: f32) -> Vec2 { + c + Vec2::new(a.cos(), a.sin()) * 10.0 +} + +#[test] +fn a_rounded_rect_scaled_3x_keeps_its_corner_radii_exact() { + let d = doc(Affine::scale(3.0, 3.0), Some(GRID), Vec::new()); + let pts = outline(&d); + // The box lands where plain scaling puts it: 0..300 by 0..120. + let (lo, hi) = pts.iter().fold((Vec2::new(f32::MAX, f32::MAX), Vec2::new(f32::MIN, f32::MIN)), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))); + assert!((lo.x).abs() < 1e-3 && (lo.y).abs() < 1e-3 && (hi.x - 300.0).abs() < 1e-3 && (hi.y - 120.0).abs() < 1e-3, "{lo:?} {hi:?}"); + // Each corner is the same radius-10 arc, moved to its corner of the bigger box. + let corners = [(Vec2::new(10.0, 10.0), Vec2::ZERO, 180.0f32), (Vec2::new(90.0, 10.0), Vec2::new(200.0, 0.0), 270.0), (Vec2::new(90.0, 30.0), Vec2::new(200.0, 80.0), 0.0), (Vec2::new(10.0, 30.0), Vec2::new(0.0, 80.0), 90.0)]; + for (c, shift, from) in corners { + for i in 0..=8 { + let a = (from + i as f32 * 90.0 / 8.0).to_radians(); + let want = arc(c, a) + shift; + let d = dist(&pts, want); + assert!(d < 0.02, "corner at {c:?}, {i}/8: {d}"); + // And the arc's centre is still 10 from it: the radius is exact, not stretched. + assert!(((want - (c + shift)).length() - 10.0).abs() < 1e-3); + } + } + // Without guides, the same instance is a plain 3× scale (corners radius 30). + let plain = evaluate(&doc(Affine::scale(3.0, 3.0), None, Vec::new()), 0); + assert_eq!(plain.items[0].transform, Affine::scale(3.0, 3.0)); +} + +#[test] +fn the_centre_scales_by_the_remainder_and_edges_one_way() { + // 2× wide, 1.5× high: 200 × 60. The centre is 200 − 20 = 180 wide (80 → 180) and + // 60 − 20 = 40 high (20 → 40). + let d = doc(Affine::scale(2.0, 1.5), Some(GRID), Vec::new()); + let it = &evaluate(&d, 0).items[0]; + let map = |p: Vec2| it.transform.apply(p); + let pts = outline(&d); + // The middle of the top edge (50, 0) lands at (100, 0); of the left edge (0, 20) at (0, 30). + assert!(dist(&pts, Vec2::new(100.0, 0.0)) < 1e-3); + assert!(dist(&pts, Vec2::new(0.0, 30.0)) < 1e-3); + // The straight top edge runs from x = 10 to x = 190 (the corners are 10 each). + assert!(dist(&pts, Vec2::new(10.0, 0.0)) < 1e-3 && dist(&pts, Vec2::new(190.0, 0.0)) < 1e-3); + // The stroke keeps its width (no scale is left in the item's transform). + assert_eq!(map(Vec2::new(1.0, 0.0)) - map(Vec2::ZERO), Vec2::new(1.0, 0.0)); + assert_eq!(it.stroke.as_ref().map(|s| s.width), Some(2.0)); +} + +#[test] +fn no_spare_space_clamps_the_corners_and_closes_the_centre() { + // 0.1× wide: 10 across, less than the corners' 20. They share it (5 each) and the centre is + // a line; nothing turns inside out. + let d = doc(Affine::scale(0.1, 1.0), Some(GRID), Vec::new()); + let pts = outline(&d); + assert!(pts.iter().all(|p| p.x >= -1e-3 && p.x <= 10.0 + 1e-3), "{pts:?}"); + assert!(dist(&pts, Vec2::new(5.0, 0.0)) < 1e-3); + // Exactly no spare space (0.2× → 20 across): corners full size, the centre a line. + let pts = outline(&doc(Affine::scale(0.2, 1.0), Some(GRID), Vec::new())); + assert!(dist(&pts, arc(Vec2::new(10.0, 10.0), 225f32.to_radians())) < 0.02); + assert!(pts.iter().all(|p| p.x <= 20.0 + 1e-3)); + // Zero scale: everything on one line, still finite. + let pts = outline(&doc(Affine::scale(0.0, 1.0), Some(GRID), Vec::new())); + assert!(pts.iter().all(|p| p.x.abs() < 1e-3 && p.y.is_finite())); +} + +#[test] +fn rotation_skew_and_flips_apply_after_slicing() { + let rot = 30f32.to_radians(); + let xf = Affine::translate(400.0, 300.0).mul(&Affine::rotate(rot)).mul(&Affine::scale(3.0, 3.0)); + let d = doc(xf, Some(GRID), Vec::new()); + let it = &evaluate(&d, 0).items[0]; + // The item's transform is the instance's translation and rotation, with no scale. + let expect = Affine::translate(400.0, 300.0).mul(&Affine::rotate(rot)); + assert!(it.transform.m.iter().zip(expect.m).all(|(a, b)| (a - b).abs() < 1e-4), "{:?}", it.transform); + // The sliced corner (the top-right arc, moved by 200) turns with the instance. + let pts = outline(&d); + let want = expect.apply(arc(Vec2::new(90.0, 10.0), 315f32.to_radians()) + Vec2::new(200.0, 0.0)); + assert!(dist(&pts, want) < 0.02); + // A horizontal flip slices by the magnitude, then mirrors. + let flip = doc(Affine::scale(3.0, -3.0), Some(GRID), Vec::new()); + let it = &evaluate(&flip, 0).items[0]; + assert!((it.transform.determinant() + 1.0).abs() < 1e-4); + let pts = outline(&flip); + assert!(dist(&pts, Vec2::new(300.0, -120.0)).is_finite() && pts.iter().all(|p| p.y <= 1e-3 && p.y >= -120.0 - 1e-3)); +} + +#[test] +fn unscaled_instances_and_nested_symbols_draw_as_they_are() { + // At scale 1 nothing is cut: the symbol's own path is drawn, shared. + let d = doc(Affine::translate(5.0, 5.0), Some(GRID), Vec::new()); + let dl = evaluate(&d, 0); + let sym_path = match &d.symbol(SYM).unwrap().timeline.layers[0].keyframes[0].elements[0].kind { + ElementKind::Shape(s) => s.path.clone(), + _ => unreachable!(), + }; + assert!(Arc::ptr_eq(&dl.items[0].path, &sym_path)); + // A nested symbol inside scales normally: its item carries the whole 3× scale. + let mut d = doc(Affine::scale(3.0, 3.0), Some(GRID), vec![instance(SymbolId(950), Affine::translate(50.0, 20.0))]); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(el(3, Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::WHITE)))))); + let mut l = Layer::new(LayerId(951), "dot"); + l.keyframes = vec![Arc::new(k)]; + d.library.push(Arc::new(Symbol { id: SymbolId(950), name: "Dot".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(l)] } })); + let dl = evaluate(&d, 0); + let dot = dl.items.iter().find(|i| i.path.bounds().width() == 4.0).unwrap(); + assert_eq!(dot.transform, Affine::scale(3.0, 3.0).mul(&Affine::translate(50.0, 20.0))); +} + +#[test] +fn hostile_guides_and_scales_never_break_evaluation() { + for grid in [ + ScaleGrid { left: 90.0, right: 10.0, top: 10.0, bottom: 30.0 }, + ScaleGrid { left: f32::NAN, right: 10.0, top: 10.0, bottom: 30.0 }, + ScaleGrid { left: -1e9, right: 1e9, top: -5.0, bottom: 500.0 }, + ScaleGrid { left: 50.0, right: 50.0, top: 20.0, bottom: 20.0 }, + ] { + for xf in [Affine::scale(3.0, 3.0), Affine::scale(1e-30, 1e30), Affine::scale(f32::INFINITY, 1.0), Affine { m: [0.0, 0.0, 0.0, 0.0, 1.0, 1.0] }] { + let dl = evaluate(&doc(xf, Some(grid), Vec::new()), 0); + for it in &dl.items { + let _ = it.path.flatten(&it.transform, 0.25); + } + } + } +} diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 6720e447..88eb3845 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -33,7 +33,7 @@ fn layer(id: u64, keys: Vec>) -> Arc { } fn symbol(id: u64, kind: SymbolKind, layers: Vec>) -> Arc { - Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, timeline: Timeline { layers } }) + Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid: None, timeline: Timeline { layers } }) } fn doc(root: Vec>, library: Vec>) -> Document { diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 4633a16b..039d057e 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -53,7 +53,7 @@ pub fn demo() -> Document { .with_stroke(Rgba::hex(0x5a1410), 3.0); let ball_el = el(&mut d, "ball body", Affine::IDENTITY, ElementKind::Shape(ball_shape)); let ball_layer = layer(d.alloc_id(), "body", 0x4fa3ff, vec![key(0, 1, vec![ball_el], None)]); - d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![ball_layer] } })); + d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![ball_layer] } })); let star_id = SymbolId(d.alloc_id()); let star_shape = Shape::filled(Path::star(0.0, 0.0, 60.0, 26.0, 5), Paint::Solid(Rgba::hex(0xfff6a8))).with_stroke(Rgba::hex(0xe0a400), 2.5); @@ -67,7 +67,7 @@ pub fn demo() -> Document { }) .collect(); let star_layer = layer(d.alloc_id(), "spin", 0x4fa3ff, star_keys); - d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![star_layer] } })); + d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![star_layer] } })); // --- main timeline (index 0 = top) --------------------------------------------------- const LEN: u32 = 48; @@ -161,7 +161,7 @@ pub fn interactive() -> Document { let (up, over, down) = (face(&mut d, 0x3d8bfd), face(&mut d, 0x6aa8ff), face(&mut d, 0x2a64c0)); let hit_area = el(&mut d, "hit", Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(-120.0, -50.0, 240.0, 100.0), solid(0x000000)))); let states = layer(d.alloc_id(), "states", 0x4fa3ff, vec![key(0, 1, up, None), key(1, 1, over, None), key(2, 1, down, None), key(3, 1, vec![hit_area], None)]); - d.library.push(Arc::new(Symbol { id: button_id, name: "Play Button".into(), kind: SymbolKind::Button, linkage: None, timeline: Timeline { layers: vec![states] } })); + d.library.push(Arc::new(Symbol { id: button_id, name: "Play Button".into(), kind: SymbolKind::Button, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![states] } })); // A movie clip that spins on its own timeline. let spinner_id = SymbolId(d.alloc_id()); @@ -175,7 +175,7 @@ pub fn interactive() -> Document { }) .collect(); let spin = layer(d.alloc_id(), "spin", 0xffd54a, spin_keys); - d.library.push(Arc::new(Symbol { id: spinner_id, name: "Spinner".into(), kind: SymbolKind::MovieClip, linkage: None, timeline: Timeline { layers: vec![spin] } })); + d.library.push(Arc::new(Symbol { id: spinner_id, name: "Spinner".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![spin] } })); // Main timeline: actions on top, then the button (menu frame), the show, the backdrop. let mut menu = key(0, 1, Vec::new(), None); diff --git a/crates/doc/src/sound_tests.rs b/crates/doc/src/sound_tests.rs index 8e31c35b..ea4a2efb 100644 --- a/crates/doc/src/sound_tests.rs +++ b/crates/doc/src/sound_tests.rs @@ -194,7 +194,7 @@ fn nested(kind: SymbolKind, len: u32, inner: &[(u32, u32, Option)], // Pad the symbol's timeline to `len` frames with a second, silent layer. let mut pad = Layer::new(LayerId(11), "pad"); pad.keyframes = vec![Arc::new(Keyframe::new(0, len))]; - d.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } })); + d.library.push(Arc::new(Symbol { linkage: None, scale_grid: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } })); let mut l = Layer::new(LayerId(1), "outer"); l.keyframes = instances .iter() diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index a84fe80a..c64132e9 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -703,7 +703,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { } inner.push(Arc::new(layer)); } - s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, timeline: Timeline { layers: inner } })); + s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, scale_grid: None, timeline: Timeline { layers: inner } })); if folder.is_some() { s.doc.place_entry(LibraryEntry::Item(LibraryItem::Symbol(sym_id)), folder); } diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index 2928925e..a5078824 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -215,7 +215,7 @@ impl Session { /// at opacity `alpha` (a symbol added to `doc`, which is only drawn). fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, alpha: f32) -> Arc { let symbol = SymbolId(doc.alloc_id()); - doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, timeline })); + doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline })); let mut k = Keyframe::new(0, 1); k.elements.push(Arc::new(Element { id: ElementId(doc.alloc_id()), diff --git a/crates/engine/src/tests_bone.rs b/crates/engine/src/tests_bone.rs index d21f2a01..3f841149 100644 --- a/crates/engine/src/tests_bone.rs +++ b/crates/engine/src/tests_bone.rs @@ -31,7 +31,7 @@ pub(crate) fn three_bars() -> Session { k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) })); k }); - d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let inst = |id: u64, x: f32| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 100.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: bar, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } }); let shape = Arc::new(Element { id: ElementId(SHAPE), name: String::new(), transform: Affine::translate(100.0, 250.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::BLACK))) }); let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); diff --git a/crates/engine/src/tests_sound.rs b/crates/engine/src/tests_sound.rs index d3922655..0e11a7ec 100644 --- a/crates/engine/src/tests_sound.rs +++ b/crates/engine/src/tests_sound.rs @@ -308,7 +308,7 @@ fn sounds_inside_symbols_are_in_the_exported_soundtrack_at_their_offset_and_loop let mut k = Keyframe::new(1, 3); k.sound = Some(FrameSound::new(SoundId(id))); inner.keyframes = vec![Arc::new(Keyframe::new(0, 1)), Arc::new(k)]; - s.doc.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + s.doc.library.push(Arc::new(Symbol { linkage: None, scale_grid: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let mut k = Keyframe::new(1, 8); k.elements.push(Arc::new(Element { id: ElementId(502), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(501), loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } })); let mut outer = Layer::new(LayerId(503), "puppet"); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index e0b75dd1..1e1ccbd1 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -11,6 +11,7 @@ pub mod edit; pub mod morph; pub mod planar; pub mod raw; +pub mod slice; mod fit; mod path; pub mod svg; diff --git a/crates/geom/src/slice.rs b/crates/geom/src/slice.rs new file mode 100644 index 00000000..8fdd881f --- /dev/null +++ b/crates/geom/src/slice.rs @@ -0,0 +1,430 @@ +//! 9-slice scaling (ADR 0055): a box cut by four guides into corners, edges and a centre, scaled +//! so the corners keep their size, the edges stretch one way and the centre both ways. +//! +//! The map is separable: each axis is three linear pieces ([`Axis`]). Within one of the nine +//! cells it is affine, so a Bézier piece that stays in one cell maps exactly by mapping its +//! control points. [`slice_path`] cuts every segment where it crosses a guide (de Casteljau at the +//! exact crossing parameters) and maps each piece with its cell's affine; at a guide both cells +//! agree, so the result stays connected. + +use crate::{Affine, Path, PathCmd, Vec2}; + +/// One axis of a 9-slice map: the source stops `[lo, a, b, hi]` (the box's edges and the two +/// guides) and where they land. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Axis { + from: [f32; 4], + to: [f32; 4], +} + +impl Axis { + /// The axis of a box `lo..hi` with guides at `a` and `b`, scaled by `k` (at least 0) about the + /// origin: the box lands where plain scaling puts it (`k·lo..k·hi`), the parts outside the + /// guides keep their size and the centre takes the rest. When the rest would be negative the + /// two outer parts share what there is, in proportion, and the centre closes. + /// + /// Guides outside the box are clamped into it (and `b` to at least `a`). `None` for an empty + /// box, a negative scale or anything not finite. + pub fn new(lo: f32, a: f32, b: f32, hi: f32, k: f32) -> Option { + if ![lo, a, b, hi, k].iter().all(|v| v.is_finite()) || hi <= lo || k < 0.0 { + return None; + } + let a = a.clamp(lo, hi); + let b = b.clamp(a, hi); + let (near, far) = (a - lo, hi - b); + let (tlo, thi) = (k * lo, k * hi); + let room = thi - tlo; + let edges = near + far; + let (near, far) = if edges > room && edges > 0.0 { (near * room / edges, far * room / edges) } else { (near, far) }; + let to = [tlo, tlo + near, thi - far, thi]; + to.iter().all(|v| v.is_finite()).then_some(Axis { from: [lo, a, b, hi], to }) + } + + /// The identity map on `lo..hi` (what an unscaled axis is). + pub fn identity(lo: f32, hi: f32) -> Axis { + Axis { from: [lo, lo, hi, hi], to: [lo, lo, hi, hi] } + } + + /// The two guides, in source space. + pub fn guides(&self) -> [f32; 2] { + [self.from[1], self.from[2]] + } + + /// Which piece `v` is in: 0 before the first guide, 1 between them, 2 after the second. + pub fn piece(&self, v: f32) -> usize { + if v < self.from[1] { + 0 + } else if v <= self.from[2] { + 1 + } else { + 2 + } + } + + /// Piece `i` as `v ↦ scale · v + offset`. The outer pieces carry on past the box's edges + /// with their own slope; a piece of no width has the slope of plain scaling (nothing lies in + /// it but its edge, which maps right either way). + pub fn linear(&self, i: usize) -> (f32, f32) { + let i = i.min(2); + let (f0, f1) = (self.from[i], self.from[i + 1]); + let (t0, t1) = (self.to[i], self.to[i + 1]); + let whole = (self.to[3] - self.to[0]) / (self.from[3] - self.from[0]).max(f32::MIN_POSITIVE); + let scale = if f1 - f0 > 1e-6 { (t1 - t0) / (f1 - f0) } else { whole }; + // Anchored where the piece starts (the outer ones at their guide, so they meet the centre). + let (anchor, at) = if i == 0 { (f1, t1) } else { (f0, t0) }; + (scale, at - scale * anchor) + } + + /// Where `v` lands. + pub fn map(&self, v: f32) -> f32 { + let (s, o) = self.linear(self.piece(v)); + s * v + o + } +} + +/// A whole 9-slice map: the horizontal and the vertical axis. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Slice9 { + pub x: Axis, + pub y: Axis, +} + +impl Slice9 { + pub fn map(&self, p: Vec2) -> Vec2 { + Vec2::new(self.x.map(p.x), self.y.map(p.y)) + } + + /// The affine map of the cell `(ix, iy)`. + pub fn cell(&self, ix: usize, iy: usize) -> Affine { + let (sx, ox) = self.x.linear(ix); + let (sy, oy) = self.y.linear(iy); + Affine { m: [sx, 0.0, 0.0, sy, ox, oy] } + } + + /// The cell a point is in. + fn cell_of(&self, p: Vec2) -> Affine { + self.cell(self.x.piece(p.x), self.y.piece(p.y)) + } +} + +/// Largest number of commands [`slice_path`] writes (a path that would grow past it is mapped +/// point by point instead, which is exact for straight edges and close for curves). +pub const MAX_SLICED_CMDS: usize = 4_000_000; + +/// `path` placed by `pre` (its own space to the box's) and then sliced by `map`: every segment cut +/// where it crosses a guide, each piece mapped by its cell's affine. Straight edges stay straight +/// within a cell, curves stay curves, fill areas stay closed (an implied closing line is drawn +/// out, since it may cross a guide). +pub fn slice_path(path: &Path, pre: &Affine, map: &Slice9) -> Path { + if path.cmds.len().saturating_mul(4) > MAX_SLICED_CMDS { + return path.transformed(pre).transformed_by(|p| map.map(p)); + } + let gx = map.x.guides(); + let gy = map.y.guides(); + let mut out = Vec::with_capacity(path.cmds.len() + 8); + let mut cur = Vec2::ZERO; + let mut start = Vec2::ZERO; + let mut ts: Vec = Vec::with_capacity(16); + for c in &path.cmds { + match *c { + PathCmd::MoveTo(p) => { + let p = pre.apply(p); + out.push(PathCmd::MoveTo(map.map(p))); + cur = p; + start = p; + } + PathCmd::LineTo(p) => { + let p = pre.apply(p); + pieces(&[cur, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::QuadTo(a, p) => { + let (a, p) = (pre.apply(a), pre.apply(p)); + pieces(&[cur, a, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::CubicTo(a, b, p) => { + let (a, b, p) = (pre.apply(a), pre.apply(b), pre.apply(p)); + pieces(&[cur, a, b, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::Close => { + if cur != start { + pieces(&[cur, start], &gx, &gy, map, &mut ts, &mut out); + } + out.push(PathCmd::Close); + cur = start; + } + } + } + Path { cmds: out } +} + +/// Writes segment `ctrl` (2, 3 or 4 control points: a line, a quadratic or a cubic) as its pieces +/// between guide crossings, each mapped by its cell. +fn pieces(ctrl: &[Vec2], gx: &[f32; 2], gy: &[f32; 2], map: &Slice9, ts: &mut Vec, out: &mut Vec) { + ts.clear(); + let xs: Vec = ctrl.iter().map(|p| p.x).collect(); + let ys: Vec = ctrl.iter().map(|p| p.y).collect(); + for g in gx { + crossings(&xs, *g, ts); + } + for g in gy { + crossings(&ys, *g, ts); + } + ts.sort_by(f32::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut t0 = 0.0; + for &t1 in ts.iter().chain(std::iter::once(&1.0)) { + if t1 - t0 < 1e-6 { + continue; + } + let part = sub(ctrl, t0, t1); + let mid = eval(ctrl, (t0 + t1) * 0.5); + let m = map.cell_of(mid); + push(&part, &m, out); + t0 = t1; + } +} + +fn push(part: &[Vec2], m: &Affine, out: &mut Vec) { + match *part { + [_, p] => out.push(PathCmd::LineTo(m.apply(p))), + [_, a, p] => out.push(PathCmd::QuadTo(m.apply(a), m.apply(p))), + [_, a, b, p] => out.push(PathCmd::CubicTo(m.apply(a), m.apply(b), m.apply(p))), + _ => {} + } +} + +/// The point at `t` (de Casteljau). +fn eval(ctrl: &[Vec2], t: f32) -> Vec2 { + let mut p = [Vec2::ZERO; 4]; + let n = ctrl.len().min(4); + p[..n].copy_from_slice(&ctrl[..n]); + for k in (1..n).rev() { + for i in 0..k { + p[i] = p[i].lerp(p[i + 1], t); + } + } + p[0] +} + +/// The piece of the curve between `t0` and `t1`, as control points of the same degree. +fn sub(ctrl: &[Vec2], t0: f32, t1: f32) -> Vec { + // Split at t1, keep the first part; then split that at t0 / t1, keep the second. + let first = split(ctrl, t1).0; + if t0 <= 0.0 { + return first; + } + let u = if t1 > 1e-12 { t0 / t1 } else { 0.0 }; + split(&first, u).1 +} + +/// De Casteljau split at `t`: the two halves. +fn split(ctrl: &[Vec2], t: f32) -> (Vec, Vec) { + // Each level is one point shorter: the first and last points of every level are the halves'. + let n = ctrl.len().min(4); + let mut work = [Vec2::ZERO; 4]; + work[..n].copy_from_slice(&ctrl[..n]); + let mut left = Vec::with_capacity(n); + let mut right = Vec::with_capacity(n); + for k in (0..n).rev() { + left.push(work[0]); + right.push(work[k]); + for i in 0..k { + work[i] = work[i].lerp(work[i + 1], t); + } + } + right.reverse(); + (left, right) +} + +/// Adds every `t` in (0, 1) where the 1-D Bézier `c` (2 to 4 coefficients) equals `v`: the curve +/// is cut where its derivative is zero into monotone runs, and each run that crosses `v` is +/// bisected. Exact to `f32`, at most three crossings per guide. +fn crossings(c: &[f32], v: f32, ts: &mut Vec) { + let f = |t: f32| bez1(c, t) - v; + let mut stops = [0.0f32; 4]; + let mut n = 0; + stops[n] = 0.0; + n += 1; + if let [x0, x1, x2, x3] = *c { + // Derivative (a quadratic) in power form: A t² + B t + C. + let (q0, q1, q2) = (3.0 * (x1 - x0), 3.0 * (x2 - x1), 3.0 * (x3 - x2)); + let (a, b, cc) = (q0 - 2.0 * q1 + q2, 2.0 * (q1 - q0), q0); + let mut roots = [f32::NAN; 2]; + if a.abs() > 1e-12 { + let disc = b * b - 4.0 * a * cc; + if disc >= 0.0 { + let s = disc.sqrt(); + roots = [(-b - s) / (2.0 * a), (-b + s) / (2.0 * a)]; + } + } else if b.abs() > 1e-12 { + roots[0] = -cc / b; + } + roots.sort_by(f32::total_cmp); + for r in roots { + if r > 0.0 && r < 1.0 && n < 3 { + stops[n] = r; + n += 1; + } + } + } else if let [x0, x1, x2] = *c { + let den = x0 - 2.0 * x1 + x2; + if den.abs() > 1e-12 { + let r = (x0 - x1) / den; + if r > 0.0 && r < 1.0 { + stops[n] = r; + n += 1; + } + } + } + stops[n] = 1.0; + n += 1; + for w in stops[..n].windows(2) { + let (mut lo, mut hi) = (w[0], w[1]); + let (flo, fhi) = (f(lo), f(hi)); + if !(flo.is_finite() && fhi.is_finite()) || flo == 0.0 || fhi == 0.0 || (flo > 0.0) == (fhi > 0.0) { + continue; + } + let rising = fhi > flo; + for _ in 0..40 { + let mid = 0.5 * (lo + hi); + if (f(mid) > 0.0) == rising { + hi = mid; + } else { + lo = mid; + } + } + let t = 0.5 * (lo + hi); + if t > 1e-6 && t < 1.0 - 1e-6 { + ts.push(t); + } + } +} + +fn bez1(c: &[f32], t: f32) -> f32 { + let u = 1.0 - t; + match *c { + [a, b] => u * a + t * b, + [a, b, d] => u * u * a + 2.0 * u * t * b + t * t * d, + [a, b, d, e] => u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * d + t * t * t * e, + _ => 0.0, + } +} + +impl Path { + /// Every point mapped by `f` (any map, not only an affine one). + pub fn transformed_by(&self, f: impl Fn(Vec2) -> Vec2) -> Path { + Path { + cmds: self + .cmds + .iter() + .map(|c| match *c { + PathCmd::MoveTo(p) => PathCmd::MoveTo(f(p)), + PathCmd::LineTo(p) => PathCmd::LineTo(f(p)), + PathCmd::QuadTo(a, p) => PathCmd::QuadTo(f(a), f(p)), + PathCmd::CubicTo(a, b, p) => PathCmd::CubicTo(f(a), f(b), f(p)), + PathCmd::Close => PathCmd::Close, + }) + .collect(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-3 + } + + #[test] + fn an_axis_keeps_its_ends_and_gives_the_centre_the_rest() { + // A 100-wide box, 10 and 10 outside the guides, scaled 3x: 300 wide, 280 in the centre. + let ax = Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(); + assert!(close(ax.map(0.0), 0.0)); + assert!(close(ax.map(10.0), 10.0)); + assert!(close(ax.map(90.0), 290.0)); + assert!(close(ax.map(100.0), 300.0)); + assert!(close(ax.map(50.0), 150.0), "the centre scales by 280 / 80"); + // About the origin, as plain scaling: a box from -50 lands on -150..150. + let ax = Axis::new(-50.0, -40.0, 40.0, 50.0, 3.0).unwrap(); + assert!(close(ax.map(-50.0), -150.0) && close(ax.map(-40.0), -140.0) && close(ax.map(50.0), 150.0)); + } + + #[test] + fn no_spare_space_shares_what_there_is_and_closes_the_centre() { + // Corners 10 + 30 = 40 of a 100 box, scaled to 20: they shrink to 5 and 15. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.2).unwrap(); + assert!(close(ax.map(10.0), 5.0) && close(ax.map(70.0), 5.0) && close(ax.map(100.0), 20.0)); + // Exactly no spare space: the centre is a line. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.4).unwrap(); + assert!(close(ax.map(10.0), 10.0) && close(ax.map(70.0), 10.0) && close(ax.map(100.0), 40.0)); + // Zero scale: everything at the origin. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.0).unwrap(); + assert!(close(ax.map(0.0), 0.0) && close(ax.map(100.0), 0.0)); + // Guides outside or crossed are clamped; bad numbers give nothing. + let ax = Axis::new(0.0, -20.0, 140.0, 100.0, 2.0).unwrap(); + assert!(close(ax.map(50.0), 100.0)); + assert!(Axis::new(0.0, 10.0, 90.0, 0.0, 2.0).is_none()); + assert!(Axis::new(0.0, 10.0, 90.0, 100.0, -1.0).is_none()); + assert!(Axis::new(0.0, f32::NAN, 90.0, 100.0, 1.0).is_none()); + } + + #[test] + fn a_line_across_the_guides_is_cut_there() { + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(), y: Axis::new(0.0, 10.0, 30.0, 40.0, 1.0).unwrap() }; + let p = slice_path(&Path::line(Vec2::new(0.0, 20.0), Vec2::new(100.0, 20.0)), &Affine::IDENTITY, &map); + let pts: Vec = p + .cmds + .iter() + .filter_map(|c| match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => Some(p), + _ => None, + }) + .collect(); + assert_eq!(pts.len(), 4); + for (got, want) in pts.iter().zip([0.0, 10.0, 290.0, 300.0]) { + assert!(close(got.x, want) && close(got.y, 20.0), "{got:?} vs {want}"); + } + } + + #[test] + fn a_closing_line_is_drawn_out_so_it_bends_at_the_guides() { + // A triangle whose closing edge runs diagonally across the left guide. + let mut p = Path::default(); + p.cmds = vec![PathCmd::MoveTo(Vec2::new(0.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 40.0)), PathCmd::Close]; + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(), y: Axis::identity(0.0, 40.0) }; + let s = slice_path(&p, &Affine::IDENTITY, &map); + assert_eq!(s.cmds.last(), Some(&PathCmd::Close)); + // Every vertex of the result is the map of a point on the source outline. + assert!(s.cmds.len() > p.cmds.len() + 2); + } + + #[test] + fn curves_are_cut_at_exact_crossings_and_stay_on_the_mapped_curve() { + let c = [Vec2::new(0.0, 0.0), Vec2::new(30.0, 60.0), Vec2::new(70.0, -20.0), Vec2::new(100.0, 40.0)]; + let mut p = Path::default(); + p.cmds = vec![PathCmd::MoveTo(c[0]), PathCmd::CubicTo(c[1], c[2], c[3])]; + let map = Slice9 { x: Axis::new(0.0, 25.0, 75.0, 100.0, 2.5).unwrap(), y: Axis::new(-20.0, 0.0, 20.0, 60.0, 1.5).unwrap() }; + let s = slice_path(&p, &Affine::IDENTITY, &map); + // Sample the source curve; each sample's image must lie on the sliced path (within + // flattening tolerance): the piecewise-affine image of a Bézier is the pieces' Béziers. + let flat: Vec = s.flatten(&Affine::IDENTITY, 0.01).into_iter().flat_map(|l| l.points).collect(); + for i in 0..=50 { + let q = map.map(eval(&c, i as f32 / 50.0)); + let d = flat.windows(2).map(|w| crate::segment_distance(q, w[0], w[1])).fold(f32::INFINITY, f32::min); + assert!(d < 0.1, "sample {i}: {d}"); + } + } + + #[test] + fn the_pre_transform_places_the_path_first() { + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 2.0).unwrap(), y: Axis::identity(0.0, 10.0) }; + let s = slice_path(&Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), &Affine::translate(90.0, 0.0), &map); + assert_eq!(s.cmds.first(), Some(&PathCmd::MoveTo(Vec2::new(190.0, 0.0)))); + assert!(matches!(s.cmds.last(), Some(PathCmd::LineTo(p)) if close(p.x, 200.0))); + } +} diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 84b22ce7..8bfba887 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -36,7 +36,7 @@ fn layer(id: u64, keys: Vec>) -> Arc { } fn symbol(id: u64, kind: SymbolKind, layers: Vec>) -> Arc { - Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, timeline: Timeline { layers } }) + Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid: None, timeline: Timeline { layers } }) } fn this() -> Target { @@ -447,7 +447,7 @@ fn frames_are_baked_and_stored_once() { assert!(m.stats.paths < 40, "{:?}", m.stats); // Unused library symbols stay out. let mut d = doc.clone(); - d.library.push(Arc::new(Symbol { id: SymbolId(999_999), name: "unused".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline::default() })); + d.library.push(Arc::new(Symbol { id: SymbolId(999_999), name: "unused".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline::default() })); assert_eq!(movie(&d, &HtmlOptions::default()).json["symbols"], m.json["symbols"]); } @@ -582,8 +582,8 @@ fn sounds_carry_their_envelopes_and_volumes_and_start_in_graphics_and_clips_as_i let inst = |id, symbol| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } }); // A graphic with a fading sound on its frame 1 (of 2), a clip with a left-channel one on its // frame 0 (of 3), both on a layer at half volume; a sound of the main timeline's own. - doc.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(20), name: "g".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![layer(21, vec![key(0, 1, None, vec![]), key(1, 1, snd(SoundSync::Event, SoundEffect::FadeOut), vec![])], 1.0)] } })); - doc.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(30), name: "c".into(), kind: SymbolKind::MovieClip, timeline: Timeline { layers: vec![layer(31, vec![key(0, 3, snd(SoundSync::Stream, SoundEffect::LeftChannel), vec![])], 0.5)] } })); + doc.library.push(Arc::new(Symbol { linkage: None, scale_grid: None, id: SymbolId(20), name: "g".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![layer(21, vec![key(0, 1, None, vec![]), key(1, 1, snd(SoundSync::Event, SoundEffect::FadeOut), vec![])], 1.0)] } })); + doc.library.push(Arc::new(Symbol { linkage: None, scale_grid: None, id: SymbolId(30), name: "c".into(), kind: SymbolKind::MovieClip, timeline: Timeline { layers: vec![layer(31, vec![key(0, 3, snd(SoundSync::Stream, SoundEffect::LeftChannel), vec![])], 0.5)] } })); doc.timeline_mut(0).layers = vec![layer(1, vec![key(0, 6, snd(SoundSync::Event, SoundEffect::None), vec![])], 1.0), layer(2, vec![key(0, 6, None, vec![inst(40, 20), inst(41, 30)])], 0.5)]; let m = movie(&doc, &HtmlOptions::default()); // The fade's points span one play (half a second); the clip's span its 3 frames. diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index a0dbe1bd..4a93644d 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -22,7 +22,7 @@ use crate::edges::{self, Edge}; use crate::xml::{self, Element as X}; use anicraft_doc::{ Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, - Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, Language, Linkage, SourceScript, + Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, Language, Linkage, ScaleGrid, SourceScript, }; use anicraft_geom::{Affine, FillRule, Path, Vec2}; use anicraft_text::{FaceMatch, Fonts}; @@ -769,6 +769,31 @@ impl<'a> Builder<'a> { Some(l) } + /// A symbol's 9-slice guides (ADR 0055): `scaleGridLeft`, `scaleGridRight`, `scaleGridTop` + /// and `scaleGridBottom` on the `DOMSymbolItem`, in the symbol's space, written when its + /// guides are on. All four or none; guides given the wrong way round are put in order. + fn scale_grid(&mut self, item: &X) -> Option { + let keys = ["scaleGridLeft", "scaleGridRight", "scaleGridTop", "scaleGridBottom"]; + if keys.iter().all(|k| item.attr(k).is_none()) { + return None; + } + let v: Vec = keys.iter().filter_map(|k| item.f32(k)).collect(); + let grid = match v[..] { + [l, r, t, b] => Some(ScaleGrid { left: l.min(r), right: l.max(r), top: t.min(b), bottom: t.max(b) }), + _ => None, + }; + match grid.filter(|g| g.check().is_ok()) { + Some(g) => { + self.report.keep("9-slice scaling guides"); + Some(g) + } + None => { + self.report.skip("9-slice guides that aren't numbers (left out)"); + None + } + } + } + /// The script settings of the package's publish profile (`PublishSettings.xml`): the /// language its frame scripts are written in (`ActionScriptVersion`; 3 when the file /// doesn't say) and the document class (`DocumentClass`). The profile marked current is @@ -803,7 +828,8 @@ impl<'a> Builder<'a> { None => Timeline { layers: vec![Arc::new(Layer::new(LayerId(self.doc.alloc_id()), "Layer 1"))] }, }; let short = name.rsplit('/').next().unwrap_or(&name).to_string(); - self.doc.library.push(Arc::new(Symbol { id, name: short, kind, linkage, timeline })); + let scale_grid = self.scale_grid(&item); + self.doc.library.push(Arc::new(Symbol { id, name: short, kind, linkage, scale_grid, timeline })); self.place_in_folder(&name, anicraft_doc::LibraryItem::Symbol(id)); } } From 3fba4f742f7c0b2f7fe325afa8d431706897f7fe Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:13:48 -0700 Subject: [PATCH 010/192] feat(engine): symbol.set_scale_grid turns 9-slice guides on, off and moves them (M2) --- crates/engine/src/cmds_draw.rs | 66 +++++++++++- crates/engine/src/lib.rs | 2 + crates/engine/src/scale_grid_tests.rs | 141 ++++++++++++++++++++++++++ crates/engine/src/tests.rs | 6 ++ 4 files changed, 214 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/scale_grid_tests.rs diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index c64132e9..d6ef936a 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -2,7 +2,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Selection, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, ScaleGrid, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Decomposed, Path, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -34,6 +34,15 @@ pub fn specs() -> Vec { c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))), c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))), c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the symbols of every selected instance)}", true, set_symbol_kind), + c( + "symbol.set_scale_grid", + "9-Slice Scaling", + "", + None, + "{symbol?: id (default: the symbol open for editing, else the selected instance's), on?: bool, left?, right?, top?, bottom? (guide positions in the symbol's space)} turns a symbol's guides for 9-slice scaling on or off, or moves them (ADR 0055). Turning them on puts them a quarter of the way in from each edge of the symbol's artwork; moving one turns them on. Scaled instances then keep the corners outside the guides unscaled, stretch the edges one way and the centre both ways → {symbol, scale_grid: {left, right, top, bottom} | null}", + true, + set_scale_grid, + ), c("element.rename", "Instance Name", "", None, "{name}", true, |s, p| s.each_layer(true, |s| rename(s, p))), c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, true))), c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, true))), @@ -555,6 +564,61 @@ fn set_symbol_kind(s: &mut Session, p: &Value) -> Result { Ok(json!({"symbol": ids.first().map(|i| i.0), "symbols": ids.iter().map(|i| i.0).collect::>(), "kind": format!("{kind:?}")})) } +/// The symbol a command means: `symbol`, else the selected instance's. +fn selected_symbol(s: &Session, p: &Value) -> Result { + Ok(match opt_u64(p, "symbol")? { + Some(id) => SymbolId(id), + None => { + // The symbol of the selected instance. + let (layer, sel) = s.selection.first().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?; + s.elements_on(layer) + .iter() + .find(|e| e.id == sel) + .and_then(|e| match e.kind { + ElementKind::Symbol { symbol, .. } => Some(symbol), + ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera => None, + }) + .ok_or_else(|| EngineError::State("the selection is not a symbol instance".into()))? + } + }) +} + +/// 9-slice guides (ADR 0055): on, off or moved, on one symbol. +fn set_scale_grid(s: &mut Session, p: &Value) -> Result { + let on = opt_bool(p, "on")?; + let edges = [opt_f32(p, "left")?, opt_f32(p, "right")?, opt_f32(p, "top")?, opt_f32(p, "bottom")?]; + if on.is_none() && edges.iter().all(Option::is_none) { + return Err(EngineError::Param("pass 'on', or a guide to move: 'left', 'right', 'top' or 'bottom'".into())); + } + // The open symbol is the one being edited; otherwise the selected instance's. + let id = match (opt_u64(p, "symbol")?, s.editing_symbol()) { + (None, Some(open)) => open, + _ => selected_symbol(s, p)?, + }; + let sym = s.doc.symbol(id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + let grid = if on == Some(false) { + if edges.iter().any(Option::is_some) { + return Err(EngineError::Param("guides can't be moved while turning them off".into())); + } + None + } else { + let start = sym.scale_grid.unwrap_or_else(|| { + let b = anicraft_doc::symbol_box(&s.doc, sym); + ScaleGrid::inset(&if b.is_empty() { anicraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0) } else { b }) + }); + let [l, r, t, b] = edges; + let g = ScaleGrid { left: l.unwrap_or(start.left), right: r.unwrap_or(start.right), top: t.unwrap_or(start.top), bottom: b.unwrap_or(start.bottom) }; + g.check().map_err(EngineError::Param)?; + Some(g) + }; + if let Some(sym) = s.doc.library.iter_mut().find(|x| x.id == id) + && sym.scale_grid != grid + { + Arc::make_mut(sym).scale_grid = grid; + } + Ok(json!({"symbol": id.0, "scale_grid": grid.map(|g| json!({"left": g.left, "right": g.right, "top": g.top, "bottom": g.bottom}))})) +} + fn rename(s: &mut Session, p: &Value) -> Result { let name: String = str_req(p, "name")?.chars().take(128).collect(); for e in s.selected_elements_mut()? { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a6972fe4..17e44ea9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -958,3 +958,5 @@ mod erase_tests; mod eyedropper_tests; #[cfg(test)] mod selection_tests; +#[cfg(test)] +mod scale_grid_tests; diff --git a/crates/engine/src/scale_grid_tests.rs b/crates/engine/src/scale_grid_tests.rs new file mode 100644 index 00000000..14a25453 --- /dev/null +++ b/crates/engine/src/scale_grid_tests.rs @@ -0,0 +1,141 @@ +//! 9-slice scaling end to end (ADR 0055): the command, undo, the file format, plug-ins and what +//! a scaled instance renders. + +use crate::Session; +use anicraft_doc::{ScaleGrid, SymbolId}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +/// A 100 × 40 rounded drawing object turned into a symbol (its space runs from (−50, −20) to +/// (50, 20)), its instance selected. +fn panel() -> (Session, SymbolId) { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 40, "radius": 10, "fill": "#3366cc", "stroke": "#000000", "stroke_width": 2})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Panel"})); + (s, SymbolId(v["symbol"].as_u64().unwrap())) +} + +fn grid(s: &Session, id: SymbolId) -> Option { + s.doc.symbol(id).and_then(|x| x.scale_grid) +} + +#[test] +fn turning_guides_on_puts_them_a_quarter_in_and_moving_one_keeps_the_rest() { + let (mut s, id) = panel(); + let v = run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert_eq!(v["symbol"], json!(id.0)); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -25.0, right: 25.0, top: -10.0, bottom: 10.0 })); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + run(&mut s, "symbol.set_scale_grid", json!({"top": -12})); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -40.0, right: 40.0, top: -12.0, bottom: 10.0 })); + // Off forgets them (as in Animate, turning them on again starts from the artwork). + let v = run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + assert_eq!(v["scale_grid"], Value::Null); + assert_eq!(grid(&s, id), None); + // Moving a guide turns them on. + run(&mut s, "symbol.set_scale_grid", json!({"symbol": id.0, "left": -45})); + assert_eq!(grid(&s, id).map(|g| g.left), Some(-45.0)); +} + +#[test] +fn bad_guides_are_refused_and_change_nothing() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + let before = grid(&s, id); + assert!(err(&mut s, "symbol.set_scale_grid", json!({"left": 30})).contains("left"), "past the right guide"); + assert!(err(&mut s, "symbol.set_scale_grid", json!({"bottom": -20})).contains("top")); + err(&mut s, "symbol.set_scale_grid", json!({"left": 1e30})); + err(&mut s, "symbol.set_scale_grid", json!({})); + err(&mut s, "symbol.set_scale_grid", json!({"on": false, "left": 1})); + err(&mut s, "symbol.set_scale_grid", json!({"on": true, "symbol": 999_999})); + assert_eq!(grid(&s, id), before); + // With nothing selected and no symbol open there is nothing to set it on. + run(&mut s, "edit.deselect", json!({})); + err(&mut s, "symbol.set_scale_grid", json!({"on": true})); +} + +#[test] +fn each_change_is_one_undo_step_and_a_drag_of_moves_is_one_too() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert_eq!(s.undo_label(), Some("9-Slice Scaling")); + // A guide dragged: many moves, one step. + s.begin_gesture("Move 9-Slice Guide"); + for x in [-26, -30, -35, -38] { + run(&mut s, "symbol.set_scale_grid", json!({"left": x})); + } + s.end_gesture(); + assert_eq!(grid(&s, id).map(|g| g.left), Some(-38.0)); + s.undo().unwrap(); + assert_eq!(grid(&s, id).map(|g| g.left), Some(-25.0)); + s.undo().unwrap(); + assert_eq!(grid(&s, id), None); + s.redo().unwrap(); + assert!(grid(&s, id).is_some()); +} + +#[test] +fn inside_the_open_symbol_it_needs_no_selection() { + let (mut s, id) = panel(); + run(&mut s, "symbol.edit", json!({})); + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert!(grid(&s, id).is_some()); +} + +#[test] +fn the_guides_survive_the_file_and_older_files_open_without_them() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(text.contains("\"scale_grid\"")); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back.symbol(id).and_then(|x| x.scale_grid), grid(&s, id)); + // A symbol without guides writes nothing for them, so older files read the same. + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(!text.contains("scale_grid")); + assert_eq!(crate::format::from_json(&text).unwrap().symbol(id).and_then(|x| x.scale_grid), None); + // Unusable guides in a file are dropped, not drawn. + let mut doc = s.doc.clone(); + if let Some(sym) = doc.library.first_mut() { + std::sync::Arc::make_mut(sym).scale_grid = Some(ScaleGrid { left: 9.0, right: -9.0, top: 0.0, bottom: 1.0 }); + } + let text = crate::format::to_json(&doc).unwrap(); + assert_eq!(crate::format::from_json(&text).unwrap().symbol(id).and_then(|x| x.scale_grid), None); +} + +#[test] +fn a_scaled_instance_renders_with_unscaled_corners() { + // The CPU renderer (the oracle) draws the sliced instance: at 3× wide its top-left corner + // pixels match the unscaled instance's, while plain scaling stretches them. + let (mut s, _) = panel(); + s.doc.stage = anicraft_doc::Stage { width: 400, height: 200, ..s.doc.stage }; + let corner = |s: &Session| { + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + // The instance's top-left corner is at (100, 100): the 12 × 12 pixels there. + (0..12u32).flat_map(|y| (0..12u32).map(move |x| (x, y))).map(|(x, y)| format!("{:?}", img.pixel(100 + x, 100 + y))).collect::>() + }; + let at_one = corner(&s); + // Scale about the left edge: 3× wide. + run(&mut s, "modify.transform", json!({"a": 3, "b": 0, "c": 0, "d": 1, "e": -200, "f": 0})); + let plain = corner(&s); + assert_ne!(plain, at_one, "plain scaling stretches the corner"); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + assert_eq!(corner(&s), at_one, "9-slice keeps it"); +} + +#[test] +fn plug_ins_may_set_guides() { + assert!(crate::cmds_plugin::plugin_may_call("symbol.set_scale_grid").is_ok()); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e1d514c7..0143d66c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -632,6 +632,12 @@ fn panic_hunt_every_command() { json!({"first": 0, "last": 50, "scale_x": -1, "pivot": [0, 0], "edge": "vcenter", "to_stage": true, "merge": false}), json!({"first": 3, "last": 1, "edge": "right", "layer": u64::MAX, "items": [[0, 0, 0]]}), json!({"first": 0, "last": 99_999, "layer": 0, "items": (0..200).map(|i| json!([i, i, i])).collect::>()}), + // 9-slice guides (ADR 0055): crossed, huge, not numbers, moved while turned off. + json!({"on": true, "left": 90, "right": 10, "top": 1e30, "bottom": -1e30, "symbol": 1}), + json!({"on": false, "left": 5}), + json!({"on": "x", "left": f64::NAN, "right": "y", "top": null}), + json!({"left": -1e7, "right": 1e7, "top": -1e7, "bottom": 1e7}), + json!({"on": true, "symbol": u64::MAX}), ]; // File commands are exercised separately (they touch the disk). let skip = |id: &str| id.starts_with("file."); From 9644061d098d8a05746c5aa980bcd35f716d4565 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:15:55 -0700 Subject: [PATCH 011/192] test(xfl): a 9-slice corpus package with goldens and probes (M2) --- crates/engine/tests/xfl_corpus.rs | 9 ++++ crates/xfl/src/import.rs | 13 ++---- crates/xfl/tests/corpus.rs | 13 +++++- .../tests/corpus/nineslice/DOMDocument.xml | 42 ++++++++++++++++++ .../corpus/nineslice/LIBRARY/Ui/Half.xml | 22 +++++++++ .../corpus/nineslice/LIBRARY/Ui/Panel.xml | 35 +++++++++++++++ .../tests/corpus/nineslice/LIBRARY/Ui/Pip.xml | 21 +++++++++ .../corpus/nineslice/golden/frame-000.png | Bin 0 -> 4022 bytes .../xfl/tests/corpus/nineslice/nineslice.xfl | 1 + 9 files changed, 146 insertions(+), 10 deletions(-) create mode 100644 crates/xfl/tests/corpus/nineslice/DOMDocument.xml create mode 100644 crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Half.xml create mode 100644 crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Panel.xml create mode 100644 crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Pip.xml create mode 100644 crates/xfl/tests/corpus/nineslice/golden/frame-000.png create mode 100644 crates/xfl/tests/corpus/nineslice/nineslice.xfl diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index f24fc0e8..3322ac32 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -34,6 +34,7 @@ const FRAMES: &[(&str, &[u32])] = &[ ("guides", &[0, 6, 12]), ("interactive", &[0, 9]), ("masks", &[0]), + ("nineslice", &[0]), ("primitives", &[0]), ("scenes", &[0, 3, 7, 8, 10]), ("scripts", &[0, 4]), @@ -84,6 +85,14 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("masks", 0, 10.0, 22.0, 0xFFFFFF), ("masks", 0, 145.0, 10.0, 0xFFFFFF), ("masks", 0, 270.0, 70.0, 0xCB997E), + // 9-slice (ADR 0055): the stretched panel's top-left corner keeps its radius-10 curve (plain + // scaling would leave the background there), its middle is the panel, and the graphic inside + // it scales normally (a dot 2.8 times as wide). + ("nineslice", 0, 27.0, 113.0, 0x2A9D8F), + ("nineslice", 0, 137.0, 13.0, 0x2A9D8F), + ("nineslice", 0, 100.0, 125.0, 0x2A9D8F), + ("nineslice", 0, 151.0, 130.0, 0xE9C46A), + ("nineslice", 0, 21.0, 111.0, 0xF1FAEE), // Guide artwork never draws. ("guides", 0, 5.0, 5.0, 0xFFFFFF), ("guides", 0, 160.0, 60.0, 0xFFFFFF), diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 4a93644d..04f57878 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -782,16 +782,11 @@ impl<'a> Builder<'a> { [l, r, t, b] => Some(ScaleGrid { left: l.min(r), right: l.max(r), top: t.min(b), bottom: t.max(b) }), _ => None, }; - match grid.filter(|g| g.check().is_ok()) { - Some(g) => { - self.report.keep("9-slice scaling guides"); - Some(g) - } - None => { - self.report.skip("9-slice guides that aren't numbers (left out)"); - None - } + let grid = grid.filter(|g| g.check().is_ok()); + if grid.is_none() { + self.report.skip("9-slice guides that aren't usable (left out)"); } + grid } /// The script settings of the package's publish profile (`PublishSettings.xml`): the diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index 87843e84..d1c15e14 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -69,6 +69,7 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[ ("guides", &[]), ("interactive", &[]), ("masks", &[]), + ("nineslice", &[("9-slice guides that aren't usable (left out)", 1)]), ("primitives", &[]), ("scenes", &[("frame comments", 1)]), ("scripts", &[]), @@ -83,7 +84,7 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[ /// What each package keeps without running (ADR 0013 tier 1: scripts outside the subset, and /// class names); packages not listed keep nothing. -const KEPT: &[(&str, &[(&str, usize)])] = &[("bitmaps", &[("library folders", 1)]), ("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)]), ("symbols", &[("library folders", 1)])]; +const KEPT: &[(&str, &[(&str, usize)])] = &[("bitmaps", &[("library folders", 1)]), ("nineslice", &[("library folders", 1)]), ("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)]), ("symbols", &[("library folders", 1)])]; /// The frame scripts each package brings that run (ADR 0013 tier 2: in the subset). const RUNS: &[(&str, &[(&str, usize)])] = &[ @@ -198,6 +199,16 @@ fn tweens_keep_their_kinds_eases_and_hints() { assert_eq!(doc.frame_count(), 13); } +#[test] +fn nineslice_guides_come_across_in_the_symbols_space() { + let (doc, _) = import("nineslice"); + let grid = |name: &str| doc.library.iter().find(|s| s.name == name).and_then(|s| s.scale_grid); + assert_eq!(grid("Panel"), Some(anicraft_doc::ScaleGrid { left: 10.0, right: 90.0, top: 10.0, bottom: 30.0 })); + assert_eq!(grid("Pip"), None); + assert_eq!(grid("Half"), None, "one guide alone isn't a grid"); + assert_eq!(doc.library.iter().find(|s| s.name == "Panel").map(|s| s.kind), Some(SymbolKind::MovieClip)); +} + #[test] fn masks_and_folders_link_up() { let (doc, _) = import("masks"); diff --git a/crates/xfl/tests/corpus/nineslice/DOMDocument.xml b/crates/xfl/tests/corpus/nineslice/DOMDocument.xml new file mode 100644 index 00000000..c64fe7da --- /dev/null +++ b/crates/xfl/tests/corpus/nineslice/DOMDocument.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Half.xml b/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Half.xml new file mode 100644 index 00000000..95647df5 --- /dev/null +++ b/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Half.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Panel.xml b/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Panel.xml new file mode 100644 index 00000000..091bbb5b --- /dev/null +++ b/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Panel.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Pip.xml b/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Pip.xml new file mode 100644 index 00000000..77956e8f --- /dev/null +++ b/crates/xfl/tests/corpus/nineslice/LIBRARY/Ui/Pip.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/nineslice/golden/frame-000.png b/crates/xfl/tests/corpus/nineslice/golden/frame-000.png new file mode 100644 index 0000000000000000000000000000000000000000..01349e07ceb172017f23e475d43d7680c87668cf GIT binary patch literal 4022 zcmdT{dsGv576wtGvNT0j(`q4#qO~Z4Qbk1*U#yR;W-Y5(i)LJ1Wd$WFRRV+zVtpVg z7Oka1tH3}?$HCjG!fl*&#hV+h^t?76ICX5X^wi|YkPh1pSwh;mz0rwvT*)54)(b^s z`f1Ls0m*gC!K?>opJrXtT>!z)Yqls?ZLdSr(qR zg4@~IV9-9yUMKHd$5gh3qbiuCY)#sLMmxBO|MA_OdPpCL6IwcJ1| z3dJvELvpWuC%i+$&_$#^@^+>AK0~afnS7#Pxk1}8^id2}tvAsXTj z=c4%#QATg^=bMM(g3NG#hRWy6y|9vUnk!khE14NxM(QuNG#fNraYx*sY{uBl{1+2h zhlQ#oWgOOVATS98p-hB^n3C0t7ZQwl?m~Nuo9Sd0m;6C+PElKAMt|!ZjaD;|yEJo} z)Ur(;fnqd7IS%BPi*w1#QmhjT2lR2JpdBNC4wu(!Gc?iWo1$_V8NtR1k!-lV90!Y0GhN;krkKFA?lh>7N$y?-YhuxsIJ~Qn zoo`CWeTw{Sq2;!9F-;#Tj7M1e7_F2jD56A>JHL*TGok$lA;$;&{%(lOER{Jm)tDY} z)R*Nn-2@wKbQwlMwi;3C4aERRMUC<(QIPi|SIFl7aRh7$k`MHBEmPo77Bn{ii!_^Y zV>h^GVkR{^VbfV#W=e)1|2Q=&r9{cl1qDX2{L`t5m(juiH=xa4YRfKmr3~odKxl^_ z_?Ry?@5{YrVRJ%>9B>FAI z7&6<_QH7p{91?&AbS(enFfx)TohNvGzDa)GwxBPOVHGr9{&+rn}mDC&C z_KqOpZzER^T9G@FR-Y$b6NP`L9vHp*dK8y@l5x|4{qP9?$)JhpW{s$UPJW^$Wyliw zqltvz7}zqx0P>)FG($B}uhqlDkJIogOk%piDF7#g zm*Q~s1n_j~6A%iYpbP6|n%y=^6nsXB!rM9r87gzuHdiTjF}$yTzAA!lJP(^D6874H zrKy)Ijp$0pu1d3=o;nc57ctBH%$wPGvdEz(r(kPkMzEZ`wOI~0iqDzGVu2EEc^>#A zmr-6J$)G{~x@i@r=-O+`W;;2=mrw=RV9!T1dOo(^c9kxQ|1Z$(;WkwO)SD;*&^tv! zOzV%*SyhRff{f|3I8j$g{6B|*Iw~c4@@_OQ7GOKe)+L4TO-e#=6iE-W;nDb!0>_HE z+FoUoT9OLGjbveUGAdxF>}O6x@<0NWw&m|Eump#Smm=o_7eTHkwTP_;f()i#Xl8gK zrAz2X?#@(KO397_(?;07+3TzN{52PL9ukI}qJPmmHU7*QadN zl}+N?FXd{s^Y!apvR+5gFXZfZDrlBz{J!`|<5+Imw8R{+xR27%y*`tB2WM7`VPl<4g{t?Z0bjts}OSfbQ+gy2BzRTuC{hFAEs%YKF1lm} zfS0gM4iQ!;ijZ0ppvqUpk7h9|G zhmdoHc2ZOzWE)AMx6uq=8{S~M$t7k#(M*AN0$-0KEboJv$iX+6X%l3*p}Aag_MX70 zgiZCi>66`da8#7K6infw&hVxA(<(S@OMv`-QOSf+n0la_nMK8R!%okIJg3z&V&B1? z7GKw)G`DW>R(Gj=+-Z>AefZT?U7)^Jfab)GJA~EbX7rbu6Cln)BFtkILhN;FXDmz4 zLH#q2Td#&apA&yo2OvZ67lr?jw}p7Y#%yNk2t{j{DP*pD^2ZnxQAfN;ClQBX$4_QU zL?60t-e?jO%wdr`6vjaI;V9ufUe6RnM^fBjQE}QFsz3B|E2@n_R4|DF1w@Sc&l!ch zHrL5RYjX(}OpIr$+Djf+VUVXHu#o}}_unY9h8*A_n;)x-qu322_S*4M%SWyn!8N1? zlaup;Z!*L+wBM7xPRT8<6(EnoT*NafK^8?PTwRh-j1$pw0IC`z7L8bQ@Q@x`n=>?O zyU)o`?`fNqLF=m76WWNoXM>W0(nvN{&lsLwK-4i0bW>z>T-9#){Zekj>l7|YjBa_wX28K<&2)wy@(*AQ`r zu7y1=3)N7($8w&N(-{p)8%nfQrmal;{;T%9Bfbt#m39teE}YpqRvXGxE$5Ytw8><7 zx#%vo?V7-~xOwm;ANa=ZbfM@}+#4%ax33Ry{%6ZeX&Q8H_;Y+L&k3Hrx##icd(azp zhN>IND7bn#K$_AVP5+v)^?*eDa Date: Wed, 11 Nov 2026 01:18:05 -0700 Subject: [PATCH 012/192] test(render): the oracle, SVG and Lottie draw 9-sliced instances; HTML reports them (M2) --- crates/doc/src/nine_slice.rs | 6 ++ crates/render/src/html.rs | 8 ++- crates/render/src/html_tests.rs | 13 ++++ crates/render/src/lib.rs | 3 + crates/render/src/nine_slice_tests.rs | 89 +++++++++++++++++++++++++++ 5 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 crates/render/src/nine_slice_tests.rs diff --git a/crates/doc/src/nine_slice.rs b/crates/doc/src/nine_slice.rs index 63947dc1..e9e3d7be 100644 --- a/crates/doc/src/nine_slice.rs +++ b/crates/doc/src/nine_slice.rs @@ -66,6 +66,12 @@ pub(crate) fn slicing(doc: &Document, sym: &Symbol, transform: &Affine) -> Optio }) } +/// Whether an instance of `sym` placed by `transform` is drawn 9-sliced (exporters that place +/// symbols themselves say when they can't). +pub fn slices(doc: &Document, sym: &Symbol, transform: &Affine) -> bool { + slicing(doc, sym, transform).is_some() +} + /// The 9-slice map of box `b` with guides `grid`, scaled by `sx`, `sy` (both at least 0). An /// axis with no extent (a symbol only a line high) scales plainly. pub fn map_for(grid: &ScaleGrid, b: &Rect, sx: f32, sy: f32) -> Option { diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 21cb4b25..1743eb8f 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -13,7 +13,8 @@ //! clips have their own playheads, buttons their pointer states). Identical paths, paints and //! 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, +//! What doesn't carry across is counted in the report: filters, 9-slice scaling (instances +//! scale as a whole), Subtract and Invert blending, //! 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. @@ -94,6 +95,7 @@ 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 outside the ActionScript subset (not run; kept in the document only)"; +const NINE_SLICE: &str = "9-slice scaling (scaled as a whole)"; 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. @@ -437,6 +439,10 @@ impl<'a> Bake<'a> { ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => { let (Some(&y), Some(sym)) = (self.symbols.get(symbol), self.doc.symbol(*symbol)) else { return }; let len = sym.timeline.frame_count(); + // The page's player places symbols itself and doesn't slice them yet (ADR 0055). + if anicraft_doc::nine_slice::slices(self.doc, sym, &el.transform) { + self.notes.entry(NINE_SLICE).or_default().insert(el.id.0); + } let mut o = Map::new(); o.insert("y".into(), json!(y)); o.insert("id".into(), json!(el.id.0)); diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 8bfba887..e336a810 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -503,8 +503,21 @@ fn what_does_not_carry_across_is_reported() { *blend = BlendMode::Subtract; } Arc::make_mut(&mut tl.layers[0]).keyframe_mut(1).unwrap().script = Some(FrameScript::Plugin(PluginScript { id: "org.example.menu".into(), entry: "main".into() })); + // A 9-slice symbol, scaled: the page scales it as a whole (ADR 0055). + let sym = match &doc.timeline(0).layers[2].keyframes[0].elements[0].kind { + ElementKind::Symbol { symbol, .. } => *symbol, + _ => unreachable!(), + }; + if let Some(x) = doc.library.iter_mut().find(|x| x.id == sym) { + Arc::make_mut(x).scale_grid = Some(anicraft_doc::ScaleGrid { left: 1.0, right: 2.0, top: 1.0, bottom: 2.0 }); + } + let m = movie(&doc, &HtmlOptions::default()); + assert_eq!(m.report.get(NINE_SLICE), None, "unscaled instances draw the same either way"); + let tl = doc.timeline_mut(0); + Arc::make_mut(&mut Arc::make_mut(&mut tl.layers[2]).keyframe_mut(0).unwrap().elements[0]).transform = Affine::scale(2.0, 1.0); let m = movie(&doc, &HtmlOptions::default()); assert_eq!(m.report.get(FILTERS), Some(&1)); + assert_eq!(m.report.get(NINE_SLICE), Some(&1)); assert_eq!(m.report.get(BLENDS), Some(&1)); assert_eq!(m.report.get(PLUGIN_SCRIPTS), Some(&1)); // The player says so when the frame script's keyframe is entered. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f85251d7..762a940f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -903,6 +903,9 @@ fn composite(cov: &Coverage, op: &Prepared, b: IRect, band_y0: i32, w: usize, ro } } +#[cfg(test)] +mod nine_slice_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/render/src/nine_slice_tests.rs b/crates/render/src/nine_slice_tests.rs new file mode 100644 index 00000000..75a92b54 --- /dev/null +++ b/crates/render/src/nine_slice_tests.rs @@ -0,0 +1,89 @@ +//! 9-slice scaling (ADR 0055) in the renderer and the exports that draw evaluated frames: the +//! CPU oracle, SVG and Lottie all see the sliced outline, baked, with strokes at their width. + +use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, ScaleGrid, Shape, Stage, Stroke, Symbol, SymbolId, SymbolKind, Timeline, evaluate}; +use anicraft_geom::{Affine, Path}; +use std::sync::Arc; + +/// A 100 × 40 rounded panel (radius 10, a 2-wide outline) with guides 10 in, one instance at +/// (20, 20) scaled by `sx`, `sy`, on a 400 × 200 stage. +fn panel(sx: f32, sy: f32, guides: bool) -> Document { + let mut d = Document { stage: Stage { width: 400, height: 200, ..Stage::default() }, ..Document::default() }; + let mut shape = Shape::filled(Path::rounded_rect(0.0, 0.0, 100.0, 40.0, 10.0), Paint::Solid(Rgba::hex(0x2A9D8F))); + shape.stroke = Some(Stroke::new(Rgba::hex(0x264653), 2.0)); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(Element { id: ElementId(2), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) })); + let mut l = Layer::new(LayerId(3), "art"); + l.keyframes = vec![Arc::new(k)]; + let grid = guides.then_some(ScaleGrid { left: 10.0, right: 90.0, top: 10.0, bottom: 30.0 }); + d.library.push(Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(l)] } })); + let inst = Element { + id: ElementId(5), + name: String::new(), + transform: Affine::translate(20.0, 20.0).mul(&Affine::scale(sx, sy)), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + }; + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(inst)); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k)]; + d +} + +/// The `n` × `n` block of pixels from (x0, y0). +fn pixels(d: &Document, x0: u32, y0: u32, n: u32) -> Vec { + let pm = crate::render_frame(d, 0, 1.0).unwrap(); + (0..n).flat_map(|y| (0..n).map(move |x| (x, y))).filter_map(|(x, y)| pm.pixel(x0 + x, y0 + y)).collect() +} + +fn same(a: &[crate::Premul], b: &[crate::Premul]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| p.iter().zip(q).all(|(x, y)| (x - y).abs() < 1e-3)) +} + +#[test] +fn the_oracle_draws_every_corner_as_the_unscaled_one() { + // Unscaled the panel covers (20, 20)–(120, 60); scaled 3.5 × 3, (20, 20)–(370, 140). Each + // 12 × 12 corner block (its outline included) matches the unscaled panel's own corner. + let (one, big, plain) = (panel(1.0, 1.0, true), panel(3.5, 3.0, true), panel(3.5, 3.0, false)); + for ((ux, uy), (bx, by)) in [((19, 19), (19, 19)), ((109, 19), (359, 19)), ((19, 49), (19, 129)), ((109, 49), (359, 129))] { + let want = pixels(&one, ux, uy, 12); + assert!(same(&pixels(&big, bx, by, 12), &want), "corner at ({bx}, {by})"); + assert!(!same(&pixels(&plain, bx, by, 12), &want), "plain scaling changes the corner at ({bx}, {by})"); + } +} + +#[test] +fn svg_writes_the_sliced_outline_with_the_stroke_at_its_width() { + let svg = crate::svg::to_svg(&evaluate(&panel(3.0, 3.0, true), 0), &Stage { width: 400, height: 200, ..Stage::default() }); + // The right edge lands at 20 + 300 and the stroke stays 2 wide (plain scaling: 6). + assert!(svg.contains("320"), "{svg}"); + assert!(svg.contains("stroke-width=\"2\""), "{svg}"); + let plain = crate::svg::to_svg(&evaluate(&panel(3.0, 3.0, false), 0), &Stage { width: 400, height: 200, ..Stage::default() }); + assert!(plain.contains("stroke-width=\"6\""), "{plain}"); +} + +#[test] +fn lottie_bakes_the_sliced_outline() { + let x = crate::lottie::to_lottie(&panel(3.0, 3.0, true), "panel", 0, 1, false); + let v: serde_json::Value = serde_json::from_str(&x.json).unwrap(); + // Every vertex of every shape layer, in stage space. + let mut xs = Vec::new(); + fn walk(v: &serde_json::Value, xs: &mut Vec) { + match v { + serde_json::Value::Object(o) => { + if let Some(serde_json::Value::Array(vs)) = o.get("v") { + xs.extend(vs.iter().filter_map(|p| p.get(0).and_then(serde_json::Value::as_f64))); + } + o.values().for_each(|c| walk(c, xs)); + } + serde_json::Value::Array(a) => a.iter().for_each(|c| walk(c, xs)), + _ => {} + } + } + walk(&v, &mut xs); + let max = xs.iter().copied().fold(f64::MIN, f64::max); + assert!((max - 320.0).abs() < 0.01, "{max}"); + // The top-right corner arc starts 10 in from the right edge: a vertex at x = 310. + assert!(xs.iter().any(|x| (x - 310.0).abs() < 0.01), "{xs:?}"); + assert!(x.report.is_empty(), "{:?}", x.report); +} From 224fc840129147017496c6f5ad6b85845a5ed23d Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:18:26 -0700 Subject: [PATCH 013/192] test(gpu): 9-sliced instances bin like the oracle draws them (M2) --- crates/gpu/src/tests.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 214cd49c..e8fc906d 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -465,6 +465,27 @@ fn composited_sample() -> anicraft_doc::Document { doc } +/// A rounded panel with 9-slice guides, placed stretched, scaled up and turned. +fn nine_slice_sample() -> anicraft_doc::Document { + use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, ScaleGrid, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; + let mut d = anicraft_doc::Document { stage: anicraft_doc::Stage { width: 320, height: 200, ..Default::default() }, ..Default::default() }; + let mut shape = Shape::filled(Path::rounded_rect(0.0, 0.0, 60.0, 30.0, 8.0), Paint::Solid(Rgba::hex(0x2a9d8f))); + shape.stroke = Some(Stroke::new(Rgba::hex(0x264653), 2.0)); + let el = |id, transform, kind| std::sync::Arc::new(Element { id: ElementId(id), name: String::new(), transform, color: ColorEffect::default(), kind }); + let mut k = Keyframe::new(0, 1); + k.elements.push(el(2, Affine::IDENTITY, ElementKind::Shape(shape))); + let mut l = Layer::new(LayerId(3), "art"); + l.keyframes = vec![std::sync::Arc::new(k)]; + d.library.push(std::sync::Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: Some(ScaleGrid { left: 8.0, right: 52.0, top: 8.0, bottom: 22.0 }), timeline: Timeline { layers: vec![std::sync::Arc::new(l)] } })); + let inst = |id, xf| el(id, xf, ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }); + let mut k = Keyframe::new(0, 1); + k.elements.push(inst(5, Affine::translate(10.0, 10.0).mul(&Affine::scale(4.5, 1.2)))); + k.elements.push(inst(6, Affine::translate(30.0, 70.0).mul(&Affine::scale(2.0, 3.5)))); + k.elements.push(inst(7, Affine::translate(220.0, 90.0).mul(&Affine::rotate(0.5)).mul(&Affine::scale(1.5, 2.5)))); + std::sync::Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![std::sync::Arc::new(k)]; + d +} + #[test] fn binned_coverage_matches_the_oracle_on_the_cpu() { let mut all = scenes(); @@ -480,6 +501,10 @@ fn binned_coverage_matches_the_oracle_on_the_cpu() { for (f, s) in [(0u32, 0.4f32), (30, 0.6)] { all.push(("composited sample", anicraft_doc::evaluate(&comp, f), View::stage(&comp, s))); } + // A 9-sliced instance (ADR 0055) reaches the stage through evaluation: cut outlines, strokes + // at their own width. + let nine = nine_slice_sample(); + all.push(("9-slice", anicraft_doc::evaluate(&nine, 0), View::stage(&nine, 0.7))); for (name, dl, v) in all { let (scene, _) = prepare_scene(&dl, &v).unwrap(); let b = binning::bin(&scene, v.width, v.height).unwrap(); From fb5556f140b55fbf0fd45a6b687c55fbd24acbc8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 04:34:06 -0700 Subject: [PATCH 014/192] feat(shell): 9-slice guides on the stage while editing a symbol, Properties and Library controls (M2) --- src/a11y.rs | 2 +- src/app.rs | 22 +++++++ src/library.rs | 2 + src/main.rs | 3 +- src/panels.rs | 45 +++++++++++++ src/scale_grid.rs | 160 ++++++++++++++++++++++++++++++++++++++++++++++ src/stage.rs | 18 +++++- src/theme.rs | 5 ++ 8 files changed, 254 insertions(+), 3 deletions(-) create mode 100644 src/scale_grid.rs diff --git a/src/a11y.rs b/src/a11y.rs index 2e829dc5..f9bbdc0e 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -352,7 +352,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index 37151273..b9617566 100644 --- a/src/app.rs +++ b/src/app.rs @@ -235,6 +235,8 @@ pub enum Drag { BonePose { bone: anicraft_engine::doc::BoneId, local: egui::Pos2 }, /// Moving a whole armature by its root, from stage point `last` last frame. ArmatureMove { layer: anicraft_engine::doc::LayerId, last: egui::Pos2 }, + /// Moving one of the open symbol's 9-slice guides (ADR 0055). + SliceGuide { guide: crate::scale_grid::Guide }, Pan, } @@ -1110,6 +1112,26 @@ impl App { self.run("raw.subselect", json!({"x": 0, "y": 60, "slop": 4})); self.raw_ends = Vec::new(); } + Some(which @ ("nineslice" | "nineslicedit")) => { + // 9-slice scaling (ADR 0055): a rounded panel symbol with its guides on, one + // instance as drawn and one stretched wide (its corners stay round), the wide one + // selected; "nineslicedit" opens the symbol with its guides on the stage. + self.run("layer.new", json!({"name": "Panels"})); + self.run("draw.rect", json!({"x": 80, "y": 560, "w": 200, "h": 80, "radius": 24, "fill": "#2a9d8f", "stroke": "#264653", "stroke_width": 4})); + self.run("modify.convert_to_symbol", json!({"name": "Panel"})); + self.run("symbol.set_kind", json!({"kind": "movie_clip"})); + self.run("symbol.set_scale_grid", json!({"left": -70, "right": 70, "top": -14, "bottom": 14})); + self.run("edit.duplicate", json!({"dx": 260, "dy": 0})); + // Stretched about its left edge (x = 340): 2.9 times as wide, 1.4 times as high. + self.run("modify.transform", json!({"a": 2.9, "b": 0, "c": 0, "d": 1.4, "e": 340.0 * -1.9, "f": 600.0 * -0.4})); + if which == "nineslicedit" { + // The instance as drawn opens in place, the scene dimmed around it. + self.run("element.pick", json!({"x": 180, "y": 600})); + self.run("symbol.edit", json!({})); + self.run("edit.deselect", json!({})); + self.tool = Tool::Select; + } + } Some(which @ ("brush" | "brushing")) => { // Brushed artwork on a new layer (ADR 0033): a pressure-tapered wave, a flat // calligraphic tip at 45°, square dabs, and a pink stroke painted behind a raw diff --git a/src/library.rs b/src/library.rs index bc8660fe..ea2f72e4 100644 --- a/src/library.rs +++ b/src/library.rs @@ -783,6 +783,8 @@ fn properties(app: &mut App, ui: &mut egui::Ui) { app.run("script.set_class", json!({"symbol": id.0, "class": v, "base": base})); } }); + // 9-slice scaling (ADR 0055), as in Animate's Symbol Properties. + crate::panels::scale_grid_props(app, ui, id, "library"); } LibraryItem::Bitmap(id) => { let Some(mut on) = app.s.doc.bitmap(id).map(|b| b.smoothing) else { return }; diff --git a/src/main.rs b/src/main.rs index 3f5dde9d..f2746514 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,6 +46,7 @@ mod pathtools; mod platform; mod plugins_ui; mod prefs; +mod scale_grid; mod sound; mod shape_hints; mod stage; @@ -179,7 +180,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/panels.rs b/src/panels.rs index e944c954..44d6bbb3 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -275,6 +275,43 @@ pub(crate) fn live(app: &mut App, label: &str, id: &str, p: Value) { app.run(id, p); } +/// A symbol's 9-slice guides (ADR 0055): Animate's "Enable guides for 9-slice scaling" and, +/// when on, where the four guides are (in the symbol's space; also dragged on the stage while +/// the symbol is open). `salt` keeps two copies of the controls apart (Library, Properties). +pub(crate) fn scale_grid_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::SymbolId, salt: &str) { + let Some(grid) = app.s.doc.symbol(id).map(|s| s.scale_grid) else { return }; + let mut on = grid.is_some(); + ui.push_id(salt, |ui| { + let tip = tr!("Scaled instances keep the corners outside the guides unscaled, stretch the edges one way and the centre both ways (for buttons and panels). Edit the symbol to drag the guides"); + if crate::theme::checkbox(ui, &mut on, tr!("Enable guides for 9-slice scaling")).on_hover_text(tip).changed() { + app.run("symbol.set_scale_grid", json!({"symbol": id.0, "on": on})); + } + let Some(g) = grid else { return }; + let limit = anicraft_engine::doc::MAX_GRID_COORD; + let (mut l, mut r, mut t, mut b) = (g.left, g.right, g.top, g.bottom); + let mut changed = None; + row(ui, tr!("Guides x"), |ui| { + if ui.add(egui::DragValue::new(&mut l).range(-limit..=g.right).speed(0.5).max_decimals(1)).named(tr!("Left 9-slice guide")).changed() { + changed = Some(("left", l)); + } + if ui.add(egui::DragValue::new(&mut r).range(g.left..=limit).speed(0.5).max_decimals(1)).named(tr!("Right 9-slice guide")).changed() { + changed = Some(("right", r)); + } + }); + row(ui, tr!("Guides y"), |ui| { + if ui.add(egui::DragValue::new(&mut t).range(-limit..=g.bottom).speed(0.5).max_decimals(1)).named(tr!("Top 9-slice guide")).changed() { + changed = Some(("top", t)); + } + if ui.add(egui::DragValue::new(&mut b).range(g.top..=limit).speed(0.5).max_decimals(1)).named(tr!("Bottom 9-slice guide")).changed() { + changed = Some(("bottom", b)); + } + }); + if let Some((key, v)) = changed { + live(app, tr_noop!("Move 9-Slice Guide"), "symbol.set_scale_grid", json!({"symbol": id.0, key: v})); + } + }); +} + /// A property row for values: proportional label (left-aligned column), monospace fields. fn row(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui)) { crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, label, |ui| with_type(ui, Type::Data, add)); @@ -431,6 +468,9 @@ fn properties(app: &mut App, ui: &mut egui::Ui) { (n, l) => trn!("{n} element {on_layers}", "{n} elements {on_layers}", n, on_layers = trn!("on {n} layer", "on {n} layers", l)), }; section(ui, "prop_selection", Section::Rule, &title, None, |ui| selection_props(app, ui, e, &sel)); + } else if let Some((id, name)) = app.s.editing_symbol().and_then(|id| app.s.doc.symbol(id).map(|x| (id, x.name.clone()))) { + // Inside a symbol, nothing selected: the symbol's own settings (ADR 0055). + section(ui, "prop_symbol", Section::Rule, &tr!("Symbol: {name}", name = name), None, |ui| scale_grid_props(app, ui, id, "open")); } else { section(ui, "prop_document", Section::Rule, tr!("Document"), None, |ui| document_props(app, ui)); } @@ -610,6 +650,11 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E .set_name(tr!("Swap Symbol")); mixed(ui, m.symbol); }); + // 9-slice scaling is the symbol's (ADR 0055): on here, it is on for every instance. + let sym_id = *symbol; + row_prose(ui, tr!("Scaling"), |ui| { + ui.vertical(|ui| scale_grid_props(app, ui, sym_id, "instance")); + }); // The class scripts know the symbol by (kept, not run; ADR 0013), in documents // that use scripts. let linkage = app.s.doc.symbol(*symbol).and_then(|s| s.linkage.clone()); diff --git a/src/scale_grid.rs b/src/scale_grid.rs new file mode 100644 index 00000000..8bd8763e --- /dev/null +++ b/src/scale_grid.rs @@ -0,0 +1,160 @@ +//! 9-slice guides on the stage (ADR 0055). +//! +//! While a symbol with guides for 9-slice scaling is open for editing (ADR 0045), its four +//! guides show as dashed lines across the stage, as in Animate. The Selection tool drags them: +//! each drag is one undo step (`symbol.set_scale_grid` inside a gesture). A guide can't pass the +//! other guide of its pair. Properties has the same four numbers. + +use crate::app::{App, Drag, Tool}; +use crate::pathtools::Xf; +use crate::theme::T; +use anicraft_engine::doc::{ScaleGrid, SymbolId}; +use egui::{Color32, CursorIcon, Painter, Pos2, Rect, Stroke, pos2}; +use serde_json::json; + +/// Which guide. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Guide { + Left, + Right, + Top, + Bottom, +} + +impl Guide { + const ALL: [Guide; 4] = [Guide::Left, Guide::Right, Guide::Top, Guide::Bottom]; + + fn vertical(self) -> bool { + matches!(self, Guide::Left | Guide::Right) + } + + /// The command parameter it sets. + fn key(self) -> &'static str { + match self { + Guide::Left => "left", + Guide::Right => "right", + Guide::Top => "top", + Guide::Bottom => "bottom", + } + } + + /// Where it is, in the symbol's space. + fn at(self, g: &ScaleGrid) -> f32 { + match self { + Guide::Left => g.left, + Guide::Right => g.right, + Guide::Top => g.top, + Guide::Bottom => g.bottom, + } + } + + pub fn cursor(self) -> CursorIcon { + if self.vertical() { CursorIcon::ResizeHorizontal } else { CursorIcon::ResizeVertical } + } +} + +/// How near (screen points) the pointer takes a guide. +const GRAB: f32 = 4.0; + +/// The symbol open for editing and its guides, when it has them. +pub fn shown(app: &App) -> Option<(SymbolId, ScaleGrid)> { + let id = app.s.editing_symbol()?; + app.s.doc.symbol(id).and_then(|s| s.scale_grid).map(|g| (id, g)) +} + +/// The guide under screen point `p`, for the Selection tool. +pub fn hit(app: &App, p: Pos2, xf: Xf) -> Option { + if app.tool != Tool::Select { + return None; + } + let (_, g) = shown(app)?; + let near = |guide: Guide| { + let s = xf.to_screen(anicraft_engine::geom::Vec2::new(guide.at(&g), guide.at(&g))); + if guide.vertical() { (p.x - s.x).abs() } else { (p.y - s.y).abs() } + }; + Guide::ALL.into_iter().map(|guide| (guide, near(guide))).filter(|(_, d)| *d <= GRAB).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(guide, _)| guide) +} + +/// Starts dragging `guide`: one undo step until the drag ends. +pub fn drag_start(app: &mut App, guide: Guide) -> Drag { + app.s.begin_gesture(tr_noop!("Move 9-Slice Guide")); + Drag::SliceGuide { guide } +} + +/// The guide follows the pointer (stage point `c`, in the open symbol's space), to a tenth of a +/// pixel, stopping at the other guide of its pair. +pub fn drag_to(app: &mut App, guide: Guide, c: Pos2) { + let Some((id, g)) = shown(app) else { return }; + let v = if guide.vertical() { c.x } else { c.y }; + let v = (v * 10.0).round() / 10.0; + let v = match guide { + Guide::Left => v.min(g.right), + Guide::Right => v.max(g.left), + Guide::Top => v.min(g.bottom), + Guide::Bottom => v.max(g.top), + }; + if v.is_finite() && (v - guide.at(&g)).abs() > 1e-4 { + app.run("symbol.set_scale_grid", json!({"symbol": id.0, guide.key(): v})); + } +} + +/// Draws the guides across the canvas: dashed, over a light underlay; the one under the pointer +/// or being dragged heavier. +pub fn draw(app: &App, painter: &Painter, xf: Xf, canvas: Rect, hot: Option) { + let Some((_, g)) = shown(app) else { return }; + for guide in Guide::ALL { + let s = xf.to_screen(anicraft_engine::geom::Vec2::new(guide.at(&g), guide.at(&g))); + let ends = if guide.vertical() { [pos2(s.x, canvas.top()), pos2(s.x, canvas.bottom())] } else { [pos2(canvas.left(), s.y), pos2(canvas.right(), s.y)] }; + let width = if hot == Some(guide) { 2.0 } else { 1.0 }; + painter.line_segment(ends, Stroke::new(width + 2.0, Color32::WHITE.gamma_multiply(0.7))); + painter.extend(egui::Shape::dashed_line(&ends, Stroke::new(width, T.slice_guide), 6.0, 4.0)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Stage and screen coordinates coincide. + const XF: Xf = Xf { origin: Pos2::ZERO, zoom: 1.0 }; + + /// The `nineslicedit` screenshot state: the Panel symbol open in place, its guides at + /// x = ±70 and y = ±14 in its space. + fn app() -> App { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + app.open_panel(Some("nineslicedit")); + app + } + + #[test] + fn the_selection_tool_takes_the_guide_under_the_pointer() { + let mut app = app(); + assert!(shown(&app).is_some(), "the open symbol has guides"); + assert_eq!(hit(&app, pos2(-70.0, 300.0), XF), Some(Guide::Left)); + assert_eq!(hit(&app, pos2(72.5, -300.0), XF), Some(Guide::Right)); + assert_eq!(hit(&app, pos2(500.0, 14.0), XF), Some(Guide::Bottom)); + assert_eq!(hit(&app, pos2(0.0, 0.0), XF), None); + app.tool = Tool::Subselect; + assert_eq!(hit(&app, pos2(-70.0, 0.0), XF), None, "only the Selection tool drags guides"); + } + + #[test] + fn a_guide_drag_is_one_undo_step_and_stops_at_its_partner() { + let mut app = app(); + let before = app.s.history_len(); + let d = drag_start(&mut app, Guide::Left); + assert_eq!(d, Drag::SliceGuide { guide: Guide::Left }); + for x in [-60.0, -40.04, 200.0] { + drag_to(&mut app, Guide::Left, pos2(x, 0.0)); + } + app.s.end_gesture(); + let g = shown(&app).map(|(_, g)| g).unwrap(); + assert_eq!((g.left, g.right), (70.0, 70.0), "the left guide stops at the right one"); + assert_eq!(app.s.history_len(), before + 1); + assert_eq!(app.s.undo_label(), Some("Move 9-Slice Guide")); + app.s.undo().unwrap(); + assert_eq!(shown(&app).map(|(_, g)| g.left), Some(-70.0)); + } +} diff --git a/src/stage.rs b/src/stage.rs index 282d23ef..fb2c2427 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -303,9 +303,13 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // (ADR 0038). The Pen with Alt over the path adds a point there. let mp_move = mp_tools && command && app.drag == Drag::None && pointer.is_some_and(|p| crate::motion_path::move_hit(app, p, xf)); let pen_hot = if app.tool == Tool::Pen && alt && !panning && !preview && app.drag == Drag::None { pointer.and_then(|p| crate::motion_path::pen_hot(app, p, xf)) } else { None }; + // The open symbol's 9-slice guides take the Selection tool's press first (ADR 0055). + let slice_hot = if app.drag == Drag::None && !panning && !preview { pointer.and_then(|p| crate::scale_grid::hit(app, p, xf)) } else { None }; if resp.hovered() { let icon = match app.tool { _ if panning => CursorIcon::Grab, + _ if let Drag::SliceGuide { guide } = app.drag => guide.cursor(), + _ if let Some(guide) = slice_hot => guide.cursor(), _ if matches!(app.drag, Drag::Hint { .. } | Drag::CameraPan { .. } | Drag::BonePose { .. }) => CursorIcon::Grabbing, _ if matches!(app.drag, Drag::ArmatureMove { .. }) => CursorIcon::Move, Tool::Select if app.drag == Drag::None && pointer.is_some_and(|p| crate::bone_tool::hit(app, xf, p).is_some()) => CursorIcon::Grab, @@ -362,6 +366,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Drag::Pan } else if paused { Drag::None + } else if let Some(guide) = crate::scale_grid::hit(app, press, xf) { + crate::scale_grid::drag_start(app, guide) } else if let Some(m) = hint_at(press) { // Undo labels stay English in the history and are translated where they show. app.s.begin_gesture(tr_noop!("Move Shape Hint")); @@ -556,6 +562,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { *last = c; crate::motion_path::move_to(app, Vec2::new(d.x, d.y)); } + (Drag::SliceGuide { guide }, Some(c)) => { + let guide = *guide; + crate::scale_grid::drag_to(app, guide, c); + } (Drag::Hint { index, side }, Some(c)) => { // Live: the hint snaps to the nearest edge as the pointer moves. let (index, side) = (*index, *side); @@ -597,7 +607,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.raw_points = serde_json::Value::Null; app.s.end_gesture(); } - Drag::Transform { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::MotionMove { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } | Drag::BonePose { .. } | Drag::ArmatureMove { .. } => app.s.end_gesture(), + Drag::Transform { .. } | Drag::SliceGuide { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::MotionMove { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } | Drag::BonePose { .. } | Drag::ArmatureMove { .. } => app.s.end_gesture(), Drag::Bone { from, head, cur } => crate::bone_tool::drag_end(app, xf, from, head, cur), Drag::Width { .. } => crate::widthtool::drag_end(app), Drag::MotionPath { .. } => crate::motion_path::drag_end(app), @@ -1097,6 +1107,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { text_editor(app, ui, to_screen(Vec2::new(0.0, 0.0)), zoom); + // Inside a symbol with 9-slice guides: the guides, across the stage (ADR 0055). + let slice_drag = match app.drag { + Drag::SliceGuide { guide } => Some(guide), + _ => slice_hot, + }; + crate::scale_grid::draw(app, &painter, xf, canvas, slice_drag); // Inside a symbol: its registration point (ADR 0045; the way back is in the edit bar). if edit_view.is_some() { let c = to_screen(Vec2::ZERO); diff --git a/src/theme.rs b/src/theme.rs index 7043277a..63e586b1 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -80,6 +80,9 @@ pub struct Tokens { /// after it (green); the defaults the onion menu can change. Also the ruler's markers. pub onion_past: Color32, pub onion_future: Color32, + /// A symbol's 9-slice guides while it is open for editing (ADR 0055), dashed over a light + /// underlay so they read on any artwork. + pub slice_guide: Color32, /// Library symbol kinds. pub kind_graphic: Color32, pub kind_movie_clip: Color32, @@ -148,6 +151,7 @@ pub const GRAPHITE: Tokens = Tokens { hint_end: Color32::from_rgb(0x4f, 0xe3, 0xa8), onion_past: Color32::from_rgb(0x4f, 0x8d, 0xff), onion_future: Color32::from_rgb(0x4c, 0xd0, 0x7d), + slice_guide: Color32::from_rgb(0xd9, 0x3c, 0xc4), kind_graphic: Color32::from_rgb(0x22, 0xc7, 0xa9), kind_movie_clip: Color32::from_rgb(0x5a, 0x8f, 0xff), kind_button: Color32::from_rgb(0xff, 0xb5, 0x3d), @@ -204,6 +208,7 @@ pub const HIGH_CONTRAST: Tokens = Tokens { hint_end: Color32::from_rgb(0x74, 0xff, 0xb0), onion_past: Color32::from_rgb(0x6f, 0xa8, 0xff), onion_future: Color32::from_rgb(0x5c, 0xf0, 0x9a), + slice_guide: Color32::from_rgb(0xff, 0x6e, 0xe6), kind_graphic: Color32::from_rgb(0x3d, 0xf0, 0xcf), kind_movie_clip: Color32::from_rgb(0x85, 0xad, 0xff), kind_button: Color32::from_rgb(0xff, 0xc8, 0x5c), From f07a969c15ab97fc7b970ab164f04e4467501b2b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 04:39:19 -0700 Subject: [PATCH 015/192] test: tidy 9-slice tests for clippy (M2) --- crates/doc/src/nine_slice_tests.rs | 6 ++---- crates/geom/src/slice.rs | 6 ++---- crates/render/src/html_tests.rs | 5 +---- 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/nine_slice_tests.rs b/crates/doc/src/nine_slice_tests.rs index e9a87b47..83484f19 100644 --- a/crates/doc/src/nine_slice_tests.rs +++ b/crates/doc/src/nine_slice_tests.rs @@ -138,10 +138,8 @@ fn unscaled_instances_and_nested_symbols_draw_as_they_are() { // At scale 1 nothing is cut: the symbol's own path is drawn, shared. let d = doc(Affine::translate(5.0, 5.0), Some(GRID), Vec::new()); let dl = evaluate(&d, 0); - let sym_path = match &d.symbol(SYM).unwrap().timeline.layers[0].keyframes[0].elements[0].kind { - ElementKind::Shape(s) => s.path.clone(), - _ => unreachable!(), - }; + let ElementKind::Shape(s) = &d.symbol(SYM).unwrap().timeline.layers[0].keyframes[0].elements[0].kind else { panic!("the panel is a shape") }; + let sym_path = s.path.clone(); assert!(Arc::ptr_eq(&dl.items[0].path, &sym_path)); // A nested symbol inside scales normally: its item carries the whole 3× scale. let mut d = doc(Affine::scale(3.0, 3.0), Some(GRID), vec![instance(SymbolId(950), Affine::translate(50.0, 20.0))]); diff --git a/crates/geom/src/slice.rs b/crates/geom/src/slice.rs index 8fdd881f..357e32bb 100644 --- a/crates/geom/src/slice.rs +++ b/crates/geom/src/slice.rs @@ -394,8 +394,7 @@ mod tests { #[test] fn a_closing_line_is_drawn_out_so_it_bends_at_the_guides() { // A triangle whose closing edge runs diagonally across the left guide. - let mut p = Path::default(); - p.cmds = vec![PathCmd::MoveTo(Vec2::new(0.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 40.0)), PathCmd::Close]; + let p = Path { cmds: vec![PathCmd::MoveTo(Vec2::new(0.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 40.0)), PathCmd::Close] }; let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(), y: Axis::identity(0.0, 40.0) }; let s = slice_path(&p, &Affine::IDENTITY, &map); assert_eq!(s.cmds.last(), Some(&PathCmd::Close)); @@ -406,8 +405,7 @@ mod tests { #[test] fn curves_are_cut_at_exact_crossings_and_stay_on_the_mapped_curve() { let c = [Vec2::new(0.0, 0.0), Vec2::new(30.0, 60.0), Vec2::new(70.0, -20.0), Vec2::new(100.0, 40.0)]; - let mut p = Path::default(); - p.cmds = vec![PathCmd::MoveTo(c[0]), PathCmd::CubicTo(c[1], c[2], c[3])]; + let p = Path { cmds: vec![PathCmd::MoveTo(c[0]), PathCmd::CubicTo(c[1], c[2], c[3])] }; let map = Slice9 { x: Axis::new(0.0, 25.0, 75.0, 100.0, 2.5).unwrap(), y: Axis::new(-20.0, 0.0, 20.0, 60.0, 1.5).unwrap() }; let s = slice_path(&p, &Affine::IDENTITY, &map); // Sample the source curve; each sample's image must lie on the sliced path (within diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index e336a810..b631e1df 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -504,10 +504,7 @@ fn what_does_not_carry_across_is_reported() { } Arc::make_mut(&mut tl.layers[0]).keyframe_mut(1).unwrap().script = Some(FrameScript::Plugin(PluginScript { id: "org.example.menu".into(), entry: "main".into() })); // A 9-slice symbol, scaled: the page scales it as a whole (ADR 0055). - let sym = match &doc.timeline(0).layers[2].keyframes[0].elements[0].kind { - ElementKind::Symbol { symbol, .. } => *symbol, - _ => unreachable!(), - }; + let ElementKind::Symbol { symbol: sym, .. } = doc.timeline(0).layers[2].keyframes[0].elements[0].kind else { panic!("the fixture's third layer holds an instance") }; if let Some(x) = doc.library.iter_mut().find(|x| x.id == sym) { Arc::make_mut(x).scale_grid = Some(anicraft_doc::ScaleGrid { left: 1.0, right: 2.0, top: 1.0, bottom: 2.0 }); } From e396447c3775aed4e5c1b01277a642eba949f0d7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 04:39:19 -0700 Subject: [PATCH 016/192] docs: ADR 0055 9-slice scaling, roadmap and changelog (M2) --- CHANGELOG.md | 14 ++++ docs/adr/0055-nine-slice-scaling.md | 120 ++++++++++++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 4 +- 4 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 docs/adr/0055-nine-slice-scaling.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f4393c8..cf7f9491 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +* **9-slice scaling for symbols** (ADR 0055, M2). + * **Enable guides for 9-slice scaling** on a symbol, in the Library's item properties or in + Properties. A scaled instance then keeps its corners unscaled, stretches its edges one way + and its centre both ways. Rounded buttons and panels resize without distorting, strokes + keep their width, and rotation and skew apply after. Nested symbols, text and bitmaps + inside scale normally, as in Animate. When there isn't room for the corners, they shrink + together in proportion. + * While the symbol is open for editing, its four guides are **dashed lines across the + stage**. Drag them with the Selection tool (one undo step per drag), or type their + positions in Properties. + * Every export draws it from the same frames. SVG and Lottie get baked outlines. HTML canvas + export scales such instances as a whole for now and says so in its report. + * XFL and `.fla` import read `scaleGridLeft/Right/Top/Bottom`. Headless: + `symbol.set_scale_grid {symbol?, on?, left?, right?, top?, bottom?}`. * **Library and Properties polish** (ADR 0053, M2). * **Drag Library items onto the stage**: symbols and bitmaps land at the pointer on the active layer at the playhead, a sound goes onto that layer's keyframe; drag several at once. diff --git a/docs/adr/0055-nine-slice-scaling.md b/docs/adr/0055-nine-slice-scaling.md new file mode 100644 index 00000000..b7d525a8 --- /dev/null +++ b/docs/adr/0055-nine-slice-scaling.md @@ -0,0 +1,120 @@ +# ADR 0055: 9-slice scaling for symbols + +* Status: accepted (2026-11-11) +* Relates to: ADR 0045 (editing a symbol in place), ADR 0050 (Library management), ADR 0035 + (XFL corpus and goldens), ADR 0019/0032 (GPU stage), ADR 0028 (HTML canvas export), ADR 0004 + (destructive actions) + +## Context + +Animate's Symbol Properties has **Enable guides for 9-slice scaling**. A movie clip or graphic +symbol then has four guides (two vertical, two horizontal) that cut it into nine cells. Scaling +an instance keeps the four corner cells at their size, stretches the top and bottom edges only +across, the left and right edges only down, and the centre both ways: rounded buttons and +panels resize without their corners distorting. While the symbol is open for editing, the +guides show as dashed lines that can be dragged. Strokes keep their width. Nested symbols, text +and bitmaps inside scale as a whole. Rotation and skew still apply to the whole instance. + +Behaviour was learned from Adobe's public help pages, the XFL attributes of documents we +authored ourselves (`scaleGridLeft`, `scaleGridRight`, `scaleGridTop`, `scaleGridBottom` on +`DOMSymbolItem`) and the general technique as public UI toolkits describe it. No Adobe code, +SDK or asset was used. + +## Decision + +1. **Model.** `Symbol::scale_grid: Option` (`#[serde(default)]`, left out when + `None`, so older files open unchanged and files without guides are byte-identical). A grid + is four coordinates in the symbol's own space (`left ≤ right`, `top ≤ bottom`, finite, + within ±1,000,000). Loading drops a grid that isn't usable, so the symbol scales normally. + +2. **Evaluation stays pure** (`doc::evaluate`, `nine_slice.rs`). Entering an instance of a + symbol with a grid, its transform is decomposed as `T · R · Skew · S`. If `S` is 1 on both + axes nothing changes. Otherwise the symbol's own shapes are drawn through the **9-slice + map** of the symbol's box scaled by `|S|`, and then by `T · R · Skew` (with a flip, if `S` + had one). So rotation and skew apply after slicing, and a flipped instance is sliced by its + magnitude, then mirrored. + * **The box** is the control-point bounds of everything on every keyframe of the symbol + (guide, folder and camera layers left out; strokes don't widen it), so it doesn't move as + the symbol plays. + * **Each axis** is three linear pieces (`geom::slice::Axis`). The box lands where plain + scaling would put it (`k·lo .. k·hi`, about the registration point). The parts outside the + guides keep their size, and the centre gets the rest. **When there is no room for the + corners** (the instance is narrower than the two corners), they share what room there is + in proportion and the centre closes. Nothing turns inside out. Guides outside the box are + clamped into it. + * **Exact geometry.** Inside one cell the map is affine, so a Bézier piece maps exactly by + its control points. `slice_path` cuts each segment at the exact parameters where it + crosses a guide. It splits the segment into monotone runs at the roots of its derivative, + then bisects each run (40 steps; at most three crossings per guide). It then splits by de + Casteljau and maps each piece by its cell. Lines stay lines and curves stay curves of the + same degree. An implied closing line is written out, because it may bend at a guide. A + 100 × 40 rounded rectangle scaled 3× keeps its radius-10 arcs to within flattening + tolerance (tested analytically, and pixel-for-pixel against the unscaled corner by the + CPU oracle). + * **Strokes keep their width.** The item's transform has no 9-slice scale left in it, so + the width is the symbol's own (times a shape's own scale inside the symbol). Linear + gradients follow the map. Radial ones keep their centre on the map, and their radius + scales by the mean scale. + * **Scale as a whole, as in Animate:** nested symbols (they keep the whole transform, so + they move and stretch with the instance), text, and shapes with bitmap fills. Each nested + symbol is sliced by its own grid, if it has one, from its own instance scale. Grids don't + pass to nested symbols. + +3. **Everything sees it through `evaluate`.** The CPU renderer, the GPU stage (its binning is + tested against the oracle on a sliced scene), PNG, GIF, SVG and Lottie draw the sliced + outlines as ordinary display items. SVG and Lottie export baked outlines. Picking, onion skin + and selection work on the same items. **HTML canvas export** places symbols in the browser + at run time (ADR 0028), so its player can't slice them yet: a scaled 9-slice instance there + scales as a whole, and the export's report counts it (*"9-slice scaling (scaled as a + whole)"*). + +4. **One command.** `symbol.set_scale_grid {symbol?, on?, left?, right?, top?, bottom?}` turns + the guides on, turns them off, or moves them. Without `symbol` it acts on the symbol open + for editing, otherwise on the selected instance's symbol. Turning them on puts them a + quarter of the way in from each edge of the box. Moving a guide turns them on. Guides out of + order are refused, not swapped. It is one undo step, or one per drag inside a gesture. It + is in the `symbol` namespace, so plug-ins may call it, and it is in the fuzz. + +5. **Shell.** The checkbox **Enable guides for 9-slice scaling** is in the Library's item + properties (Animate's Symbol Properties), in Properties for a selected instance, and in + Properties while editing the symbol with nothing selected. When it is on, each place also + shows the four positions (`Guides x`, `Guides y`, monospace data, one undo step per drag). While the symbol is open + (ADR 0045), the guides are dashed lines across the whole stage in the theme's `slice_guide` + colour, over a light underlay. The Selection tool drags them (resize cursors, a heavier + line under the pointer). Each drag is one undo step, *Move 9-Slice Guide*. A guide stops at + the other guide of its pair. Edits show in the same frame. + +6. **XFL.** `scaleGridLeft/Right/Top/Bottom` on `DOMSymbolItem` become the grid when all four + are numbers; guides given the wrong way round are put in order. A partial or unreadable set + is reported (*"9-slice guides that aren't usable (left out)"*). The corpus has a + `nineslice` package (panel unscaled, scaled both ways, stretched wide; a nested graphic; a + one-guide symbol) with a golden frame and colour probes. It also opens as a `.fla` (ADR + 0054). + +## Performance + +Slicing costs time per instance per frame: one pass over the symbol's keyframes for the box, +and the cut, which is linear in path size (at most 13 pieces per segment). Unscaled instances +cost nothing more, and their paths stay shared. Sliced paths are made new each frame, as +tweened shapes already are. Measured (release build, this Windows laptop), evaluating 1,000 +instances of the rounded, outlined test panel scaled 3 × 2 takes **60 µs** as plain scaling +and **1.76 ms** sliced: about **1.7 µs per sliced instance**. A typical frame has a handful of +them. A path of more than 1,000,000 commands is mapped point by point instead of cut, so the +work stays bounded. + +## Rejected + +* **Slicing the whole instance's display list after evaluation.** It would slice nested symbols + and bitmaps too, which Animate doesn't do, and it would lose which items are the symbol's + own. +* **Corners scaled to the guides rather than to the box** (the centre scales by the instance + scale exactly, and the instance grows by its corners). The instance would no longer have the + bounds plain scaling gives it, and Free Transform's box would not match what is drawn. +* **Flattening to polygons before mapping.** It would be simpler, but curves would no longer be + curves in SVG and Lottie, and the corners would not stay exact. + +## Not yet + +HTML canvas export slicing (its player), 9-slice for bitmaps (Animate doesn't either), guides +shown in Library previews, snapping guides to artwork, a symbol-wide "scale strokes" option, +and Lottie's native 9-slice (it has none). diff --git a/docs/adr/README.md b/docs/adr/README.md index 0bb33150..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0055 | m2/nine-slice | 9-slice scaling for symbols | diff --git a/docs/roadmap.md b/docs/roadmap.md index 9e5bdb81..440156f3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -17,7 +17,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | -| Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | +| Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported. Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | | Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. | @@ -33,7 +33,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---|---| | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | -| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | +| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | From f78ae40e89e65174b1d23d43b7c1989bfac2eb51 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 04:50:41 -0700 Subject: [PATCH 017/192] feat(doc): colour effect styles as one exact colour transform, rendered, exported and edited everywhere (M2) --- crates/doc/src/camera.rs | 18 +- crates/doc/src/camera_tests.rs | 3 +- crates/doc/src/color_effect.rs | 526 ++++++++++++++++++ crates/doc/src/eval.rs | 23 +- crates/doc/src/eval_tests.rs | 8 +- crates/doc/src/lib.rs | 42 +- crates/doc/src/motion.rs | 186 ++++++- crates/doc/src/player.rs | 2 +- crates/engine/src/cmds_camera.rs | 2 +- crates/engine/src/cmds_draw.rs | 84 ++- crates/engine/src/cmds_file.rs | 2 +- crates/engine/src/cmds_motion.rs | 15 +- crates/engine/src/cmds_plugin.rs | 3 +- crates/engine/src/cmds_timeline.rs | 2 +- crates/engine/src/editing.rs | 2 +- crates/engine/src/lib.rs | 24 + crates/engine/src/motion_tests.rs | 2 +- crates/engine/src/multi_tests.rs | 4 +- crates/engine/src/onion.rs | 6 +- crates/engine/src/onion_tests.rs | 18 +- crates/engine/src/selection_tests.rs | 2 +- crates/engine/tests/xfl_corpus.rs | 21 +- crates/gpu/examples/gpu_bench.rs | 6 +- crates/gpu/src/binning.rs | 40 +- crates/gpu/src/fine.wgsl | 29 +- crates/gpu/src/lib.rs | 4 +- crates/gpu/src/tests.rs | 22 +- crates/render/src/html.rs | 39 +- crates/render/src/html/canvas.js | 35 +- crates/render/src/html/player.js | 38 +- crates/render/src/html_tests.rs | 13 +- crates/render/src/lib.rs | 10 +- crates/render/src/paint.rs | 34 +- crates/render/src/svg.rs | 43 +- crates/xfl/src/import.rs | 45 +- crates/xfl/src/tests.rs | 2 +- crates/xfl/tests/corpus.rs | 36 +- .../xfl/tests/corpus/colour/DOMDocument.xml | 60 ++ .../xfl/tests/corpus/colour/LIBRARY/Chip.xml | 19 + .../xfl/tests/corpus/colour/LIBRARY/Pair.xml | 21 + crates/xfl/tests/corpus/colour/colour.xfl | 1 + .../tests/corpus/colour/golden/frame-000.png | Bin 0 -> 2656 bytes .../tests/corpus/colour/golden/frame-006.png | Bin 0 -> 2782 bytes .../tests/corpus/colour/golden/frame-012.png | Bin 0 -> 2787 bytes .../tests/corpus/symbols/golden/frame-000.png | Bin 6606 -> 6586 bytes .../tests/corpus/symbols/golden/frame-005.png | Bin 6976 -> 6956 bytes .../tests/corpus/tweens/golden/frame-006.png | Bin 2823 -> 2829 bytes src/a11y.rs | 12 + src/app.rs | 3 + src/i18n/tests.rs | 16 + src/mixed.rs | 83 ++- src/motion_editor.rs | 51 +- src/panels.rs | 87 ++- 53 files changed, 1448 insertions(+), 296 deletions(-) create mode 100644 crates/doc/src/color_effect.rs create mode 100644 crates/xfl/tests/corpus/colour/DOMDocument.xml create mode 100644 crates/xfl/tests/corpus/colour/LIBRARY/Chip.xml create mode 100644 crates/xfl/tests/corpus/colour/LIBRARY/Pair.xml create mode 100644 crates/xfl/tests/corpus/colour/colour.xfl create mode 100644 crates/xfl/tests/corpus/colour/golden/frame-000.png create mode 100644 crates/xfl/tests/corpus/colour/golden/frame-006.png create mode 100644 crates/xfl/tests/corpus/colour/golden/frame-012.png diff --git a/crates/doc/src/camera.rs b/crates/doc/src/camera.rs index 2b6385a7..f3a78f65 100644 --- a/crates/doc/src/camera.rs +++ b/crates/doc/src/camera.rs @@ -11,7 +11,7 @@ //! keeping its size (so a layer at depth 0 moves with the stage, a far background barely moves). //! Everything here is pure: the camera at a frame is a function of the document. -use crate::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements}; +use crate::{ColorEffect, ColorTransform, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements}; use anicraft_geom::{Affine, Decomposed, Vec2}; /// Smallest and largest camera zoom (5 % to 2,000 %). @@ -55,13 +55,17 @@ impl Camera { let center = Vec2::new(fin(d.tx, rest.center.x), fin(d.ty, rest.center.y)); let zoom = fin(d.sx.abs(), 1.0).clamp(MIN_ZOOM, MAX_ZOOM); let rotation = fin(d.rotation, 0.0); - let c = el.color; - Camera { center, zoom, rotation, tint: c.tint.sanitized(), tint_amount: fin(c.tint_amount, 0.0).clamp(0.0, 1.0) } + // The camera's colour effect is a tint (ADR 0027); other styles leave the view as it is. + let (tint, amount) = match el.color { + ColorEffect::Tint { color, amount } => (color.sanitized(), fin(amount, 0.0).clamp(0.0, 1.0)), + _ => (Rgba::WHITE, 0.0), + }; + Camera { center, zoom, rotation, tint, tint_amount: amount } } /// The camera element holding this camera (for commands). pub fn to_element(&self, id: ElementId) -> Element { - Element { id, name: String::new(), transform: self.transform(), color: ColorEffect { alpha: 1.0, tint: self.tint, tint_amount: self.tint_amount }, kind: ElementKind::Camera } + Element { id, name: String::new(), transform: self.transform(), color: ColorEffect::Tint { color: self.tint, amount: self.tint_amount }, kind: ElementKind::Camera } } /// The camera on the stage: `T(centre) · R(rotation) · S(zoom)`. @@ -70,8 +74,8 @@ impl Camera { } /// The colour effect the camera puts on everything it shows. - pub fn color(&self) -> ColorEffect { - ColorEffect { alpha: 1.0, tint: self.tint, tint_amount: self.tint_amount } + pub fn color(&self) -> ColorTransform { + ColorTransform::tint(self.tint, self.tint_amount) } /// Stage space → output space for a layer `depth` pixels behind the stage: the camera's @@ -219,7 +223,7 @@ mod tests { fn hostile_cameras_stay_finite() { let mut el = Camera::rest(&stage()).to_element(ElementId(1)); el.transform = Affine { m: [f32::NAN, 0.0, 0.0, f32::INFINITY, f32::NAN, 1e30] }; - el.color.tint_amount = f32::NAN; + el.color = ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN }; let c = Camera::of_element(&el, &stage()); assert!(c.view(&stage(), 0.0).is_finite()); assert!((MIN_ZOOM..=MAX_ZOOM).contains(&c.zoom)); diff --git a/crates/doc/src/camera_tests.rs b/crates/doc/src/camera_tests.rs index 7854e915..7c0ba5a9 100644 --- a/crates/doc/src/camera_tests.rs +++ b/crates/doc/src/camera_tests.rs @@ -70,8 +70,7 @@ fn camera_rotation_and_tint_apply_to_the_whole_view() { // Stage point (105, 50) is right of the centre; the camera turned clockwise, so it shows // above the middle. In the square's space that point is (10, 50). assert!(i.transform.apply(Vec2::new(10.0, 50.0)).distance(Vec2::new(100.0, 45.0)) < 1e-3); - assert_eq!(i.color.tint_amount, 0.5); - assert_eq!(i.color.tint, Rgba::hex(0xff0000)); + assert_eq!(i.color, crate::ColorTransform::tint(Rgba::hex(0xff0000), 0.5)); } #[test] diff --git a/crates/doc/src/color_effect.rs b/crates/doc/src/color_effect.rs new file mode 100644 index 00000000..ad099ad3 --- /dev/null +++ b/crates/doc/src/color_effect.rs @@ -0,0 +1,526 @@ +//! Colour effects (ADR 0056): what Animate's Properties calls an instance's colour effect +//! *style* (None, Brightness, Tint, Advanced, Alpha), and the one colour transform every style +//! is (a multiply and an offset per channel). +//! +//! An element stores its [`ColorEffect`] as authored, so Properties shows the style and values +//! the artist chose (a tint keeps its colour at 0 %). Everything that draws works on its +//! [`ColorTransform`]: nested instances, the camera and onion skin compose their transforms +//! exactly (`concat` is the composition of the two maps), and every renderer applies the same +//! arithmetic to straight colour: `c ↦ clamp(c·multiply + offset, 0, 1)`. +//! +//! Brightness `b` is a tint towards white (`b > 0`) or black (`b < 0`) by `|b|`; a tint of +//! colour `t` by amount `k` multiplies each colour channel by `1 − k` and adds `k·t`; alpha +//! multiplies the alpha channel; Advanced is the transform itself (Animate's per-channel +//! percent and −255..255 offset, here as fractions: offset 1 is 255). + +use crate::Rgba; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// A colour transform on straight (not premultiplied) colour: channel `i` (red, green, blue, +/// alpha) becomes `clamp(c·mul[i] + add[i], 0, 1)`. Offsets are fractions of the full range. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ColorTransform { + pub mul: [f32; 4], + pub add: [f32; 4], +} + +impl Default for ColorTransform { + fn default() -> Self { + ColorTransform::IDENTITY + } +} + +/// Animate's Advanced ranges: multipliers −100..=100 %, offsets −255..=255. +pub const ADVANCED_MUL: std::ops::RangeInclusive = -1.0..=1.0; +pub const ADVANCED_ADD: std::ops::RangeInclusive = -1.0..=1.0; + +fn fin(v: f32, or: f32) -> f32 { + if v.is_finite() { v } else { or } +} + +impl ColorTransform { + pub const IDENTITY: ColorTransform = ColorTransform { mul: [1.0; 4], add: [0.0; 4] }; + + /// Multiplies alpha by `a`. + pub fn alpha(a: f32) -> ColorTransform { + ColorTransform { mul: [1.0, 1.0, 1.0, a], add: [0.0; 4] } + } + /// Mixes colour `t` in by `k` (alpha untouched). + pub fn tint(t: Rgba, k: f32) -> ColorTransform { + let j = 1.0 - k; + ColorTransform { mul: [j, j, j, 1.0], add: [k * t.r, k * t.g, k * t.b, 0.0] } + } + /// Brightness `b` in −1..=1: a tint towards white or black by `|b|`. + pub fn brightness(b: f32) -> ColorTransform { + if b >= 0.0 { ColorTransform::tint(Rgba::WHITE, b) } else { ColorTransform::tint(Rgba::BLACK, -b) } + } + + pub fn is_identity(&self) -> bool { + *self == ColorTransform::IDENTITY + } + + /// `self` applied after `inner`: the effect of `inner` nested inside `self`. Exact (no clamp + /// between the two), so composing then applying is applying one then the other on colours + /// that stay in range. + pub fn concat(&self, inner: &ColorTransform) -> ColorTransform { + let mut out = ColorTransform::IDENTITY; + for i in 0..4 { + out.mul[i] = self.mul[i] * inner.mul[i]; + out.add[i] = self.mul[i] * inner.add[i] + self.add[i]; + } + out + } + + pub fn lerp(&self, o: &ColorTransform, t: f32) -> ColorTransform { + let mut out = ColorTransform::IDENTITY; + for i in 0..4 { + out.mul[i] = anicraft_geom::lerp(self.mul[i], o.mul[i], t); + out.add[i] = anicraft_geom::lerp(self.add[i], o.add[i], t); + } + out + } + + /// Non-finite values drawn as a channel of 0 (as a NaN colour always was). + pub fn sanitized(&self) -> ColorTransform { + let mut out = *self; + for i in 0..4 { + if !(out.mul[i].is_finite() && out.add[i].is_finite()) { + out.mul[i] = 0.0; + out.add[i] = 0.0; + } + } + out + } + + /// The transform applied to straight colour `c`, clamped to `0..=1` (NaN to 0). + pub fn apply(&self, c: Rgba) -> Rgba { + let f = self.sanitized(); + let ch = |v: f32, i: usize| { + let x = fin(v, 0.0) * f.mul[i] + f.add[i]; + if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 } + }; + Rgba::new(ch(c.r, 0), ch(c.g, 1), ch(c.b, 2), ch(c.a, 3)) + } + + /// The alpha multiplier when alpha is only multiplied (no alpha offset): what can fade a + /// whole group at once. + pub fn alpha_factor(&self) -> Option { + (self.add[3] == 0.0).then(|| fin(self.mul[3], 0.0).clamp(0.0, 1.0)) + } + + /// The same transform with alpha untouched. + pub fn without_alpha(&self) -> ColorTransform { + let mut out = *self; + out.mul[3] = 1.0; + out.add[3] = 0.0; + out + } + + /// Whether colour channels change (anything beyond alpha). + pub fn changes_colour(&self) -> bool { + self.mul[..3].iter().any(|m| *m != 1.0) || self.add[..3].iter().any(|a| *a != 0.0) + } + + /// The alpha multiplier as an opacity estimate `0..=1` (picking, outlines). + pub fn opacity(&self) -> f32 { + fin(self.mul[3] + self.add[3], 0.0).clamp(0.0, 1.0) + } +} + +/// The colour effect styles of Properties' Style menu, in menu order. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ColorStyle { + None, + Brightness, + Tint, + Advanced, + Alpha, +} + +impl ColorStyle { + pub const ALL: [ColorStyle; 5] = [ColorStyle::None, ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha]; + + /// The name used in files and commands. + pub fn key(self) -> &'static str { + match self { + ColorStyle::None => "none", + ColorStyle::Brightness => "brightness", + ColorStyle::Tint => "tint", + ColorStyle::Advanced => "advanced", + ColorStyle::Alpha => "alpha", + } + } + pub fn label(self) -> &'static str { + match self { + ColorStyle::None => "None", + ColorStyle::Brightness => "Brightness", + ColorStyle::Tint => "Tint", + ColorStyle::Advanced => "Advanced", + ColorStyle::Alpha => "Alpha", + } + } + pub fn from_key(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase(); + ColorStyle::ALL.into_iter().find(|x| x.key() == s) + } +} + +/// An element's colour effect, as authored: one style and its values. Draw it through +/// [`ColorEffect::transform`]. +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub enum ColorEffect { + #[default] + None, + /// Brightness −1..=1 (−100..=100 %). + Brightness(f32), + /// Tint colour (opaque) and amount 0..=1. + Tint { color: Rgba, amount: f32 }, + /// Per-channel multiply and offset (Animate's Advanced). + Advanced(ColorTransform), + /// Alpha multiplier 0..=1. + Alpha(f32), +} + +impl ColorEffect { + pub fn style(&self) -> ColorStyle { + match self { + ColorEffect::None => ColorStyle::None, + ColorEffect::Brightness(_) => ColorStyle::Brightness, + ColorEffect::Tint { .. } => ColorStyle::Tint, + ColorEffect::Advanced(_) => ColorStyle::Advanced, + ColorEffect::Alpha(_) => ColorStyle::Alpha, + } + } + + /// What it does to colour (its values clamped into the style's range first). + pub fn transform(&self) -> ColorTransform { + match self.sanitized() { + ColorEffect::None => ColorTransform::IDENTITY, + ColorEffect::Brightness(b) => ColorTransform::brightness(b), + ColorEffect::Tint { color, amount } => ColorTransform::tint(color, amount), + ColorEffect::Advanced(t) => t, + ColorEffect::Alpha(a) => ColorTransform::alpha(a), + } + } + + /// The values clamped into each style's range, non-finite ones to the style's rest value. + pub fn sanitized(&self) -> ColorEffect { + match *self { + ColorEffect::None => ColorEffect::None, + ColorEffect::Brightness(b) => ColorEffect::Brightness(fin(b, 0.0).clamp(-1.0, 1.0)), + ColorEffect::Tint { color, amount } => ColorEffect::Tint { color: color.sanitized().with_alpha(1.0), amount: fin(amount, 0.0).clamp(0.0, 1.0) }, + ColorEffect::Advanced(t) => { + let mut o = t; + for i in 0..4 { + o.mul[i] = fin(t.mul[i], 1.0).clamp(*ADVANCED_MUL.start(), *ADVANCED_MUL.end()); + o.add[i] = fin(t.add[i], 0.0).clamp(*ADVANCED_ADD.start(), *ADVANCED_ADD.end()); + } + ColorEffect::Advanced(o) + } + ColorEffect::Alpha(a) => ColorEffect::Alpha(fin(a, 1.0).clamp(0.0, 1.0)), + } + } + + /// The alpha multiplier the effect has (1 for styles that leave alpha alone). + pub fn alpha(&self) -> f32 { + self.transform().mul[3] + } + + /// The effect with its alpha multiplier set to `a`, the rest kept (what ActionScript's + /// `alpha` and `element.set_alpha` do): None and Alpha become Alpha(a); Advanced keeps + /// its other channels; Brightness and Tint become Advanced when `a` isn't 1. + pub fn with_alpha(&self, a: f32) -> ColorEffect { + match *self { + ColorEffect::None | ColorEffect::Alpha(_) => ColorEffect::Alpha(a), + ColorEffect::Advanced(mut t) => { + t.mul[3] = a; + ColorEffect::Advanced(t) + } + ColorEffect::Brightness(_) | ColorEffect::Tint { .. } if a == 1.0 => *self, + ColorEffect::Brightness(_) | ColorEffect::Tint { .. } => { + let mut t = self.transform(); + t.mul[3] = a; + ColorEffect::Advanced(t) + } + } + } + + /// The effect in `style`, as close to this one as that style can be: Advanced is exactly + /// this transform; Alpha keeps the alpha multiplier; a tint keeps its colour; Brightness and + /// Tint otherwise start where they change nothing (the look doesn't jump when the style + /// changes, except to None). + pub fn to_style(&self, style: ColorStyle) -> ColorEffect { + if self.style() == style { + return *self; + } + match style { + ColorStyle::None => ColorEffect::None, + ColorStyle::Advanced => ColorEffect::Advanced(self.transform()), + ColorStyle::Alpha => ColorEffect::Alpha(fin(self.alpha(), 1.0).clamp(0.0, 1.0)), + ColorStyle::Brightness => ColorEffect::Brightness(0.0), + ColorStyle::Tint => ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 }, + } + } + + /// `inner` nested inside `self` as one effect (Break Apart): the other when either is None, + /// alphas multiplied, else the composed transform as Advanced. + pub fn nested(&self, inner: &ColorEffect) -> ColorEffect { + match (self, inner) { + (ColorEffect::None, x) | (x, ColorEffect::None) => *x, + (ColorEffect::Alpha(a), ColorEffect::Alpha(b)) => ColorEffect::Alpha(a * b), + (o, i) => ColorEffect::Advanced(o.transform().concat(&i.transform())), + } + } + + /// Alpha `a`, or None at full opacity. + pub fn opacity(a: f32) -> ColorEffect { + if a < 1.0 { ColorEffect::Alpha(a) } else { ColorEffect::None } + } + + /// The classic tween between two effects: within one style its values travel (a tint's + /// colour and amount); None meets any style as that style's rest value; any other change of + /// style travels in the Advanced space (multiplies and offsets), as in Animate. + pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect { + use anicraft_geom::lerp; + let rest = |s: ColorStyle| ColorEffect::None.to_style(s); + let (a, b) = match (self, o) { + (ColorEffect::None, ColorEffect::None) => return ColorEffect::None, + (ColorEffect::None, x) if x.style() != ColorStyle::Advanced => (rest(x.style()), *x), + (x, ColorEffect::None) if x.style() != ColorStyle::Advanced => (*x, rest(x.style())), + (x, y) => (*x, *y), + }; + // A tint meeting None keeps its colour all the way. + let (a, b) = match (a, b) { + (ColorEffect::Tint { amount, .. }, ColorEffect::Tint { color, amount: k }) if self.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }), + (ColorEffect::Tint { color, amount }, ColorEffect::Tint { amount: k, .. }) if o.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }), + p => p, + }; + match (a, b) { + (ColorEffect::Brightness(x), ColorEffect::Brightness(y)) => ColorEffect::Brightness(lerp(x, y, t)), + (ColorEffect::Alpha(x), ColorEffect::Alpha(y)) => ColorEffect::Alpha(lerp(x, y, t)), + (ColorEffect::Tint { color: c1, amount: k1 }, ColorEffect::Tint { color: c2, amount: k2 }) => ColorEffect::Tint { color: c1.lerp(c2, t), amount: lerp(k1, k2, t) }, + (x, y) => ColorEffect::Advanced(x.transform().lerp(&y.transform(), t)), + } + } + + /// The effect several families make together (a motion tween keying more than one, or an + /// older file's alpha with a tint): the one family when only one is in use, else Advanced + /// with them composed (alpha outermost, then brightness, tint, advanced). + pub fn compose(alpha: Option, brightness: Option, tint: Option<(Rgba, f32)>, advanced: Option) -> ColorEffect { + let n = usize::from(alpha.is_some()) + usize::from(brightness.is_some()) + usize::from(tint.is_some()) + usize::from(advanced.is_some()); + if n == 1 { + if let Some(a) = alpha { + return ColorEffect::Alpha(a); + } + if let Some(b) = brightness { + return ColorEffect::Brightness(b); + } + if let Some((color, amount)) = tint { + return ColorEffect::Tint { color, amount }; + } + if let Some(t) = advanced { + return ColorEffect::Advanced(t); + } + } + if n == 0 { + return ColorEffect::None; + } + let mut t = advanced.unwrap_or(ColorTransform::IDENTITY); + if let Some((c, k)) = tint { + t = ColorTransform::tint(c, k).concat(&t); + } + if let Some(b) = brightness { + t = ColorTransform::brightness(b).concat(&t); + } + if let Some(a) = alpha { + t = ColorTransform::alpha(a).concat(&t); + } + ColorEffect::Advanced(t) + } +} + +// ----- files --------------------------------------------------------------------------------- +// +// Every effect is written with the fields older AniCraft files have (`alpha`, `tint`, +// `tint_amount`: the look as near as they can say it), so None, Alpha and Tint effects are +// written exactly as before. `style` (and `brightness`, `multiply`, `offset`) are added only +// when those fields alone would read back as something else. A file without `style` reads as +// it always looked: a tint, an alpha, both (Advanced), or none. + +fn one() -> f32 { + 1.0 +} +fn white() -> Rgba { + Rgba::WHITE +} + +#[derive(Serialize, Deserialize)] +struct Wire { + #[serde(default = "one")] + alpha: f32, + #[serde(default = "white")] + tint: Rgba, + #[serde(default)] + tint_amount: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + style: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + brightness: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + multiply: Option<[f32; 4]>, + #[serde(default, skip_serializing_if = "Option::is_none")] + offset: Option<[f32; 4]>, +} + +/// What the legacy fields alone say. +fn legacy(alpha: f32, tint: Rgba, amount: f32) -> ColorEffect { + // Older builds clamped these where they drew them. + let (alpha, amount) = (fin(alpha, 1.0).clamp(0.0, 1.0), fin(amount, 0.0).clamp(0.0, 1.0)); + let a = (alpha != 1.0).then_some(alpha); + let t = (amount != 0.0).then_some((tint, amount)); + ColorEffect::compose(a, None, t, None) +} + +impl Serialize for ColorEffect { + fn serialize(&self, s: S) -> Result { + let mut w = Wire { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0, style: None, brightness: None, multiply: None, offset: None }; + match *self { + ColorEffect::None => {} + ColorEffect::Alpha(a) => w.alpha = a, + ColorEffect::Tint { color, amount } => (w.tint, w.tint_amount) = (color, amount), + ColorEffect::Brightness(b) => { + (w.tint, w.tint_amount) = (if b >= 0.0 { Rgba::WHITE } else { Rgba::BLACK }, b.abs()); + w.brightness = Some(b); + } + ColorEffect::Advanced(t) => { + w.alpha = t.mul[3]; + (w.multiply, w.offset) = (Some(t.mul), Some(t.add)); + } + } + if legacy(w.alpha, w.tint, w.tint_amount) != *self { + w.style = Some(self.style().key().to_string()); + } + w.serialize(s) + } +} + +impl<'de> Deserialize<'de> for ColorEffect { + fn deserialize>(d: D) -> Result { + let w = Wire::deserialize(d)?; + let fx = match w.style.as_deref().and_then(ColorStyle::from_key) { + None => legacy(w.alpha, w.tint, w.tint_amount), + Some(ColorStyle::None) => ColorEffect::None, + Some(ColorStyle::Alpha) => ColorEffect::Alpha(w.alpha), + Some(ColorStyle::Tint) => ColorEffect::Tint { color: w.tint, amount: w.tint_amount }, + Some(ColorStyle::Brightness) => ColorEffect::Brightness(w.brightness.unwrap_or(0.0)), + Some(ColorStyle::Advanced) => ColorEffect::Advanced(ColorTransform { mul: w.multiply.unwrap_or([1.0; 4]), add: w.offset.unwrap_or([0.0; 4]) }), + }; + Ok(fx.sanitized()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: Rgba, b: Rgba) -> bool { + (a.r - b.r).abs() < 1e-5 && (a.g - b.g).abs() < 1e-5 && (a.b - b.b).abs() < 1e-5 && (a.a - b.a).abs() < 1e-5 + } + + #[test] + fn styles_are_the_transforms_animate_documents() { + let c = Rgba::new(0.4, 0.2, 0.8, 1.0); + // Brightness +60 %: towards white; −50 %: towards black. + assert!(close(ColorEffect::Brightness(0.6).transform().apply(c), Rgba::new(0.4 * 0.4 + 0.6, 0.2 * 0.4 + 0.6, 0.8 * 0.4 + 0.6, 1.0))); + assert!(close(ColorEffect::Brightness(-0.5).transform().apply(c), Rgba::new(0.2, 0.1, 0.4, 1.0))); + // Tint 25 % red. + let t = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.25 }.transform().apply(c); + assert!(close(t, Rgba::new(0.4 * 0.75 + 0.25, 0.15, 0.6, 1.0))); + // Advanced: red ×50 %, green +51 (0.2), alpha ×80 % −25.5 (−0.1); clamped. + let adv = ColorTransform { mul: [0.5, 1.0, 1.0, 0.8], add: [0.0, 0.2, 0.5, -0.1] }; + assert!(close(adv.apply(c), Rgba::new(0.2, 0.4, 1.0, 0.7))); + assert!(close(ColorEffect::Alpha(0.3).transform().apply(c), c.with_alpha(0.3))); + } + + #[test] + fn composition_is_exact() { + let outer = ColorTransform::tint(Rgba::new(0.0, 0.5, 1.0, 1.0), 0.4); + let inner = ColorTransform { mul: [0.5, -0.2, 0.9, 0.7], add: [0.1, 0.6, 0.0, 0.05] }; + let c = Rgba::new(0.3, 0.6, 0.2, 0.9); + assert!(close(outer.concat(&inner).apply(c), outer.apply(inner.apply(c)))); + assert_eq!(ColorTransform::IDENTITY.concat(&inner), inner); + assert_eq!(inner.concat(&ColorTransform::IDENTITY), inner); + } + + #[test] + fn nan_draws_a_zero_channel() { + let t = ColorTransform { mul: [f32::NAN, 1.0, 1.0, 1.0], add: [0.0; 4] }; + assert_eq!(t.apply(Rgba::WHITE), Rgba::new(0.0, 1.0, 1.0, 1.0)); + assert_eq!(ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN }.sanitized(), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 }); + } + + #[test] + fn tweens_within_a_style_and_across_styles() { + let red = Rgba::new(1.0, 0.0, 0.0, 1.0); + let blue = Rgba::new(0.0, 0.0, 1.0, 1.0); + assert_eq!(ColorEffect::Alpha(1.0).lerp(&ColorEffect::Alpha(0.0), 0.25), ColorEffect::Alpha(0.75)); + assert_eq!(ColorEffect::None.lerp(&ColorEffect::Brightness(-1.0), 0.5), ColorEffect::Brightness(-0.5)); + assert_eq!(ColorEffect::None.lerp(&ColorEffect::Tint { color: red, amount: 1.0 }, 0.5), ColorEffect::Tint { color: red, amount: 0.5 }); + assert_eq!(ColorEffect::Tint { color: red, amount: 1.0 }.lerp(&ColorEffect::Tint { color: blue, amount: 1.0 }, 0.5), ColorEffect::Tint { color: Rgba::new(0.5, 0.0, 0.5, 1.0), amount: 1.0 }); + // A style change travels in the advanced space: halfway between the two transforms. + let a = ColorEffect::Tint { color: red, amount: 1.0 }; + let b = ColorEffect::Alpha(0.5); + let mid = a.lerp(&b, 0.5); + assert_eq!(mid.style(), ColorStyle::Advanced); + assert_eq!(mid.transform(), a.transform().lerp(&b.transform(), 0.5)); + // The ends look like the keyframes. + assert_eq!(a.lerp(&b, 0.0).transform(), a.transform()); + assert_eq!(a.lerp(&b, 1.0).transform(), b.transform()); + } + + #[test] + fn style_changes_keep_the_look_where_they_can() { + let fx = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.4 }; + assert_eq!(fx.to_style(ColorStyle::Advanced).transform(), fx.transform()); + assert_eq!(ColorEffect::Alpha(0.3).to_style(ColorStyle::Advanced).alpha(), 0.3); + assert_eq!(ColorEffect::Advanced(ColorTransform::alpha(0.3)).to_style(ColorStyle::Alpha), ColorEffect::Alpha(0.3)); + assert!(fx.to_style(ColorStyle::Brightness).transform().is_identity()); + assert_eq!(fx.with_alpha(0.5).transform(), ColorTransform::alpha(0.5).concat(&fx.transform())); + assert_eq!(fx.with_alpha(1.0), fx); + assert_eq!(ColorEffect::None.with_alpha(0.2), ColorEffect::Alpha(0.2)); + } + + #[test] + fn older_files_read_as_they_looked_and_simple_effects_write_as_before() { + let read = |s: &str| serde_json::from_str::(s).unwrap(); + let white = r#""tint":{"r":1.0,"g":1.0,"b":1.0,"a":1.0}"#; + assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#)), ColorEffect::None); + assert_eq!(read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#)), ColorEffect::Alpha(0.5)); + assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.25}}"#)), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.25 }); + let both = read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.25}}"#)); + assert_eq!(both.transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::WHITE, 0.25))); + // Byte for byte as before. + assert_eq!(serde_json::to_string(&ColorEffect::None).unwrap(), format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#)); + assert_eq!(serde_json::to_string(&ColorEffect::Alpha(0.5)).unwrap(), format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#)); + for fx in [ + ColorEffect::None, + ColorEffect::Alpha(1.0), + ColorEffect::Alpha(0.25), + ColorEffect::Brightness(-0.5), + ColorEffect::Brightness(0.0), + ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.0 }, + ColorEffect::Tint { color: Rgba::new(0.0, 0.5, 1.0, 1.0), amount: 0.75 }, + ColorEffect::Advanced(ColorTransform { mul: [0.5, -1.0, 1.0, 0.75], add: [0.25, 0.0, -0.5, 0.125] }), + ColorEffect::Advanced(ColorTransform::IDENTITY), + ] { + let json = serde_json::to_string(&fx).unwrap(); + assert_eq!(read(&json), fx, "{json}"); + } + // Brightness still reads, in older builds, as the tint it looks like. + let json = serde_json::to_string(&ColorEffect::Brightness(-0.5)).unwrap(); + assert!(json.contains(r#""tint_amount":0.5"#) && json.contains(r#""style":"brightness""#), "{json}"); + // Out-of-range values in a file are clamped; an unknown style reads as the legacy fields. + assert_eq!(read(r#"{"style":"brightness","brightness":7}"#), ColorEffect::Brightness(1.0)); + assert_eq!(read(r#"{"style":"sepia","alpha":0.5}"#), ColorEffect::Alpha(0.5)); + } +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 8fb0a447..2b912a80 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -2,7 +2,7 @@ use crate::camera::Camera; use crate::player::PlayerState; -use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind}; +use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind}; use anicraft_geom::walk::PathWalk; use anicraft_geom::{Affine, FillRule, Path}; use std::borrow::Cow; @@ -20,7 +20,8 @@ pub struct DisplayItem { pub fill: Option, pub stroke: Option, pub fill_rule: FillRule, - pub color: ColorEffect, + /// The colour transform of every instance around it, composed (ADR 0056). + pub color: ColorTransform, /// The top-level layer and element this item came from (for picking). pub layer: LayerId, pub element: ElementId, @@ -32,7 +33,7 @@ pub struct DisplayItem { pub masks: Option, /// Guide artwork: shown while editing, never in output. pub guide: bool, - /// The innermost group this item fades with (see [`DisplayList::groups`]); `color.alpha` + /// The innermost group this item fades with (see [`DisplayList::groups`]); `color` /// leaves out the groups' opacity. pub group: Option, /// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied). @@ -73,7 +74,7 @@ impl DisplayList { /// The opacity an item ends up with: its own times every group's it is in (what an item /// looks like when nothing overlaps it; also what picking and outlines use). pub fn effective_alpha(&self, item: &DisplayItem) -> f32 { - let mut a = item.color.alpha; + let mut a = item.color.opacity(); let mut g = item.group; for _ in 0..self.groups.len() { let Some(id) = g else { break }; @@ -293,7 +294,7 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft struct Ctx { /// Local → stage transform and colour effect of the enclosing instance. xf: Affine, - color: ColorEffect, + color: ColorTransform, depth: usize, /// The top-level layer and element everything inside belongs to (for picking). root: Option<(LayerId, ElementId)>, @@ -313,7 +314,7 @@ struct Ctx { impl Ctx { fn top(xf: Affine) -> Ctx { - Ctx { xf, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None } + Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None } } /// A main timeline seen through `camera`: its tint colours everything. @@ -433,7 +434,8 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut }; let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id)); let xf = layer_xf.mul(&el.transform); - let color = cx.color.concat(&el.color); + let fx = el.color.transform(); + let color = cx.color.concat(&fx); match &el.kind { ElementKind::Shape(s) => out.items.push(DisplayItem { path: s.path.clone(), @@ -495,11 +497,14 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut // group at full opacity, and the group blends at the instance's alpha. (Mask // artwork ignores opacity, so it never needs one.) // A blend mode composites the instance on its own too, then blends it. - let fade = el.color.alpha.clamp(0.0, 1.0); + // An alpha offset (Advanced) changes each item's alpha on its own: it stays + // in the items' transform, and the group (for a blend or filters) is opaque. + let fade = fx.alpha_factor().unwrap_or(1.0); let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || !filters.is_empty()) { let gid = out.groups.len() as u32; out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: filters.iter().map(crate::Filter::sanitized).collect(), clip }); - (cx.color.concat(&ColorEffect { alpha: 1.0, ..el.color }), Some(gid)) + let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx }; + (cx.color.concat(&inner), Some(gid)) } else { (color, cx.group) }; diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index e2d27250..5a012336 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::{Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind}; +use crate::{ColorEffect, Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind}; fn shape_el(id: u64, x: f32) -> Element { Element { @@ -93,7 +93,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { id: ElementId(60), name: String::new(), transform: Affine::translate(100.0, 0.0), - color: ColorEffect { alpha: 0.5, ..Default::default() }, + color: ColorEffect::Alpha(0.5), kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, }, ); @@ -101,7 +101,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { assert_eq!(dl.items.len(), MAX_SYMBOL_DEPTH); assert_eq!(dl.items[0].transform.translation().x, 100.0); // The instance's opacity is its group's: it fades as one. - assert_eq!((dl.items[0].color.alpha, dl.effective_alpha(&dl.items[0])), (1.0, 0.5)); + assert_eq!((dl.items[0].color.mul[3], dl.effective_alpha(&dl.items[0])), (1.0, 0.5)); assert_eq!(dl.groups.len(), 1); assert!(dl.items.iter().all(|i| i.element == ElementId(60))); } @@ -352,7 +352,7 @@ fn a_motion_tween_drives_each_property_on_its_own_curve() { let d = motion_doc(); let at = |f| { let dl = evaluate(&d, f); - (dl.items[0].transform.translation().x, dl.items[0].color.alpha) + (dl.items[0].transform.translation().x, dl.items[0].color.mul[3]) }; assert_eq!(at(0), (0.0, 1.0)); // X eases in over 0..12 (a quarter of the way at half time); alpha runs linearly over 0..23. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 258e5431..da4eb5e7 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -9,6 +9,7 @@ pub use anicraft_actions as actions; pub mod armature; mod bitmap; +mod color_effect; pub mod camera; mod filter; mod easing; @@ -26,9 +27,10 @@ pub mod sound; pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; pub use easing::Easing; +pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform}; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; pub use library::{FolderId, LibraryEntry, LibraryFolder, LibraryItem, LibraryTree, NameError}; -pub use motion::{MotionTween, OnPath, Pin, PinError, Property, PropertyKey, Props, Track, motion_path}; +pub use motion::{MotionTween, OnPath, PROPERTIES, Pin, PinError, Property, PropertyKey, Props, Track, motion_path}; pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync}; pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle}; @@ -463,44 +465,6 @@ pub struct TextBlock { pub box_height: f32, } -/// Colour effect applied to an element and everything inside it. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct ColorEffect { - /// Alpha multiplier `0..=1`. - pub alpha: f32, - /// Tint colour mixed in by `tint_amount`. - pub tint: Rgba, - pub tint_amount: f32, -} - -impl Default for ColorEffect { - fn default() -> Self { - ColorEffect { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0 } - } -} - -impl ColorEffect { - /// Effect of `inner` nested inside `self`. - pub fn concat(&self, inner: &ColorEffect) -> ColorEffect { - // Tints compose by keeping the stronger one; alpha multiplies. - let (tint, amount) = if inner.tint_amount >= self.tint_amount { (inner.tint, inner.tint_amount) } else { (self.tint, self.tint_amount) }; - ColorEffect { alpha: self.alpha * inner.alpha, tint, tint_amount: amount } - } - pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect { - ColorEffect { - alpha: anicraft_geom::lerp(self.alpha, o.alpha, t), - tint: self.tint.lerp(o.tint, t), - tint_amount: anicraft_geom::lerp(self.tint_amount, o.tint_amount, t), - } - } - pub fn apply(&self, c: Rgba) -> Rgba { - let k = self.tint_amount.clamp(0.0, 1.0); - let mut out = c.lerp(self.tint.with_alpha(c.a), k); - out.a = c.a * self.alpha.clamp(0.0, 1.0); - out - } -} - /// An instance on a keyframe. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Element { diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index bbe806a3..685d5ae6 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -2,7 +2,7 @@ //! //! A classic tween interpolates a whole keyframe into the next one. A motion tween instead //! belongs to one keyframe span and one object in it (its *target*). Each property (x, y, -//! scale, rotation, skew, alpha, tint) may have a [`Track`] of property keyframes anywhere in +//! scale, rotation, skew, and the colour effect's alpha, brightness, tint and advanced values) may have a [`Track`] of property keyframes anywhere in //! the span; between two keys the value follows the segment's [`Easing`], which may be a custom //! cubic Bézier. A property without a track keeps the target's own value (its *base*: how it //! looks on the span's first frame). Evaluation is pure: [`MotionTween::apply`] maps the base @@ -21,7 +21,7 @@ //! time the whole path when only the ends are pinned. Anchors that aren't pinned shape the path //! only. -use crate::{Element, ElementId, Easing}; +use crate::{ColorEffect, ColorStyle, ColorTransform, Element, ElementId, Easing, Rgba}; use anicraft_geom::edit::ANCHOR; use anicraft_geom::walk::CurveWalk; use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2}; @@ -35,7 +35,7 @@ pub const MAX_KEYS: usize = 10_000; pub const MAX_PATH_SEGMENTS: usize = 1_000; /// A property a motion tween animates. Values are in the units the Motion Editor shows: -/// pixels, percent and degrees. +/// pixels, percent, degrees, and 0–255 for colour channels and offsets (as Animate shows them). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Property { @@ -49,13 +49,64 @@ pub enum Property { Rotation, /// Degrees of horizontal skew, within ±89. Skew, - /// Colour effect: opacity and tint amount, percent. + /// Colour effect (ADR 0056), by style. Alpha: opacity, percent. Alpha, + /// Brightness, −100..=100 %. + Brightness, + /// Tint amount, percent, and the tint colour's channels, 0–255. Tint, + TintRed, + TintGreen, + TintBlue, + /// Advanced: each channel's multiplier, −100..=100 %, and offset, −255..=255. + RedMultiplier, + GreenMultiplier, + BlueMultiplier, + AlphaMultiplier, + RedOffset, + GreenOffset, + BlueOffset, + AlphaOffset, } +/// How many properties there are. +pub const PROPERTIES: usize = 20; + impl Property { - pub const ALL: [Property; 8] = [Property::X, Property::Y, Property::ScaleX, Property::ScaleY, Property::Rotation, Property::Skew, Property::Alpha, Property::Tint]; + pub const ALL: [Property; PROPERTIES] = [ + Property::X, + Property::Y, + Property::ScaleX, + Property::ScaleY, + Property::Rotation, + Property::Skew, + Property::Alpha, + Property::Brightness, + Property::Tint, + Property::TintRed, + Property::TintGreen, + Property::TintBlue, + Property::RedMultiplier, + Property::GreenMultiplier, + Property::BlueMultiplier, + Property::AlphaMultiplier, + Property::RedOffset, + Property::GreenOffset, + Property::BlueOffset, + Property::AlphaOffset, + ]; + + /// The Advanced properties: multipliers then offsets, red first. + pub const ADVANCED: [Property; 8] = [ + Property::RedMultiplier, + Property::GreenMultiplier, + Property::BlueMultiplier, + Property::AlphaMultiplier, + Property::RedOffset, + Property::GreenOffset, + Property::BlueOffset, + Property::AlphaOffset, + ]; /// The name used in files and commands (`x`, `scale_x`, `alpha`…). pub fn key(self) -> &'static str { @@ -67,7 +118,19 @@ impl Property { Property::Rotation => "rotation", Property::Skew => "skew", Property::Alpha => "alpha", + Property::Brightness => "brightness", Property::Tint => "tint", + Property::TintRed => "tint_red", + Property::TintGreen => "tint_green", + Property::TintBlue => "tint_blue", + Property::RedMultiplier => "red_multiplier", + Property::GreenMultiplier => "green_multiplier", + Property::BlueMultiplier => "blue_multiplier", + Property::AlphaMultiplier => "alpha_multiplier", + Property::RedOffset => "red_offset", + Property::GreenOffset => "green_offset", + Property::BlueOffset => "blue_offset", + Property::AlphaOffset => "alpha_offset", } } @@ -80,24 +143,49 @@ impl Property { Property::Rotation => "Rotation", Property::Skew => "Skew", Property::Alpha => "Alpha", + Property::Brightness => "Brightness", Property::Tint => "Tint", + Property::TintRed => "Tint red", + Property::TintGreen => "Tint green", + Property::TintBlue => "Tint blue", + Property::RedMultiplier => "Red multiplier", + Property::GreenMultiplier => "Green multiplier", + Property::BlueMultiplier => "Blue multiplier", + Property::AlphaMultiplier => "Alpha multiplier", + Property::RedOffset => "Red offset", + Property::GreenOffset => "Green offset", + Property::BlueOffset => "Blue offset", + Property::AlphaOffset => "Alpha offset", } } pub fn unit(self) -> &'static str { match self { Property::X | Property::Y => "px", - Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Tint => "%", + Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Brightness | Property::Tint => "%", + Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => "%", Property::Rotation | Property::Skew => "°", + Property::TintRed | Property::TintGreen | Property::TintBlue | Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => "", } } /// The Motion Editor's groups: Position, Transform, Colour effect. pub fn group(self) -> &'static str { + match self.style() { + None if matches!(self, Property::X | Property::Y) => "Position", + None => "Transform", + Some(_) => "Colour effect", + } + } + + /// The colour effect style a colour property belongs to (`None` for position and transform). + pub fn style(self) -> Option { match self { - Property::X | Property::Y => "Position", - Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => "Transform", - Property::Alpha | Property::Tint => "Colour effect", + Property::X | Property::Y | Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => None, + Property::Alpha => Some(ColorStyle::Alpha), + Property::Brightness => Some(ColorStyle::Brightness), + Property::Tint | Property::TintRed | Property::TintGreen | Property::TintBlue => Some(ColorStyle::Tint), + Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier | Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => Some(ColorStyle::Advanced), } } @@ -108,6 +196,7 @@ impl Property { "scaley" => "scale_y", "rotate" => "rotation", "opacity" => "alpha", + "tint_amount" => "tint", other => other, }; Property::ALL.into_iter().find(|p| p.key() == s) @@ -121,6 +210,9 @@ impl Property { Property::Rotation => -100_000.0..=100_000.0, Property::Skew => -89.0..=89.0, Property::Alpha | Property::Tint => 0.0..=100.0, + Property::Brightness | Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => -100.0..=100.0, + Property::TintRed | Property::TintGreen | Property::TintBlue => 0.0..=255.0, + Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => -255.0..=255.0, } } @@ -129,7 +221,7 @@ impl Property { } fn is_transform(self) -> bool { - !matches!(self, Property::Alpha | Property::Tint) + self.style().is_none() } fn clamp(self, v: f32) -> f32 { @@ -140,13 +232,57 @@ impl Property { /// Every property's value, indexed like [`Property::ALL`]. #[derive(Clone, Copy, Debug, PartialEq)] -pub struct Props(pub [f32; 8]); +pub struct Props(pub [f32; PROPERTIES]); impl Props { - /// An element's own values. + /// An element's own values. Colour properties come from its colour effect's style; the + /// other styles' properties hold their rest values (alpha 100 %, brightness 0, tint 0 % of + /// white, Advanced 100 % and 0). pub fn of(el: &Element) -> Props { let d = el.transform.decompose(); - Props([d.tx, d.ty, d.sx * 100.0, d.sy * 100.0, d.rotation.to_degrees(), d.skew.atan().to_degrees(), el.color.alpha * 100.0, el.color.tint_amount * 100.0]) + let mut p = Props([0.0; PROPERTIES]); + for (q, v) in [(Property::X, d.tx), (Property::Y, d.ty), (Property::ScaleX, d.sx * 100.0), (Property::ScaleY, d.sy * 100.0), (Property::Rotation, d.rotation.to_degrees()), (Property::Skew, d.skew.atan().to_degrees())] { + p.set(q, v); + } + p.set_colour(&el.color); + p + } + + /// Sets the colour properties from `fx`, as [`Props::of`] does. + fn set_colour(&mut self, fx: &ColorEffect) { + let (mut alpha, mut bright, mut tint, mut rgb, mut adv) = (1.0, 0.0, 0.0, Rgba::WHITE, ColorTransform::IDENTITY); + match *fx { + ColorEffect::None => {} + ColorEffect::Alpha(a) => alpha = a, + ColorEffect::Brightness(b) => bright = b, + ColorEffect::Tint { color, amount } => (tint, rgb) = (amount, color), + ColorEffect::Advanced(t) => adv = t, + } + self.set(Property::Alpha, alpha * 100.0); + self.set(Property::Brightness, bright * 100.0); + self.set(Property::Tint, tint * 100.0); + self.set(Property::TintRed, rgb.r * 255.0); + self.set(Property::TintGreen, rgb.g * 255.0); + self.set(Property::TintBlue, rgb.b * 255.0); + let values = adv.mul.iter().map(|m| m * 100.0).chain(adv.add.iter().map(|a| a * 255.0)); + for (q, v) in Property::ADVANCED.into_iter().zip(values) { + self.set(q, v); + } + } + + /// The colour effect of the styles in `styles` from these values (the other styles' values + /// are left out): one style alone is that style; several compose into Advanced (ADR 0056). + pub fn color_effect(&self, styles: &[ColorStyle]) -> ColorEffect { + let v = |p: Property| p.clamp(self.get(p)); + let on = |s: ColorStyle| styles.contains(&s); + let alpha = on(ColorStyle::Alpha).then(|| v(Property::Alpha) / 100.0); + let bright = on(ColorStyle::Brightness).then(|| v(Property::Brightness) / 100.0); + let tint = on(ColorStyle::Tint).then(|| (Rgba::new(v(Property::TintRed) / 255.0, v(Property::TintGreen) / 255.0, v(Property::TintBlue) / 255.0, 1.0), v(Property::Tint) / 100.0)); + let adv = on(ColorStyle::Advanced).then(|| { + let [rm, gm, bm, am, ro, go, bo, ao] = Property::ADVANCED.map(v); + ColorTransform { mul: [rm, gm, bm, am].map(|m| m / 100.0), add: [ro, go, bo, ao].map(|a| a / 255.0) } + }); + ColorEffect::compose(alpha, bright, tint, adv).sanitized() } pub fn get(&self, p: Property) -> f32 { self.0.get(p.index()).copied().unwrap_or(0.0) @@ -891,15 +1027,25 @@ impl MotionTween { el.transform = m; } } - if let Some(t) = self.track(Property::Alpha).and_then(|t| t.value_at(frame)) { - el.color.alpha = (t / 100.0).clamp(0.0, 1.0); - } - if let Some(t) = self.track(Property::Tint).and_then(|t| t.value_at(frame)) { - el.color.tint_amount = (t / 100.0).clamp(0.0, 1.0); + // Colour: the styles keyed here and the target's own, composed (ADR 0056). + if self.tracks.iter().any(|t| !t.property.is_transform()) { + el.color = props.color_effect(&self.colour_styles(&base.color)); } el } + /// The colour effect styles the target shows over the span: those with keyed properties, + /// and its own style (unless None). + pub fn colour_styles(&self, own: &ColorEffect) -> Vec { + let mut out: Vec = Vec::new(); + for s in self.tracks.iter().filter_map(|t| t.property.style()).chain((own.style() != ColorStyle::None).then_some(own.style())) { + if !out.contains(&s) { + out.push(s); + } + } + out + } + /// Sets property `p`'s key at `frame`. A property's first key also gets a key on the span's /// first frame holding `base` (its value until now), so the rest of the span is unchanged. pub fn set_key(&mut self, p: Property, frame: u32, value: f32, base: f32) { @@ -1083,7 +1229,7 @@ mod tests { m.set_key(Property::Alpha, 10, 0.0, 100.0); let at5 = m.apply(&base, 5.0); assert_eq!(at5.transform, base.transform, "colour-only tween keeps the transform bit for bit"); - assert!((at5.color.alpha - 0.5).abs() < 1e-6); + assert!((at5.color.alpha() - 0.5).abs() < 1e-6 && at5.color.style() == ColorStyle::Alpha); } #[test] @@ -1167,7 +1313,7 @@ mod tests { fn property_keys_round_trip() { for p in Property::ALL { assert_eq!(Property::from_key(p.key()), Some(p)); - assert!(!p.label().is_empty() && !p.unit().is_empty() && !p.group().is_empty()); + assert!(!p.label().is_empty() && (!p.unit().is_empty() || p.range() == (0.0..=255.0) || p.range() == (-255.0..=255.0)) && !p.group().is_empty()); } assert_eq!(Property::from_key("Scale X"), Some(Property::ScaleX)); assert_eq!(Property::from_key("nope"), None); diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index e3170648..5d6847ec 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -102,7 +102,7 @@ impl Overrides { } } if let Some(a) = self.alpha { - e.color.alpha = a; + e.color = e.color.with_alpha(a); } e } diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index a5b64bbe..55fb9244 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -167,7 +167,7 @@ fn set(s: &mut Session, p: &Value) -> Result { let lim = 1_000_000.0; c.center = Vec2::new(c.center.x.clamp(-lim, lim), c.center.y.clamp(-lim, lim)); el.transform = c.transform(); - el.color = c.color(); + el.color = c.to_element(el.id).color; Ok(c) })(); s.layer = layer; diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index a84fe80a..dc70975f 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -2,7 +2,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Selection, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_doc::{ColorEffect, ColorStyle, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Decomposed, Path, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -29,7 +29,8 @@ pub fn specs() -> Vec { c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), - c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), + c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), + c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera's effect is a tint", true, |s, p| s.each_layer(true, |s| set_color_effect(s, p))), c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))), c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))), c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))), @@ -401,11 +402,86 @@ fn set_alpha(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("param 'alpha' must be between 0 and 1".into())); } for e in s.selected_elements_mut()? { - e.color.alpha = a; + e.color = e.color.with_alpha(a); } Ok(json!({"alpha": a})) } +/// Each colour effect value `element.set_color_effect` takes: its key, style, range and scale +/// (the model's value is the param's divided by it). +const EFFECT_VALUES: [(&str, ColorStyle, f32, f32, f32); 11] = [ + ("alpha", ColorStyle::Alpha, 0.0, 100.0, 100.0), + ("brightness", ColorStyle::Brightness, -100.0, 100.0, 100.0), + ("tint_amount", ColorStyle::Tint, 0.0, 100.0, 100.0), + ("red_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("green_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("blue_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("alpha_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("red_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("green_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("blue_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("alpha_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), +]; + +fn set_color_effect(s: &mut Session, p: &Value) -> Result { + let style = match opt_str(p, "style")? { + Some(k) => Some(ColorStyle::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown style '{k}' (none, brightness, tint, advanced or alpha)")))?), + None => None, + }; + let tint = opt_color(p, "tint")?; + let mut values: Vec<(usize, f32)> = Vec::new(); + let mut families: Vec = tint.map(|_| ColorStyle::Tint).into_iter().collect(); + for (i, (key, fam, lo, hi, scale)) in EFFECT_VALUES.iter().enumerate() { + if let Some(v) = opt_f32(p, key)? { + if !(*lo..=*hi).contains(&v) { + return Err(EngineError::Param(format!("param '{key}' must be between {lo} and {hi}"))); + } + values.push((i, v / scale)); + if !families.contains(fam) { + families.push(*fam); + } + } + } + let style = match (style, families.as_slice()) { + (Some(st), f) if f.iter().any(|x| *x != st) => return Err(EngineError::Param(format!("the {} style has none of these values: give only its own", st.key()))), + (Some(st), _) => Some(st), + (None, []) => return Err(EngineError::Param("give a style, or a value to set".into())), + (None, [one]) => Some(*one), + (None, _) => return Err(EngineError::Param("these values belong to different styles: give one style's values".into())), + }; + let mut first = None; + for e in s.selected_elements_mut()? { + let target = style.unwrap_or(e.color.style()); + if matches!(e.kind, ElementKind::Camera) && !matches!(target, ColorStyle::Tint | ColorStyle::None) { + return Err(EngineError::State("the camera's colour effect is a tint".into())); + } + let mut fx = e.color.to_style(target); + if let ColorEffect::Tint { color, .. } = &mut fx + && let Some(t) = tint + { + *color = t.with_alpha(1.0); + } + for &(i, v) in &values { + match &mut fx { + ColorEffect::Alpha(a) if i == 0 => *a = v, + ColorEffect::Brightness(b) if i == 1 => *b = v, + ColorEffect::Tint { amount, .. } if i == 2 => *amount = v, + ColorEffect::Advanced(t) => { + if let Some(m) = i.checked_sub(3).and_then(|j| t.mul.get_mut(j)) { + *m = v; + } else if let Some(o) = i.checked_sub(7).and_then(|j| t.add.get_mut(j)) { + *o = v; + } + } + _ => {} + } + } + e.color = fx.sanitized(); + first.get_or_insert(e.color); + } + Ok(first.map_or(Value::Null, |fx| crate::color_effect_json(&fx))) +} + /// Most filters on one instance. const MAX_FILTERS: usize = 16; @@ -750,7 +826,7 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { let mut c = (**child).clone(); c.id = ElementId(s.doc.alloc_id()); c.transform = e.transform.mul(&child.transform); - c.color = e.color.concat(&child.color); + c.color = e.color.nested(&child.color); fresh_ids.push(c.id); out.push(Arc::new(c)); } diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 5a046c8c..3ec7adbc 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -270,7 +270,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { list.into_iter() .map(|e| { let id = anicraft_doc::ElementId(s.doc.alloc_id()); - Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect { alpha: e.alpha, ..Default::default() }, kind: e.kind }) + Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect::opacity(e.alpha), kind: e.kind }) }) .collect() }; diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 776b90a7..35527e4a 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -15,7 +15,7 @@ use crate::cmds_timeline::target; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props}; +use anicraft_doc::{Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props}; use anicraft_geom::{Affine, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -23,7 +23,7 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|tint, value (px, %, °), frame?, layer?}", true, set_key as crate::RunFn), + c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)", true, set_key as crate::RunFn), c("motion.remove_key", "Remove Property Keyframe", "", None, "{property? (default: every property), frame?, layer?}", true, remove_key), c("motion.set_ease", "Property Ease", "", None, "{easing, property? (default: every property), frame? (inside the segment), layer?}", true, set_ease), c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is", false, info), @@ -111,7 +111,7 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { let v = was.get(p) + d; if e.offset == 0 && m.track(p).is_none() { new_base.set(p, v); - if matches!(p, Property::Alpha | Property::Tint) { + if p.style().is_some() { base_color = true; } else { base_xf = true; @@ -120,8 +120,8 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { m.set_key(p, e.offset, v, base_props.get(p)); } } - let tracks_xf = m.tracks.iter().any(|t| !matches!(t.property, Property::Alpha | Property::Tint)); - let tracks_color = m.tracks.iter().any(|t| matches!(t.property, Property::Alpha | Property::Tint)); + let tracks_xf = m.tracks.iter().any(|t| t.property.style().is_none()); + let tracks_color = m.tracks.iter().any(|t| t.property.style().is_some()); let mut base = after; // Exact where nothing is keyed on the first frame: the edited object is the new base. base.transform = match (base_xf, e.offset == 0 && !tracks_xf) { @@ -131,8 +131,9 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { }; base.color = match (base_color, e.offset == 0 && !tracks_color) { (true, true) => base.color, - (true, false) => ColorEffect { alpha: (new_base.get(Property::Alpha) / 100.0).clamp(0.0, 1.0), tint: base.color.tint, tint_amount: (new_base.get(Property::Tint) / 100.0).clamp(0.0, 1.0) }, - (false, _) => ColorEffect { tint: base.color.tint, ..e.base.color }, + // The base's style and the edit's, from the new values (ADR 0056). + (true, false) => new_base.color_effect(&[e.base.color.style(), base.color.style()]), + (false, _) => e.base.color, }; if let Some(slot) = kf.elements.get_mut(idx) { *slot = Arc::new(base); diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 616bd168..88e82aaa 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -126,7 +126,8 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result "selected": s.selection.contains(s.layer, e.id), "transform": e.transform.m, "bounds": if b.is_empty() { Value::Null } else { json!([b.min.x, b.min.y, b.max.x - b.min.x, b.max.y - b.min.y]) }, - "alpha": e.color.alpha, + "alpha": e.color.alpha(), + "color_effect": crate::color_effect_json(&e.color), }); match &e.kind { ElementKind::Shape(sh) => { diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index 456ddd78..e173b55d 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -353,7 +353,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R // A motion tween split in two keeps moving the same way in both halves. let motion = if copy { k.motion.as_ref().map(|m| { - let base = m.target_index(&k.elements).and_then(|t| k.elements.get(t)).map_or(anicraft_doc::Props([0.0; 8]), |e| anicraft_doc::Props::of(e)); + let base = m.target_index(&k.elements).and_then(|t| k.elements.get(t)).map_or(anicraft_doc::Props([0.0; anicraft_doc::PROPERTIES]), |e| anicraft_doc::Props::of(e)); m.split_at(&base, frame - k.start) }) } else { diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index 2928925e..e71cebba 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -221,7 +221,7 @@ fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, id: ElementId(doc.alloc_id()), name: String::new(), transform, - color: ColorEffect { alpha, ..ColorEffect::default() }, + color: ColorEffect::opacity(alpha), kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, })); let mut layer = Layer::new(LayerId(doc.alloc_id()), ""); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a6972fe4..4c3e4947 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -894,6 +894,30 @@ pub(crate) enum KeyEdit { Pose, } +/// A colour effect as commands report it (ADR 0056): its style and that style's values, in the +/// units `element.set_color_effect` takes (percent; Advanced offsets −255..255). +pub fn color_effect_json(fx: &anicraft_doc::ColorEffect) -> serde_json::Value { + use anicraft_doc::ColorEffect; + let r = |v: f32, k: f32| f64::from((v * k * 100.0).round() / 100.0); + let mut v = serde_json::json!({"style": fx.style().key()}); + match *fx { + ColorEffect::None => {} + ColorEffect::Alpha(a) => v["alpha"] = r(a, 100.0).into(), + ColorEffect::Brightness(b) => v["brightness"] = r(b, 100.0).into(), + ColorEffect::Tint { color, amount } => { + v["tint"] = color.to_hex().into(); + v["tint_amount"] = r(amount, 100.0).into(); + } + ColorEffect::Advanced(t) => { + for (i, ch) in ["red", "green", "blue", "alpha"].iter().enumerate() { + v[format!("{ch}_multiplier")] = r(t.mul.get(i).copied().unwrap_or(1.0), 100.0).into(); + v[format!("{ch}_offset")] = r(t.add.get(i).copied().unwrap_or(0.0), 255.0).into(); + } + } + } + v +} + /// Short human label for an element (properties panel, library, CLI). pub fn element_label(doc: &Document, e: &Element) -> String { let kind = match &e.kind { diff --git a/crates/engine/src/motion_tests.rs b/crates/engine/src/motion_tests.rs index dc7206cd..7f707024 100644 --- a/crates/engine/src/motion_tests.rs +++ b/crates/engine/src/motion_tests.rs @@ -95,7 +95,7 @@ fn transforms_and_colour_edits_key_their_own_properties() { assert!(m.track(Property::ScaleY).is_none() && m.track(Property::X).is_none()); s.set_frame(4); let e = s.visible_elements()[0].clone(); - assert!((e.color.alpha - 0.625).abs() < 1e-5 && (e.transform.decompose().sx - 1.5).abs() < 1e-4); + assert!((e.color.alpha() - 0.625).abs() < 1e-5 && (e.transform.decompose().sx - 1.5).abs() < 1e-4); // Non-tweenable edits change the object itself, whatever the frame. run(&mut s, "edit.select_all", json!({})); run(&mut s, "element.set_fill", json!({"color": "#ff0000"})); diff --git a/crates/engine/src/multi_tests.rs b/crates/engine/src/multi_tests.rs index dc2bac63..bd6ed5af 100644 --- a/crates/engine/src/multi_tests.rs +++ b/crates/engine/src/multi_tests.rs @@ -285,7 +285,7 @@ fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() { let n = dl.items.len(); let (ghost, now) = (&dl.items[n - 2], &dl.items[n - 1]); assert_eq!((left(ghost), left(now)), (100.0, 140.0)); - assert!(ghost.color.alpha < 1.0 && ghost.color.tint_amount > 0.0 && now.color.alpha == 1.0); + assert!(ghost.color.mul[3] < 1.0 && ghost.color.changes_colour() && now.color.is_identity()); // The job does the same, keyed apart from the plain picture. let view = anicraft_render::View { transform: Affine::IDENTITY, width: 64, height: 64, background: None }; let plain_job = crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, Some(&ghosts)); @@ -295,7 +295,7 @@ fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() { // Edit Multiple Frames shows both keyframes at full strength. let multi = OnionSkin { edit_multiple: true, markers: crate::onion::Markers::Relative { before: 4, after: 0 }, ..OnionSkin::default() }; let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi); - assert!(dl.items.iter().rev().take(2).all(|i| i.color.alpha == 1.0 && i.color.tint_amount == 0.0)); + assert!(dl.items.iter().rev().take(2).all(|i| i.color.is_identity())); // With nothing to add, the job draws the picture as it is. let off = make_off(&pic); assert_eq!(off.display_list().items.len(), plain.items.len()); diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs index fd5a51a5..594f98da 100644 --- a/crates/engine/src/onion.rs +++ b/crates/engine/src/onion.rs @@ -19,7 +19,7 @@ //! program; nothing was copied. use crate::{CommandSpec, MAX_FRAME, Result, Session}; -use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline}; +use anicraft_doc::{ColorTransform, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline}; use anicraft_geom::{Rect, Vec2}; use serde_json::{Value, json}; use std::collections::{BTreeMap, HashSet}; @@ -168,12 +168,12 @@ impl OnionSkin { } /// The colour effect an onion frame gets, and the outline colour (when outlines are on). - pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorEffect, Option) { + pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorTransform, Option) { let alpha = self.alpha(distance, reach); let color = if past { self.past } else { self.future }; let (tint, tint_amount) = if self.tint { (color, TINT_AMOUNT) } else { (Rgba::WHITE, 0.0) }; let outline = self.outlines.then(|| color.with_alpha(alpha * color.a.clamp(0.0, 1.0))); - (ColorEffect { alpha, tint, tint_amount }, outline) + (ColorTransform::alpha(alpha).concat(&ColorTransform::tint(tint, tint_amount)), outline) } /// A hash of everything that changes the picture, for render-cache keys. diff --git a/crates/engine/src/onion_tests.rs b/crates/engine/src/onion_tests.rs index db289dd2..4da367cb 100644 --- a/crates/engine/src/onion_tests.rs +++ b/crates/engine/src/onion_tests.rs @@ -106,11 +106,12 @@ fn onion_frames_fade_by_distance_in_their_colours() { assert!((1..=5).all(|d| flat.alpha(d, 5) == NEAR_ALPHA)); let (past, line) = o.look(true, 1, 2); - assert_eq!((past.tint, past.tint_amount, past.alpha, line), (o.past, TINT_AMOUNT, NEAR_ALPHA, None)); + let look = |c, a| anicraft_doc::ColorTransform::alpha(a).concat(&anicraft_doc::ColorTransform::tint(c, TINT_AMOUNT)); + assert_eq!((past, line), (look(o.past, NEAR_ALPHA), None)); let (future, _) = o.look(false, 2, 2); - assert_eq!((future.tint, future.alpha), (o.future, FAR_ALPHA)); + assert_eq!(future, look(o.future, FAR_ALPHA)); let (own, _) = OnionSkin { tint: false, ..o }.look(true, 1, 2); - assert_eq!(own.tint_amount, 0.0, "untinted frames keep their own colours"); + assert!(!own.changes_colour(), "untinted frames keep their own colours"); let (_, line) = OnionSkin { outlines: true, ..o }.look(false, 2, 2); assert_eq!(line, Some(o.future.with_alpha(FAR_ALPHA))); } @@ -182,10 +183,11 @@ fn composed_onion_frames_are_tinted_faded_and_under_the_playhead() { let skin = OnionSkin::default(); let dl = compose(&s.doc, 0, 4, Some(&skin), |sc, f| evaluate_scene(&s.doc, sc, f)); // Frames 2, 6, 3, 5 under frame 4: the keyframes there hold the rectangle at 10, 50, 10, 50. - let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect(); + let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.mul[3], 1.0 - i.color.mul[0])).collect(); assert_eq!(got, vec![(10.0, FAR_ALPHA, TINT_AMOUNT), (50.0, FAR_ALPHA, TINT_AMOUNT), (10.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, 1.0, 0.0)]); - assert_eq!(dl.items.first().map(|i| i.color.tint), Some(skin.past)); - assert_eq!(dl.items.get(1).map(|i| i.color.tint), Some(skin.future)); + let tint = |c| anicraft_doc::ColorTransform::tint(c, TINT_AMOUNT).add; + assert_eq!(dl.items.first().map(|i| i.color.add), Some(tint(skin.past))); + assert_eq!(dl.items.get(1).map(|i| i.color.add), Some(tint(skin.future))); // Off, or None: the frame alone. let off = OnionSkin { ghosts: false, ..skin }; assert_eq!(compose(&s.doc, 0, 4, Some(&off), |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1); @@ -230,7 +232,7 @@ fn edit_multiple_frames_shows_keyframes_within_the_markers_at_full_strength() { // doesn't; the one on 4 is the playhead's. assert_eq!(multi_frames(tl, 4, 2, 6).iter().map(|e| e.frame).collect::>(), vec![0]); let dl = compose(&s.doc, 0, 4, Some(&near), |sc, f| evaluate_scene(&s.doc, sc, f)); - assert_eq!(dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect::>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]); + assert_eq!(dl.items.iter().map(|i| (left(i), i.color.mul[3], 1.0 - i.color.mul[0])).collect::>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]); let wide = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..near }; let dl = compose(&s.doc, 0, 4, Some(&wide), |sc, f| evaluate_scene(&s.doc, sc, f)); assert_eq!(dl.items.iter().map(left).collect::>(), vec![10.0, 90.0, 50.0], "other keyframes in frame order, the playhead's on top"); @@ -420,7 +422,7 @@ fn extra_frames_sit_on_their_own_layer_over_an_opaque_background() { let ball = plain.items.last().unwrap().layer; let on_ball: Vec<&DisplayItem> = dl.items.iter().filter(|i| i.layer == ball).collect(); assert!(on_ball.len() > 1); - assert_eq!(on_ball.last().map(|i| (i.color.alpha, i.color.tint_amount)), Some((1.0, 0.0)), "the playhead's ball is on top"); + assert_eq!(on_ball.last().map(|i| i.color.is_identity()), Some(true), "the playhead's ball is on top"); } // Rendered: the ball on frame 1 (top left of its path) shows over the sky, in Edit Multiple // Frames at full strength. diff --git a/crates/engine/src/selection_tests.rs b/crates/engine/src/selection_tests.rs index 6ae32395..082436c5 100644 --- a/crates/engine/src/selection_tests.rs +++ b/crates/engine/src/selection_tests.rs @@ -206,7 +206,7 @@ fn properties_edits_apply_to_each_layer() { run(&mut s, "element.set_transform", json!({"rotation": 45})); for (l, id) in [(top, a), (bottom, b)] { let e = element(&s, l, id).unwrap(); - assert_eq!(e.color.alpha, 0.5); + assert_eq!(e.color, anicraft_doc::ColorEffect::Alpha(0.5)); assert_eq!(e.name, "both"); assert!((e.transform.decompose().rotation.to_degrees() - 45.0).abs() < 1e-3); let ElementKind::Shape(sh) = &e.kind else { panic!() }; diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index f24fc0e8..f35b3f00 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -29,6 +29,7 @@ fn corpus() -> PathBuf { /// The frames rendered for each package (frames count across scenes, from 0). const FRAMES: &[(&str, &[u32])] = &[ ("bitmaps", &[0]), + ("colour", &[0, 6, 12]), ("filters", &[0]), ("gradients", &[0]), ("guides", &[0, 6, 12]), @@ -73,9 +74,27 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("symbols", 5, 130.0, 40.0, 0x457B9D), // The button's Up frame. ("symbols", 0, 82.0, 130.0, 0x2A9D8F), - // Brightness +60% and -50% of #6D597A. + // Brightness +60% and -50% of #6D597A; Advanced: red ×20 %, green +120, at 80 % over white. ("symbols", 0, 230.0, 130.0, 0xC5BDCA), ("symbols", 0, 260.0, 130.0, 0x372D3D), + ("symbols", 0, 290.0, 130.0, 0x44DA95), + // Colour effects on #2A9D8F (ADR 0056): None, Brightness +50 %, Tint 60 % #E9C46A, Advanced + // (red −100 % +255, green 50 %, blue −60), Alpha 25 % over white. + ("colour", 0, 30.0, 40.0, 0x2A9D8F), + ("colour", 0, 90.0, 40.0, 0x94CEC7), + ("colour", 0, 150.0, 40.0, 0x9DB479), + ("colour", 0, 210.0, 40.0, 0xD54F53), + ("colour", 0, 270.0, 40.0, 0xCAE6E3), + // Brightness −40 % around a 50 % red tint: both, exactly (not the stronger one alone). + ("colour", 0, 60.0, 110.0, 0x592F2B), + // Tint #264653 to Advanced: the ends, and halfway in the advanced space. + ("colour", 0, 160.0, 105.0, 0x264653), + ("colour", 6, 220.0, 105.0, 0x614771), + ("colour", 12, 280.0, 105.0, 0x944C8D), + // Brightness −100 % to +60 %: halfway is brightness −20 % (not the transforms' midpoint). + ("colour", 0, 160.0, 152.0, 0x000000), + ("colour", 6, 220.0, 152.0, 0x227E72), + ("colour", 12, 280.0, 152.0, 0xAAD8D2), ("tweens", 0, 20.0, 25.0, 0xF4A261), ("tweens", 12, 300.0, 25.0, 0xF4A261), // Masked stripes: inside the spot, and outside it. diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index 14c54690..772614c6 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -13,7 +13,7 @@ //! (512 px tiles drawn in parallel, as the render service does, until finished); and how far //! the GPU-binned picture is from the oracle's. -use anicraft_doc::{Bitmap, BitmapId, ColorEffect, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; +use anicraft_doc::{Bitmap, BitmapId, ColorEffect, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; use anicraft_geom::{FillRule, Path}; use anicraft_gpu::{Binning, GpuRenderer, compare_premul8}; use anicraft_geom::Affine; @@ -54,7 +54,7 @@ fn composited() -> Document { 0 | 1 => { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { - Arc::make_mut(e).color.alpha = 0.6; + Arc::make_mut(e).color = ColorEffect::Alpha(0.6); } } } @@ -172,7 +172,7 @@ fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList { let color = if is_past { past } else { future }; let mut part = evaluate(doc, f); for item in &mut part.items { - item.color = item.color.concat(&ColorEffect { alpha, tint: color, tint_amount: 0.8 }); + item.color = item.color.concat(&ColorTransform::alpha(alpha).concat(&ColorTransform::tint(color, 0.8))); if mode == Onion::Outlines && item.masks.is_none() { item.outline = Some(color.with_alpha(alpha)); } diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index 490c48e2..fced063d 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -252,7 +252,16 @@ pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_ let mut images: Vec> = Vec::new(); let ramps_at = (PAINT_VEC4S * ops.len()) as u32; // Where each layer shown by a fill goes, after the tables (the tables' size is known first). - let table_len: usize = ops.iter().filter(|f| matches!(f.shader, Shader::Linear { .. } | Shader::Radial { .. }) && f.layer.is_none()).count() * RAMP; + // Gradients' ramps, and each bitmap's colour transform (two entries). + let table_len: usize = ops + .iter() + .filter(|f| f.layer.is_none()) + .map(|f| match &f.shader { + Shader::Linear { .. } | Shader::Radial { .. } => RAMP, + Shader::Bitmap { pixels, .. } if pixels.width > 0 && pixels.height > 0 => 2, + _ => 0, + }) + .sum(); let mut layer_at: Vec> = vec![None; scene.layers.len()]; let mut cursor = PAINT_VEC4S * ops.len() + table_len; for f in &ops { @@ -306,9 +315,12 @@ pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_ None => return Err(NeedsFull::Bitmaps), }; let m = inv.m; - let (k, alpha, tint, keep) = colour_effect(fx); + // The colour transform (ADR 0056) rides in the ramp table: multiplies, then + // offsets, sanitized as the oracle applies them. + let fx = fx.sanitized(); + ramps.extend_from_slice(&[fx.mul, fx.add]); // Bit 0: repeat; bit 1: the nearest pixel instead of bilinear (no smoothing). - (BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], k, alpha], [tint[0], tint[1], tint[2], u(keep)]]) + (BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], 0.0, 0.0], [0.0; 4]]) } } // `prepare_scene` never hands these over; draw nothing rather than guess. @@ -441,28 +453,6 @@ fn cpu_lists(ops: &[&Fill], tables: &Tables, tiles_x: u32, tiles_y: u32) -> List Lists { index, geo, entries_at: entries_at as u32, ops_at: ops_at as u32, entries: total, pieces, work } } -/// A colour effect as the shader applies it to each bitmap tap, the same arithmetic as -/// [`anicraft_doc::ColorEffect::apply`] then `premultiply`'s sanitizing: `(tint amount, alpha, -/// tint, kept channels)`. Each straight channel `c` becomes `c + (tint − c)·k`, alpha `a·alpha`, -/// clamped to `0..=1`. A NaN the oracle would carry into a channel (and its sanitizing turn -/// into 0) is a channel left out of `kept` (bit per channel, red first) instead. -fn colour_effect(fx: &anicraft_doc::ColorEffect) -> (f32, f32, [f32; 3], u32) { - let k = fx.tint_amount.clamp(0.0, 1.0); - let alpha = fx.alpha.clamp(0.0, 1.0); - let t = [fx.tint.r, fx.tint.g, fx.tint.b]; - let mut keep = 0u32; - let mut tint = [0.0f32; 3]; - for (i, (&v, out)) in t.iter().zip(tint.iter_mut()).enumerate() { - if v.is_finite() && k.is_finite() { - keep |= 1 << i; - *out = v; - } - } - // A NaN opacity makes every channel 0 (premultiplied by a sanitized alpha of 0). - let alpha = if alpha.is_finite() { alpha } else { 0.0 }; - (if k.is_finite() { k } else { 0.0 }, alpha, tint, keep) -} - /// Tile row `r`'s streams: per tile, its fills in drawing order with the clip and group /// entries they need. fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u32], t: &Tables) -> RowOut { diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 374e5b20..1accec1f 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -158,19 +158,15 @@ fn finite(v: f32) -> bool { // One bitmap tap at integer (x, y) (wrapped when repeating, then clamped to the edges as // `Pixels::at` does), through the colour effect, premultiplied. -fn tap(slot: u32, x: i32, y: i32, size: vec2, repeat: bool, fx: vec4, tint: vec4) -> vec4 { +// The colour transform (ColorTransform::apply): each straight channel `c·mul + add`, clamped. +fn tap(slot: u32, x: i32, y: i32, size: vec2, repeat: bool, mul: vec4, add: vec4) -> vec4 { var q = vec2(x, y); if repeat { q = ((q % size) + size) % size; } q = clamp(q, vec2(0), size - vec2(1)); - let c = texel(slot, q); - let keep = bitcast(tint.w); - let k = fx.z; - var rgb = clamp(c.rgb + (tint.rgb - c.rgb) * k, vec3(0.0), vec3(1.0)); - rgb = select(vec3(0.0), rgb, vec3((keep & 1u) != 0u, (keep & 2u) != 0u, (keep & 4u) != 0u)); - let a = clamp(c.a * fx.w, 0.0, 1.0); - return vec4(rgb * a, a); + let c = clamp(texel(slot, q) * mul + add, vec4(0.0), vec4(1.0)); + return vec4(c.rgb * c.a, c.a); } // Rust's `rem_euclid` for f32. @@ -181,11 +177,12 @@ fn rem_euclid(u: f32, n: f32) -> f32 { // The oracle's sample of a bitmap at pixel centre `p` (paint.rs › sample): bilinear, or the // pixel `p` falls in when the bitmap doesn't allow smoothing (flag bit 1). -fn bitmap(base: u32, p: vec2) -> vec4 { +fn bitmap(base: u32, ramp: u32, p: vec2) -> vec4 { let h0 = paints[base]; let m = paints[base + 1u]; let n = paints[base + 2u]; - let tint = paints[base + 3u]; + let mul = paints[ramp]; + let add = paints[ramp + 1u]; let slot = bitcast(h0.x); let flags = bitcast(h0.y); let repeat = (flags & 1u) != 0u; @@ -205,7 +202,7 @@ fn bitmap(base: u32, p: vec2) -> vec4 { return vec4(0.0); } if nearest { - return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, n, tint); + return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, mul, add); } let fx_ = u - 0.5; let fy_ = v - 0.5; @@ -215,10 +212,10 @@ fn bitmap(base: u32, p: vec2) -> vec4 { let ty = fy_ - y0; let xi = i32(x0); let yi = i32(y0); - let a = tap(slot, xi, yi, size, repeat, n, tint); - let b = tap(slot, xi + 1, yi, size, repeat, n, tint); - let c = tap(slot, xi, yi + 1, size, repeat, n, tint); - let d = tap(slot, xi + 1, yi + 1, size, repeat, n, tint); + let a = tap(slot, xi, yi, size, repeat, mul, add); + let b = tap(slot, xi + 1, yi, size, repeat, mul, add); + let c = tap(slot, xi, yi + 1, size, repeat, mul, add); + let d = tap(slot, xi + 1, yi + 1, size, repeat, mul, add); let top = a + (b - a) * tx; let bottom = c + (d - c) * tx; return top + (bottom - top) * ty; @@ -245,7 +242,7 @@ fn shade(op: u32, kind: u32, ramp: u32, p: vec2, x: u32, y: u32) -> vec4 Result<(), GpuError> { - use anicraft_doc::{ColorEffect, DisplayItem, ElementId, Filter, Group, LayerId, Paint, Pixels, Rgba}; + use anicraft_doc::{ColorTransform, DisplayItem, ElementId, Filter, Group, LayerId, Paint, Pixels, Rgba}; use anicraft_geom::{Affine, FillRule, Path}; let item = |path: Path, fill: Paint| DisplayItem { path: Arc::new(path), @@ -434,7 +434,7 @@ impl GpuRenderer { fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::IDENTITY, layer: LayerId(0), element: ElementId(0), outline: None, diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 214cd49c..063b66e4 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -7,7 +7,7 @@ use super::*; use crate::binning::{self as bn, Binned, PAINT_VEC4S, TILE, piece_cover, solid_of}; -use anicraft_doc::{BlendMode, ColorEffect, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, Paint, Rgba, Stroke, sample}; +use anicraft_doc::{BlendMode, ColorEffect, ColorTransform, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, Paint, Rgba, Stroke, sample}; use anicraft_geom::{Affine, FillRule, Path, Vec2}; use anicraft_render::{paint::Premul, render}; use std::sync::OnceLock; @@ -22,7 +22,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem { fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::IDENTITY, layer: LayerId(0), element: ElementId(0), outline: None, @@ -125,7 +125,7 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { out.push(("styled strokes", list(vec![dashed, zig, dots]), view(160, 100, Some(Rgba::WHITE)))); // Larger than the surface on every side; colour effects (onion-skin style tint and alpha). let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red)); - huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 }; + huge.color = ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::hex(0x4cd07d), 0.7)); out.push(("off-surface", list(vec![huge]), view(100, 80, Some(Rgba::WHITE)))); out.push(("outlines", outlined(), view(150, 110, Some(Rgba::WHITE)))); out.extend(composited_scenes()); @@ -448,7 +448,7 @@ fn composited_sample() -> anicraft_doc::Document { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { let e = Arc::make_mut(e); - e.color.alpha = if i == 0 { 0.6 } else { 0.5 }; + e.color = e.color.with_alpha(if i == 0 { 0.6 } else { 0.5 }); if let ElementKind::Symbol { blend, .. } = &mut e.kind && i == 0 { @@ -720,7 +720,7 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() { }) .collect(); let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1); - it.color.alpha = 0.5; + it.color = ColorTransform::alpha(0.5); DisplayList { items: vec![it], clip_parents: Vec::new(), groups } }; let deep = nested(MAX_FILTER_DEPTH + 1); @@ -782,12 +782,16 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { ("bitmap magnified, mirrored", list(vec![bitmap_item(Path::rect(0.0, 0.0, 64.0, 48.0), &c, false, Affine { m: [-1.7, 0.0, 0.0, 1.6, 66.0, -1.3] })]), view(64, 48, white)), ("one-pixel bitmap", list(vec![bitmap_item(Path::rect(5.5, 5.5, 20.0, 20.0), &b, true, Affine::scale(7.0, 7.0))]), view(32, 32, white)), ]; - // Colour effects: tint and alpha per tap, and a NaN tint (sanitized to 0 as the oracle does). + // Colour effects: tint and alpha per tap, and a NaN multiplier (a channel of 0, as the oracle + // draws it). let mut tinted = bitmap_item(Path::rect(0.0, 0.0, 60.0, 40.0), &c, true, Affine::scale(0.7, 0.9)); - tinted.color = ColorEffect { alpha: 0.6, tint: Rgba::new(0.2, 0.9, 0.1, 1.0), tint_amount: 0.4 }; + tinted.color = ColorTransform::alpha(0.6).concat(&ColorTransform::tint(Rgba::new(0.2, 0.9, 0.1, 1.0), 0.4)); let mut nan = bitmap_item(Path::rect(30.0, 10.0, 30.0, 30.0), &a, false, Affine::scale(2.0, 2.0)); - nan.color = ColorEffect { alpha: 1.0, tint: Rgba::new(f32::NAN, 0.5, 0.5, 1.0), tint_amount: 0.3 }; - out.push(("bitmap colour effects", list(vec![tinted, nan]), view(64, 48, Some(Rgba::new(0.1, 0.1, 0.3, 1.0))))); + nan.color = ColorTransform { mul: [f32::NAN, 0.7, 0.7, 1.0], add: [0.0, 0.15, 0.15, 0.0] }; + // Advanced (ADR 0056): a negative multiplier, offsets and an alpha offset. + let mut advanced = bitmap_item(Path::rect(4.0, 20.0, 40.0, 26.0), &a, true, Affine::scale(1.3, 1.1)); + advanced.color = ColorTransform { mul: [-1.0, 0.5, 0.2, 0.6], add: [1.0, 0.1, 0.4, 0.2] }; + out.push(("bitmap colour effects", list(vec![tinted, nan, advanced]), view(64, 48, Some(Rgba::new(0.1, 0.1, 0.3, 1.0))))); // A short (malformed) buffer: transparent past its end; an empty image draws nothing. let short = Arc::new(anicraft_doc::Pixels { width: 4, height: 4, rgba: vec![200; 20] }); let empty = Arc::new(anicraft_doc::Pixels { width: 0, height: 3, rgba: Vec::new() }); diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 21cb4b25..fc74cc5d 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -14,14 +14,14 @@ //! 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, plug-in frame scripts (they need the plug-in host) and kept scripts +//! 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::stroke_outline; 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_doc::{BlendMode, ColorTransform, 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}; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; @@ -90,7 +90,6 @@ pub struct HtmlExport { /// Notes for the report. const FILTERS: &str = "filters (not exported; drawn without them)"; 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 outside the ActionScript subset (not run; kept in the document only)"; @@ -140,15 +139,14 @@ fn matrix(m: &Affine) -> Option { Some(json!([num(a, 1e5), num(b, 1e5), num(c, 1e5), num(d, 1e5), coord(e), coord(f)])) } -/// `[alpha, tint r, g, b, tint amount]`; `None` for no effect. -fn effect(fx: &ColorEffect) -> Option { - if *fx == ColorEffect::default() { +/// A colour transform (ADR 0056): `[red, green, blue, alpha multipliers, red, green, blue, +/// alpha offsets]`; `None` for no effect. +fn effect(fx: &ColorTransform) -> Option { + let fx = fx.sanitized(); + if fx.is_identity() { return None; } - let t = fx.tint.sanitized(); - let a = if fx.alpha.is_finite() { fx.alpha } else { 1.0 }; - let k = if fx.tint_amount.is_finite() { fx.tint_amount } else { 0.0 }; - Some(json!([num(a, 1e4), num(t.r, 1e4), num(t.g, 1e4), num(t.b, 1e4), num(k, 1e4)])) + Some(Value::Array(fx.mul.iter().chain(fx.add.iter()).map(|v| num(*v, 1e4)).collect())) } /// SVG path data (what `Path2D` reads), three decimals; empty when a point isn't finite. @@ -328,7 +326,7 @@ impl<'a> Bake<'a> { i } - fn paint(&mut self, p: &Paint, el: &Element) -> usize { + fn paint(&mut self, p: &Paint) -> usize { let stops = |s: &[anicraft_doc::GradientStop]| -> Vec { s.iter() .map(|g| { @@ -345,9 +343,6 @@ impl<'a> Bake<'a> { Paint::Radial { center, radius, stops: s } => json!({"r": [coord(center.x), coord(center.y), coord(radius.max(0.0))], "st": stops(s)}), Paint::Bitmap { bitmap, repeat, matrix: m } => match self.doc.bitmap(*bitmap) { Some(b) => { - if el.color.tint_amount > 0.0 { - self.notes.entry(BITMAP_TINT).or_default().insert(el.id.0); - } let n = self.images.len(); let i = *self.image_ix.entry(b.id.0).or_insert(n); if i == n { @@ -378,11 +373,11 @@ impl<'a> Bake<'a> { /// A shape item: `p` path, `f` paint, `s` stroke `[r, g, b, a, width]`, `k` its style when /// not round and solid (`c` cap, `j` join, `ml` miter limit, `d` dash lengths and `o` their /// offset, in local units like the width), `eo` even-odd, `m` transform, `c` colour effect. - fn shape(&mut self, path: &Arc, m: &Affine, fx: &ColorEffect, fill: Option<(&Paint, &Element)>, stroke: Option<&anicraft_doc::Stroke>, rule: FillRule) -> Value { + fn shape(&mut self, path: &Arc, m: &Affine, fx: &ColorTransform, fill: Option<&Paint>, stroke: Option<&anicraft_doc::Stroke>, rule: FillRule) -> Value { let mut o = Map::new(); o.insert("p".into(), json!(self.path(path))); - if let Some((p, el)) = fill { - o.insert("f".into(), json!(self.paint(p, el))); + if let Some(p) = fill { + o.insert("f".into(), json!(self.paint(p))); } if let Some(st) = stroke { let mut s = color(st.color); @@ -417,22 +412,22 @@ impl<'a> Bake<'a> { // caps, joins and dashes included). Some(st) => { if let Some(p) = &s.fill { - out.push(self.shape(&s.path, &el.transform, &el.color, Some((p, el)), None, s.fill_rule)); + out.push(self.shape(&s.path, &el.transform, &el.color.transform(), Some(p), None, s.fill_rule)); } let outline = stroke_outline(&s.path, &el.transform, st, crate::TOLERANCE); if !outline.is_empty() { let fill = Paint::Solid(st.color); - out.push(self.shape(&Arc::new(outline), &Affine::IDENTITY, &el.color, Some((&fill, el)), None, FillRule::NonZero)); + out.push(self.shape(&Arc::new(outline), &Affine::IDENTITY, &el.color.transform(), Some(&fill), None, FillRule::NonZero)); } } - None => out.push(self.shape(&s.path, &el.transform, &el.color, s.fill.as_ref().map(|p| (p, el)), stroke, s.fill_rule)), + None => out.push(self.shape(&s.path, &el.transform, &el.color.transform(), s.fill.as_ref(), stroke, s.fill_rule)), } } // The camera is the view, not artwork (ADR 0027): it is baked into the layers. ElementKind::Camera => {} ElementKind::Text(t) => { let fill = Paint::Solid(t.color); - out.push(self.shape(&t.outline, &el.transform, &el.color, Some((&fill, el)), None, FillRule::NonZero)); + out.push(self.shape(&t.outline, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero)); } ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => { let (Some(&y), Some(sym)) = (self.symbols.get(symbol), self.doc.symbol(*symbol)) else { return }; @@ -446,7 +441,7 @@ impl<'a> Bake<'a> { if let Some(m) = matrix(&el.transform) { o.insert("m".into(), m); } - if let Some(c) = effect(&el.color) { + if let Some(c) = effect(&el.color.transform()) { o.insert("c".into(), c); } match sym.kind { diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index 6cda20cf..75d93e90 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -110,10 +110,14 @@ if (p.b !== undefined) { const im = images[p.b]; if (!im || !im.complete || !im.naturalWidth) return "rgba(128,128,128,1)"; - const key = f; + // A colour effect beyond alpha draws the bitmap's pixels through it (ADR 0056), as the + // renderer does: once per bitmap and effect while the effect stays the same. + const recolour = AniCraft.recolours(fx); + const key = recolour ? f + ":" + fx.join(",") : f; let pat = patterns.get(key); if (!pat) { - pat = g.createPattern(im, p.rep ? "repeat" : "no-repeat"); + if (patterns.size > 256) patterns.clear(); + pat = g.createPattern(recolour ? recoloured(im, fx) : im, p.rep ? "repeat" : "no-repeat"); if (pat && p.m && pat.setTransform) pat.setTransform(new DOMMatrix(p.m)); patterns.set(key, pat); } @@ -122,6 +126,31 @@ return null; } + // `im`'s pixels through colour transform `fx`, on a canvas of its size. + function recoloured(im, fx) { + const c = document.createElement("canvas"); + c.width = im.naturalWidth; + c.height = im.naturalHeight; + const g = c.getContext("2d"); + g.drawImage(im, 0, 0); + let px; + try { + px = g.getImageData(0, 0, c.width, c.height); + } catch (e) { + return im; + } + const d = px.data; + for (let i = 0; i < d.length; i += 4) { + const o = AniCraft.applyEffect(fx, [d[i] / 255, d[i + 1] / 255, d[i + 2] / 255, d[i + 3] / 255]); + d[i] = Math.round(o[0] * 255); + d[i + 1] = Math.round(o[1] * 255); + d[i + 2] = Math.round(o[2] * 255); + d[i + 3] = Math.round(o[3] * 255); + } + g.putImageData(px, 0, 0); + return c; + } + function draw() { const stack = [{ ctx: ctx, canvas: canvas }]; const masks = new Map(); @@ -150,7 +179,7 @@ const style = paintStyle(g, it.f, it.c); if (style) { const bitmap = movie.paints[it.f] && movie.paints[it.f].b !== undefined; - g.globalAlpha = bitmap ? Math.min(Math.max(it.c[0], 0), 1) : 1; + g.globalAlpha = bitmap && !AniCraft.recolours(it.c) ? Math.min(Math.max(it.c[3], 0), 1) : 1; set(g, it.m); g.fillStyle = style; // A bitmap without Allow Smoothing keeps hard pixel edges (ADR 0050). diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index ceb92473..9bcdd97d 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -25,7 +25,7 @@ var AniCraft = (function () { 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]; - const NO_EFFECT = [1, 1, 1, 1, 0]; + const NO_EFFECT = [1, 1, 1, 1, 0, 0, 0, 0]; const EMPTY = { l: [] }; // ----- geometry ------------------------------------------------------------------------------ @@ -59,18 +59,29 @@ var AniCraft = (function () { return mul(mul(mul([1, 0, 0, 1, q.tx, q.ty], [c, s, -s, c, 0, 0]), [1, 0, q.k, 1, 0, 0]), [q.sx, 0, 0, q.sy, 0, 0]); } - // ----- colour effects: [alpha, tint r, g, b, tint amount] --------------------------------------- + // ----- colour effects (ADR 0056): [r, g, b, a multipliers, r, g, b, a offsets] -------------------- - // ColorEffect::concat: tints keep the stronger one; alpha multiplies. + // ColorTransform::concat: `o` applied after `i`, exactly. function concat(o, i) { - const t = i[4] >= o[4] ? i : o; - return [o[0] * i[0], t[1], t[2], t[3], t[4]]; + const out = new Array(8); + for (let k = 0; k < 4; k++) { + out[k] = o[k] * i[k]; + out[k + 4] = o[k] * i[k + 4] + o[k + 4]; + } + return out; } - // ColorEffect::apply on straight [r, g, b, a]. + // ColorTransform::apply on straight [r, g, b, a], clamped. function applyEffect(fx, c) { - const k = Math.min(Math.max(fx[4], 0), 1); - const a = Math.min(Math.max(fx[0], 0), 1); - return [c[0] + (fx[1] - c[0]) * k, c[1] + (fx[2] - c[1]) * k, c[2] + (fx[3] - c[2]) * k, c[3] * a]; + const out = new Array(4); + for (let k = 0; k < 4; k++) { + const v = c[k] * fx[k] + fx[k + 4]; + out[k] = Number.isFinite(v) ? Math.min(Math.max(v, 0), 1) : 0; + } + return out; + } + // Whether it does more than multiply alpha (a bitmap then needs its pixels recoloured). + function recolours(fx) { + return fx[0] !== 1 || fx[1] !== 1 || fx[2] !== 1 || fx[4] !== 0 || fx[5] !== 0 || fx[6] !== 0 || fx[7] !== 0; } // ----- dictionaries ------------------------------------------------------------------------------ @@ -182,7 +193,7 @@ var AniCraft = (function () { } if (ov.alpha !== undefined) { fx = (fx || NO_EFFECT).slice(); - fx[0] = ov.alpha; + fx[3] = ov.alpha; } return { m: m, c: fx || NO_EFFECT }; } @@ -313,13 +324,14 @@ var AniCraft = (function () { // Outside the player (a button's hit area): movie clips where the timeline has them, // buttons on Up. else local = sym.kind === CLIP ? e.af || 0 : 0; - const fade = Math.min(Math.max(fx[0], 0), 1); + // Alpha alone fades the instance as one; an alpha offset stays on each item. + const fade = fx[7] === 0 ? Math.min(Math.max(fx[3], 0), 1) : 1; const blend = e.bl || "normal"; let color = concat(cx.c, fx), group = cx.group; if (masks === null && (fade < 1 - 1e-4 || blend !== "normal" || e.fx)) { group = dl.groups.length; dl.groups.push({ parent: cx.group, alpha: fade, blend: blend, clip: clip }); - color = concat(cx.c, [1, fx[1], fx[2], fx[3], fx[4]]); + color = concat(cx.c, fx[7] === 0 ? [fx[0], fx[1], fx[2], 1, fx[4], fx[5], fx[6], 0] : fx); } if (v && group !== cx.group) v.groupBegin(group, dl.groups[group]); const inner = { xf: xf, c: color, depth: cx.depth + 1, clip: clip, masks: masks, group: group }; @@ -837,5 +849,5 @@ var AniCraft = (function () { return s.replace(/[A-Z]/g, (c) => c.toLowerCase()); } - return { Player: Player, evaluate: evaluate, applyEffect: applyEffect, mul: mul, meanScale: meanScale, finite: finite }; + return { Player: Player, evaluate: evaluate, applyEffect: applyEffect, recolours: recolours, mul: mul, meanScale: meanScale, finite: finite }; })(); diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 84b22ce7..a6496c7e 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -1,7 +1,7 @@ use super::*; use anicraft_doc::actions::{ButtonEvent, EventHandler, PluginScript, Property, Target}; use anicraft_doc::player::{Event, NoScripts, PlayerState, start, step}; -use anicraft_doc::{ElementId, GradientStop, Keyframe, LayerId, LoopMode, Scene, Shape, Symbol, Tween, evaluate_player, sample}; +use anicraft_doc::{ColorEffect, ColorTransform, ElementId, GradientStop, Keyframe, LayerId, LoopMode, Scene, Shape, Symbol, Tween, evaluate_player, sample}; use anicraft_geom::Vec2; use boa_engine::{Context, Source}; @@ -65,7 +65,7 @@ fn fixture() -> Document { let knob = symbol(200, SymbolKind::Button, vec![layer(201, vec![kf(0, 1, vec![rect(2001, -20.0, -20.0, 40.0, 40.0, 0x3d8bfd)], vec![], ""), kf(1, 1, vec![rect(2002, -20.0, -20.0, 40.0, 40.0, 0x6aa8ff)], vec![], ""), kf(2, 1, vec![rect(2003, -20.0, -20.0, 40.0, 40.0, 0x2a64c0)], vec![], ""), kf(3, 1, vec![rect(2004, -25.0, -25.0, 50.0, 50.0, 0)], vec![], "")])]); // A looping three-frame graphic. let mut red = (*rect(3001, 0.0, 0.0, 30.0, 30.0, 0xff0000)).clone(); - red.color = ColorEffect { alpha: 0.8, tint: Rgba::hex(0xffffff), tint_amount: 0.2 }; + red.color = ColorEffect::Brightness(0.2).with_alpha(0.8); let blink = symbol(300, SymbolKind::Graphic, vec![layer(301, vec![kf(0, 1, vec![Arc::new(red)], vec![], ""), kf(1, 1, vec![rect(3002, 0.0, 0.0, 30.0, 30.0, 0x00ff00)], vec![], ""), kf(2, 1, vec![rect(3003, 0.0, 0.0, 30.0, 30.0, 0x0000ff)], vec![], "")])]); // A panel clip holding its own door (panel.door), that plays on and talks to its parent. let panel = symbol(400, SymbolKind::MovieClip, vec![ @@ -83,12 +83,13 @@ fn fixture() -> Document { on(ButtonEvent::Release, vec![Action::GotoAndStop { target: Target::new("panel"), frame: FrameRef::Number(99), scene: None }]), ]; let mut faded = (*inst(5003, 300, "", Affine::translate(500.0, 40.0), vec![])).clone(); - faded.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x00ffff), tint_amount: 0.6 }; + // Advanced, with an alpha offset (it stays on each item: no group fade). + faded.color = ColorEffect::Advanced(ColorTransform { mul: [0.4, 0.4, 0.4, 0.5], add: [0.0, 0.6, 0.6, 0.1] }); let gradient = Arc::new(Element { id: ElementId(5004), name: String::new(), transform: Affine::translate(20.0, 300.0), - color: ColorEffect { alpha: 1.0, tint: Rgba::hex(0xff00ff), tint_amount: 0.25 }, + color: ColorEffect::Tint { color: Rgba::hex(0xff00ff), amount: 0.25 }, kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 100.0, 40.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(100.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xffffff) }, GradientStop { offset: 1.0, color: Rgba::hex(0x000000) }] }).with_stroke(Rgba::hex(0xffff00), 2.0)), }); let mut mask = Layer::new(LayerId(6), "mask"); @@ -262,7 +263,7 @@ fn same_display_list(js: &mut Js, m: &Movie, doc: &Document, st: &PlayerState, w } assert_eq!(a["s"].is_array(), b.stroke.is_some(), "{when}: item {k} stroke"); let c = &a["c"]; - for (i, y) in [b.color.alpha, b.color.tint.r, b.color.tint.g, b.color.tint.b, b.color.tint_amount].into_iter().enumerate() { + for (i, y) in b.color.mul.into_iter().chain(b.color.add).enumerate() { assert!(close(c[i].as_f64().unwrap(), y, 1e-3), "{when}: item {k} colour effect {c} vs {:?}", b.color); } let idx = |v: &Value| v.as_u64().map(|x| x as u32); @@ -607,7 +608,7 @@ fn sounds_carry_their_envelopes_and_volumes_and_start_in_graphics_and_clips_as_i #[test] fn hostile_documents_export_without_panicking() { let mut doc = Document::default(); - let bad = Element { id: ElementId(5), name: "x".into(), transform: Affine { m: [f32::NAN, 0.0, 0.0, 1.0, f32::INFINITY, 0.0] }, color: ColorEffect { alpha: f32::NAN, tint: Rgba::new(f32::NAN, 2.0, -1.0, 1.0), tint_amount: f32::INFINITY }, kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, f32::NAN, 1.0), Paint::Radial { center: Vec2::ZERO, radius: -5.0, stops: vec![GradientStop { offset: f32::NAN, color: Rgba::BLACK }] })) }; + let bad = Element { id: ElementId(5), name: "x".into(), transform: Affine { m: [f32::NAN, 0.0, 0.0, 1.0, f32::INFINITY, 0.0] }, color: ColorEffect::Advanced(ColorTransform { mul: [f32::NAN, 2.0, -1.0, f32::INFINITY], add: [f32::NAN, 0.0, 0.0, 0.0] }), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, f32::NAN, 1.0), Paint::Radial { center: Vec2::ZERO, radius: -5.0, stops: vec![GradientStop { offset: f32::NAN, color: Rgba::BLACK }] })) }; let fine = Element { id: ElementId(6), transform: Affine::IDENTITY, ..bad.clone() }; let missing = inst(7, 12345, "ghost", Affine::IDENTITY, vec![]); Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = vec![Arc::new(bad), Arc::new(fine), missing]; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f85251d7..467fe9bc 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,7 +13,7 @@ pub mod html; pub mod lottie; pub mod svg; -use anicraft_doc::{BlendMode, ColorEffect, DisplayItem, DisplayList, Document, Paint, Rgba, evaluate}; +use anicraft_doc::{BlendMode, ColorTransform, DisplayItem, DisplayList, Document, Paint, Rgba, evaluate}; use anicraft_geom::{Affine, FillRule, Rect, Vec2}; use paint::{Premul, Shader, premultiply}; use raster::{Coverage, IRect}; @@ -836,7 +836,7 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { // Caps, joins, dashes (ADR 0046) and width profiles (ADR 0018); thin strokes and // sub-pixel dash patterns fade instead of dropping out. let (polys, alpha) = stroke::stroke_geometry(&lines, st, &m, true)?; - let fx = ColorEffect { alpha: item.color.alpha * alpha, ..item.color }; + let fx = ColorTransform::alpha(alpha).concat(&item.color); Some((polys, Shader::new(&Paint::Solid(st.color), &m, &fx, None))) }); if let Some(fill) = &item.fill { @@ -917,7 +917,7 @@ mod tests { fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::IDENTITY, layer: LayerId(0), element: ElementId(0), outline: None, @@ -980,8 +980,8 @@ mod tests { // Fading each square on its own would let the red show through the blue. let (mut r2, mut b2) = (red, blue); (r2.group, b2.group) = (None, None); - r2.color.alpha = 0.5; - b2.color.alpha = 0.5; + r2.color = ColorTransform::alpha(0.5); + b2.color = ColorTransform::alpha(0.5); let (each, _) = render(&list(vec![r2, b2]), &white).unwrap(); assert!(each.pixel(6, 1).unwrap()[0] > 0.2, "per-shape fading mixes in red"); // Nested groups multiply; a group with a bad parent link is a top-level group. diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index 4b675cf9..9857c4b2 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -1,6 +1,6 @@ //! Paint shaders: solid colours and gradients evaluated per pixel through a 256-entry LUT. -use anicraft_doc::{ColorEffect, GradientStop, Paint, Pixels, Rgba}; +use anicraft_doc::{ColorTransform, GradientStop, Paint, Pixels, Rgba}; use std::sync::Arc; use anicraft_geom::{Affine, Vec2}; @@ -20,7 +20,7 @@ pub enum Shader { Radial { inv: Affine, center: Vec2, inv_radius: f32, lut: Box<[Premul; LUT]> }, /// Samples of a bitmap: `inv` maps pixels back to the bitmap's own pixel grid. Bilinear /// when `smooth` (Allow Smoothing, ADR 0050), else the nearest pixel. - Bitmap { inv: Affine, pixels: Arc, repeat: bool, fx: ColorEffect, smooth: bool }, + Bitmap { inv: Affine, pixels: Arc, repeat: bool, fx: ColorTransform, smooth: bool }, /// Premultiplied pixels already in surface space (a filtered group): `w` wide, its top-left /// at `(x0, y0)`; transparent outside. Image { data: Arc>, x0: i32, y0: i32, w: usize }, @@ -42,7 +42,7 @@ fn sample_stops(stops: &[GradientStop], t: f32) -> Rgba { stops.last().map_or(first.color, |s| s.color) } -fn build_lut(stops: &[GradientStop], fx: &ColorEffect) -> Box<[Premul; LUT]> { +fn build_lut(stops: &[GradientStop], fx: &ColorTransform) -> Box<[Premul; LUT]> { let mut sorted: Vec = stops.iter().copied().filter(|s| s.offset.is_finite()).collect(); sorted.sort_by(|a, b| a.offset.total_cmp(&b.offset)); let mut lut = Box::new([[0.0; 4]; LUT]); @@ -56,7 +56,7 @@ fn build_lut(stops: &[GradientStop], fx: &ColorEffect) -> Box<[Premul; LUT]> { impl Shader { /// `to_pixel` maps the paint's local space to pixels. /// `image` holds a [`Paint::Bitmap`]'s pixels (an image that can't be read shows grey). - pub fn new(paint: &Paint, to_pixel: &Affine, fx: &ColorEffect, image: Option<&Arc>) -> Shader { + pub fn new(paint: &Paint, to_pixel: &Affine, fx: &ColorTransform, image: Option<&Arc>) -> Shader { let inv = to_pixel.inverse(); match (paint, inv) { (Paint::Solid(c), _) => Shader::Solid(premultiply(fx.apply(*c))), @@ -128,7 +128,7 @@ impl Shader { /// A sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), bilinear when /// `smooth`, else the pixel `q` is in, with the colour effect applied and premultiplied. /// Outside a non-repeating bitmap: transparent. -fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorEffect) -> Premul { +fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorTransform) -> Premul { let (w, h) = (px.width as f32, px.height as f32); if !(q.x.is_finite() && q.y.is_finite()) || w < 1.0 || h < 1.0 { return [0.0; 4]; @@ -173,12 +173,12 @@ mod tests { end: Vec2::new(100.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }], }; - let s = Shader::new(&paint, &Affine::IDENTITY, &ColorEffect::default(), None); + let s = Shader::new(&paint, &Affine::IDENTITY, &ColorTransform::default(), None); assert!(s.at(0, 0)[0] < 0.02); assert!(s.at(99, 0)[0] > 0.98); assert!((s.at(49, 0)[0] - 0.5).abs() < 0.02); // gradient follows the transform - let s2 = Shader::new(&paint, &Affine::scale(2.0, 1.0), &ColorEffect::default(), None); + let s2 = Shader::new(&paint, &Affine::scale(2.0, 1.0), &ColorTransform::default(), None); assert!((s2.at(99, 0)[0] - 0.5).abs() < 0.02); } @@ -188,8 +188,8 @@ mod tests { // without smoothing, each half is one flat colour up to the edge between them. let px = Arc::new(Pixels { width: 2, height: 1, rgba: vec![0, 0, 0, 255, 255, 255, 255, 255] }); let paint = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }; - let smooth = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px)); - let hard = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px)).smoothed(false); + let smooth = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorTransform::default(), Some(&px)); + let hard = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorTransform::default(), Some(&px)).smoothed(false); assert!(smooth.at(9, 5)[0] > 0.3 && smooth.at(9, 5)[0] < 0.7, "{:?}", smooth.at(9, 5)); assert_eq!(hard.at(9, 5), [0.0, 0.0, 0.0, 1.0]); assert_eq!(hard.at(10, 5), [1.0, 1.0, 1.0, 1.0]); @@ -197,39 +197,39 @@ mod tests { assert_eq!(hard.at(19, 9), [1.0, 1.0, 1.0, 1.0]); assert_eq!(hard.at(20, 5), [0.0; 4], "outside stays transparent"); // Solid shaders ignore it. - assert!(Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorEffect::default(), None).smoothed(false).is_solid().is_some()); + assert!(Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorTransform::default(), None).smoothed(false).is_solid().is_some()); } #[test] fn bitmaps_sample_bilinear_once_or_tiled() { // 2×1: black, white. let px = Arc::new(Pixels { width: 2, height: 1, rgba: vec![0, 0, 0, 255, 255, 255, 255, 255] }); - let once = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px)); + let once = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorTransform::default(), Some(&px)); let r = |s: &Shader, x| s.at(x, 3)[0]; assert!(r(&once, 0) < 0.01, "the black pixel"); assert!(r(&once, 19) > 0.99, "the white pixel"); assert!((r(&once, 9) - 0.45).abs() < 0.06, "blended across the seam: {}", r(&once, 9)); assert_eq!(once.at(25, 3), [0.0; 4], "nothing past the edge"); - let tiled = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px)); + let tiled = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorTransform::default(), Some(&px)); assert!(r(&tiled, 25) < 0.2 && r(&tiled, 35) > 0.8, "tiles repeat"); assert!(r(&tiled, 21) > 0.2, "and blend across the wrap-around seam"); // Opacity applies, premultiplied; a missing image is grey, not a crash. - let half = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorEffect { alpha: 0.5, ..Default::default() }, Some(&px)); + let half = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorTransform::alpha(0.5), Some(&px)); assert!((half.at(19, 3)[3] - 0.5).abs() < 1e-3 && (half.at(19, 3)[0] - 0.5).abs() < 1e-2); - assert!(Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(9), repeat: false, matrix: Affine::IDENTITY }, &Affine::IDENTITY, &ColorEffect::default(), None).is_solid().is_some()); + assert!(Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(9), repeat: false, matrix: Affine::IDENTITY }, &Affine::IDENTITY, &ColorTransform::default(), None).is_solid().is_some()); // The fill's image matrix places the image inside the shape: here 10× larger, from x = 40. let placed = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine { m: [10.0, 0.0, 0.0, 10.0, 40.0, 0.0] } }; - let placed = Shader::new(&placed, &Affine::IDENTITY, &ColorEffect::default(), Some(&px)); + let placed = Shader::new(&placed, &Affine::IDENTITY, &ColorTransform::default(), Some(&px)); assert_eq!(placed.at(30, 3), [0.0; 4], "before the image"); assert!(r(&placed, 42) < 0.01 && r(&placed, 57) > 0.99, "black then white, 10 px each"); // A collapsed image matrix shows nothing rather than dividing by zero. let flat = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine { m: [0.0; 6] } }; - assert_eq!(Shader::new(&flat, &Affine::IDENTITY, &ColorEffect::default(), Some(&px)).at(3, 3), [0.0; 4]); + assert_eq!(Shader::new(&flat, &Affine::IDENTITY, &ColorTransform::default(), Some(&px)).at(3, 3), [0.0; 4]); } #[test] fn alpha_effect_premultiplies() { - let s = Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorEffect { alpha: 0.5, ..Default::default() }, None); + let s = Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorTransform::alpha(0.5), None); assert_eq!(s.at(0, 0), [0.5, 0.5, 0.5, 0.5]); } } diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 55ea01dc..e5fa7e4e 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -6,7 +6,8 @@ //! way (`stroke-dasharray`, `stroke-dashoffset`; dots are zero-length round-capped dashes), //! as the renderer measures them (ADR 0046); //! * gradients keep their local geometry under a `gradientTransform`, padded at the ends; -//! * colour effects (alpha, tint) are baked into every colour and stop; +//! * colour effects (every style, ADR 0056) are baked into every colour and stop, and drawn +//! on bitmaps through an `feColorMatrix` (alpha alone as `fill-opacity`); //! * masks become `clipPath`s (fill areas only, nested through `clip-path` on the clip), and an //! empty mask clips everything, as on the stage; //! * outline-mode layers are hairlines in the layer colour; @@ -15,7 +16,7 @@ //! The output is deterministic and contains only generated ids and numbers, so it needs no //! escaping. -use anicraft_doc::{ColorEffect, DisplayItem, DisplayList, Paint, Rgba, Stage}; +use anicraft_doc::{ColorTransform, DisplayItem, DisplayList, Paint, Rgba, Stage}; use anicraft_geom::{Affine, FillRule}; use std::fmt::Write; @@ -340,7 +341,7 @@ fn effect_svg(f: &anicraft_doc::Filter, i: usize, prims: &mut String) { /// The fill attribute for `paint`, defining a gradient in `defs` when needed. `None` when the /// paint draws nothing. -fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n: &mut usize, image: Option<(&std::sync::Arc, bool)>, images: &mut Vec<(usize, bool, String)>) -> Option { +fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorTransform, defs: &mut String, n: &mut usize, image: Option<(&std::sync::Arc, bool)>, images: &mut Vec<(usize, bool, String)>) -> Option { let stops = match paint { Paint::Solid(c) => { let c = fx.apply(*c).sanitized(); @@ -350,7 +351,6 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n Paint::Bitmap { matrix, .. } => { // A pattern of the bitmap at its own pixel size, placed by the shape's transform // and the fill's image matrix. - // (Opacity comes across; tint has no SVG equivalent and is left out.) // Without Allow Smoothing (ADR 0050) the image keeps hard pixel edges. let (px, smooth) = image?; let key = std::sync::Arc::as_ptr(px) as usize; @@ -367,10 +367,35 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n }; let id = format!("p{n}"); *n += 1; + // A colour effect beyond alpha is a colour matrix on the image's pixels (ADR 0056): + // the same multiply and offset per straight channel, clamped, as the renderer's. + let fxs = fx.sanitized(); + let recolour = fxs.changes_colour() || fxs.add[3] != 0.0; + let filter = if recolour { + let fid = format!("cm{n}"); + *n += 1; + let [mr, mg, mb, ma] = fxs.mul; + let [ar, ag, ab, aa] = fxs.add; + let _ = write!( + defs, + "", + num(mr), + num(ar), + num(mg), + num(ag), + num(mb), + num(ab), + num(ma), + num(aa) + ); + format!(" filter=\"url(#{fid})\"") + } else { + String::new() + }; let m = xf.mul(matrix).m; let _ = write!( defs, - "", + "", num(m[0]), num(m[1]), num(m[2]), @@ -380,7 +405,7 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n px.width, px.height ); - let a = fx.alpha.clamp(0.0, 1.0); + let a = if recolour { 1.0 } else { fxs.mul[3].clamp(0.0, 1.0) }; return Some(if a < 1.0 { format!(" fill=\"url(#{id})\" fill-opacity=\"{}\"", num(a)) } else { format!(" fill=\"url(#{id})\"") }); } }; @@ -428,7 +453,7 @@ mod tests { fill, stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::default(), layer: LayerId(0), element: ElementId(0), outline: None, @@ -450,7 +475,7 @@ mod tests { let mut a = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::Solid(Rgba::hex(0xff0000)))); a.transform = Affine::translate(5.0, 7.0).mul(&Affine::scale(2.0, 2.0)); a.stroke = Some(Stroke::new(Rgba::BLACK, 3.0)); - a.color = ColorEffect { alpha: 0.5, ..Default::default() }; + a.color = ColorTransform::alpha(0.5); a.fill_rule = FillRule::EvenOdd; let svg = to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(svg.starts_with("")); @@ -548,7 +573,7 @@ mod group_tests { fill: Some(Paint::Solid(Rgba::BLACK)), stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::default(), layer: LayerId(0), element: ElementId(0), outline: None, diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index a0dbe1bd..36bf8407 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -5,7 +5,7 @@ //! and keyframes with durations, labels and classic tweens with their ease; shapes (solid, //! linear and radial fills, solid, dashed and dotted strokes with their caps, joints and //! miter limit), groups (flattened), rectangle and oval -//! primitives; symbol instances with their matrix, alpha and tint, loop mode and first frame; +//! primitives; symbol instances with their matrix, colour effect (every style, ADR 0056), loop mode and first frame; //! library symbols (graphic, movie clip, button) with their own timelines, nested to any //! depth; bitmaps (library items, instances and bitmap fills) whose image is stored as PNG or //! JPEG in the package; text fields, laid out with this computer's fonts (`text`, ADR 0014); @@ -15,13 +15,13 @@ //! Everything else (sound, motion tweens with property curves, unknown filters, //! bitmaps kept only in Animate's own storage) is counted in the report instead of guessed at, //! and so is whatever is drawn the nearest way AniCraft can (ragged, stipple and hatched -//! strokes, reflecting gradients, advanced colour effects, …). The self-authored corpus in `tests/corpus/` covers +//! strokes, reflecting gradients, …). The self-authored corpus in `tests/corpus/` covers //! every feature listed here, with golden renders (ADR 0035). use crate::edges::{self, Edge}; use crate::xml::{self, Element as X}; use anicraft_doc::{ - Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, + Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, ColorTransform, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, Language, Linkage, SourceScript, }; use anicraft_geom::{Affine, FillRule, Path, Vec2}; @@ -408,25 +408,34 @@ impl<'a> Builder<'a> { } } - /// An instance's `Color`: alpha, tint, or brightness (a tint towards white or black by that - /// amount, which is the same colour change). Other channel multipliers and offsets - /// (Animate's Advanced style) keep only their alpha, and are reported. + /// An instance's `Color` (ADR 0056): Animate's style comes from which attributes it has: a + /// tint (`tintMultiplier`, `tintColor`), a brightness (`brightness`, −1..1), Advanced (any + /// channel's multiplier other than 1 or an offset, −255..255), or alpha alone. Values are + /// clamped into Animate's ranges. fn color_effect(&mut self, c: &X) -> ColorEffect { - let mut fx = ColorEffect { alpha: c.f32("alphaMultiplier").unwrap_or(1.0).clamp(0.0, 1.0), ..ColorEffect::default() }; - if let Some(t) = c.f32("tintMultiplier") { - fx.tint = color(c, "tintColor", "__none"); - fx.tint_amount = t.clamp(0.0, 1.0); + let mul = |k: &str| c.f32(k).filter(|v| v.is_finite()).unwrap_or(1.0); + let off = |k: &str| c.f32(k).filter(|v| v.is_finite()).unwrap_or(0.0) / 255.0; + let alpha = mul("alphaMultiplier"); + let fx = if let Some(t) = c.f32("tintMultiplier") { + let tint = ColorEffect::Tint { color: color(c, "tintColor", "__none").with_alpha(1.0), amount: t }; + if alpha != 1.0 { tint.with_alpha(alpha) } else { tint } } else if let Some(b) = c.f32("brightness").filter(|b| *b != 0.0) { - fx.tint = if b > 0.0 { Rgba::WHITE } else { Rgba::BLACK }; - fx.tint_amount = b.abs().min(1.0); + let bright = ColorEffect::Brightness(b); + if alpha != 1.0 { bright.with_alpha(alpha) } else { bright } } else { - let multiplied = ["redMultiplier", "greenMultiplier", "blueMultiplier"].iter().any(|k| c.f32(k).is_some_and(|v| v != 1.0)); - let offset = ["redOffset", "greenOffset", "blueOffset", "alphaOffset"].iter().any(|k| c.f32(k).is_some_and(|v| v != 0.0)); - if multiplied || offset { - self.report.skip("advanced colour effects (only alpha kept)"); + let t = ColorTransform { + mul: [mul("redMultiplier"), mul("greenMultiplier"), mul("blueMultiplier"), alpha], + add: [off("redOffset"), off("greenOffset"), off("blueOffset"), off("alphaOffset")], + }; + if t.changes_colour() || t.add[3] != 0.0 { + ColorEffect::Advanced(t) + } else if alpha != 1.0 { + ColorEffect::Alpha(alpha) + } else { + ColorEffect::None } - } - fx + }; + fx.sanitized() } fn instance(&mut self, el: &X, parent: &Affine, out: &mut Vec>) { diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 8e0e1fb7..c7a407a2 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -169,7 +169,7 @@ fn symbols_instances_and_the_tween_between_them() { assert_eq!((stops[1].offset, stops[1].color.a), (0.5, 0.0)); assert_eq!((*symbol, *loop_mode, *first_frame), (sym.id, LoopMode::PlayOnce, 2)); assert_eq!(inst.transform.m, [2.0, 0.0, 0.0, 2.0, 100.0, 50.0]); - assert_eq!(inst.color.alpha, 0.5); + assert_eq!(inst.color, anicraft_doc::ColorEffect::Alpha(0.5)); // Half-way through the tween (eased), the ball is between its two positions. let dl = evaluate(&doc, 5); let ball = dl.items.iter().find(|i| matches!(i.fill, Some(Paint::Solid(c)) if c == Rgba::hex(0xff0000))).expect("the ball renders"); diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index 87843e84..8a9b7ae4 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -55,6 +55,7 @@ fn import(case: &str) -> (Document, Report) { /// package uses on purpose. const REPORTS: &[(&str, &[(&str, usize)])] = &[ ("bitmaps", &[("instances of missing bitmaps", 1), ("missing bitmap files", 1)]), + ("colour", &[]), ("filters", &[("unknown filters", 1)]), ( "gradients", @@ -75,7 +76,7 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[ ("shapes", &[]), ( "symbols", - &[("advanced colour effects (only alpha kept)", 1), ("instances of missing symbols", 1), ("missing library files", 1), ("reverse loop modes (played forward)", 1)], + &[("instances of missing symbols", 1), ("missing library files", 1), ("reverse loop modes (played forward)", 1)], ), ("text", &[("dynamic and input text fields (imported as static text)", 2), ("text fields (no fonts on this computer)", 4)]), ("tweens", &[("motion tweens (kept as keyframes)", 1), ("tween spins (turned the shortest way)", 1)]), @@ -174,16 +175,35 @@ fn symbols_keep_their_kinds_loop_modes_and_colour_effects() { let loops = &doc.timeline(0).layers[2].keyframes[0].elements; let modes: Vec<(LoopMode, u32)> = loops.iter().filter_map(|e| if let ElementKind::Symbol { loop_mode, first_frame, .. } = &e.kind { Some((*loop_mode, *first_frame)) } else { None }).collect(); assert_eq!(modes, [(LoopMode::Loop, 0), (LoopMode::PlayOnce, 1), (LoopMode::SingleFrame, 2), (LoopMode::PlayOnce, 3), (LoopMode::Loop, 0)]); - let fx: Vec<_> = doc.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| (e.color.alpha, e.color.tint, e.color.tint_amount)).collect(); - use anicraft_doc::Rgba; - assert_eq!(fx[0].0, 0.4); - assert_eq!((fx[1].1, fx[1].2), (Rgba::hex(0x0000ff), 0.7)); - assert_eq!((fx[2].1, fx[2].2), (Rgba::WHITE, 0.6), "brightness up is a tint towards white"); - assert_eq!((fx[3].1, fx[3].2), (Rgba::BLACK, 0.5), "brightness down is a tint towards black"); - assert_eq!((fx[4].0, fx[4].2), (0.8, 0.0), "advanced: alpha kept"); + let fx: Vec = doc.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| e.color).collect(); + use anicraft_doc::{ColorEffect, ColorTransform, Rgba}; + assert_eq!(fx[0], ColorEffect::Alpha(0.4)); + assert_eq!(fx[1], ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.7 }); + assert_eq!(fx[2], ColorEffect::Brightness(0.6)); + assert_eq!(fx[3], ColorEffect::Brightness(-0.5)); + assert_eq!(fx[4], ColorEffect::Advanced(ColorTransform { mul: [0.2, 1.0, 1.0, 0.8], add: [0.0, 120.0 / 255.0, 0.0, 0.0] }), "advanced: every channel"); assert_eq!(doc.timeline(0).layers[1].keyframes[0].elements[0].name, "spinner", "a movie clip keeps its instance name"); } +#[test] +fn colour_effects_come_across_in_every_style() { + use anicraft_doc::{ColorEffect, ColorTransform, Rgba}; + let (doc, _) = import("colour"); + let fx: Vec = doc.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| e.color).collect(); + assert_eq!(fx[0], ColorEffect::None); + assert_eq!(fx[1], ColorEffect::Brightness(0.5)); + assert_eq!(fx[2], ColorEffect::Tint { color: Rgba::hex(0xE9C46A), amount: 0.6 }); + assert_eq!(fx[3], ColorEffect::Advanced(ColorTransform { mul: [-1.0, 0.5, 1.0, 1.0], add: [1.0, 0.0, -60.0 / 255.0, 0.0] })); + assert_eq!(fx[4], ColorEffect::Alpha(0.25)); + assert_eq!(fx[5], ColorEffect::Brightness(-0.4)); + let pair = doc.library.iter().find(|s| s.name == "Pair").expect("Pair"); + assert_eq!(pair.timeline.layers[0].keyframes[0].elements[0].color, ColorEffect::Tint { color: Rgba::hex(0xFF0000), amount: 0.5 }); + let ends = |l: usize| (doc.timeline(0).layers[l].keyframes[0].elements[0].color.style(), doc.timeline(0).layers[l].keyframes[1].elements[0].color.style()); + use anicraft_doc::ColorStyle; + assert_eq!(ends(1), (ColorStyle::Tint, ColorStyle::Advanced)); + assert_eq!(ends(2), (ColorStyle::Brightness, ColorStyle::Brightness)); +} + #[test] fn tweens_keep_their_kinds_eases_and_hints() { let (doc, _) = import("tweens"); diff --git a/crates/xfl/tests/corpus/colour/DOMDocument.xml b/crates/xfl/tests/corpus/colour/DOMDocument.xml new file mode 100644 index 00000000..75bbeedb --- /dev/null +++ b/crates/xfl/tests/corpus/colour/DOMDocument.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/colour/LIBRARY/Chip.xml b/crates/xfl/tests/corpus/colour/LIBRARY/Chip.xml new file mode 100644 index 00000000..f4effcc3 --- /dev/null +++ b/crates/xfl/tests/corpus/colour/LIBRARY/Chip.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/colour/LIBRARY/Pair.xml b/crates/xfl/tests/corpus/colour/LIBRARY/Pair.xml new file mode 100644 index 00000000..109c282a --- /dev/null +++ b/crates/xfl/tests/corpus/colour/LIBRARY/Pair.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/colour/colour.xfl b/crates/xfl/tests/corpus/colour/colour.xfl new file mode 100644 index 00000000..860a820e --- /dev/null +++ b/crates/xfl/tests/corpus/colour/colour.xfl @@ -0,0 +1 @@ +PROXY-CS5 \ No newline at end of file diff --git a/crates/xfl/tests/corpus/colour/golden/frame-000.png b/crates/xfl/tests/corpus/colour/golden/frame-000.png new file mode 100644 index 0000000000000000000000000000000000000000..1680e4382727f2f0e0252777c292878b88d5408b GIT binary patch literal 2656 zcmeH}ZA=qM7{@UrYA{NSm?jcky&5G);zm5>5~zy^wrCDSC5MX4OvrIga8-Q968`b9sU->%8bJehs= z**yEpKmVDst?B%^5sM zBz>6WGLM4AKjGyP`Zh5{SWETYvEHkcSxoIPd>LNe+2*r*vEe%eGpLJUN7V_G zaw4Lq@3CS2-CXrkh1?}XS*+iGO_q6TP|U1`s`V55MHe|nDcjyKjt$ElqjO}LiSEA~ zYA8@L!_+H19jpheR{mgHoC0ZlXd*d@xxQr7Rk0aS_%W5a^U;(!D(C7&g4Hv9%0v_t_JxIYF}) zu^@CLAF=2#1aere{QXm199~Y+B^mDsYf#_I8NXWadY6F*RZD^|2(!Xzao;}+1=?eM zztGXk>_hi;ucXCmp^6=l6PGx~c-Dp?OdG{R=Mg3se(Fc4>i3)URUG4Bf8Yc9+gJ5$ zo+t{Ov@Aw#mW=%Fbjp58;IOz z|GvSOsAq%V4`dLmo9xQ6g!ir!@|66x=hOaOW*8sL_9a&3=G(jlFQeO#bE&CV!u;tq zc)H(rU0e$V1l0p9p!Dk+FZO=7IABC>a~3duS{nL5h{3cDr~nBw(dkIF8n{9p5;Q%l zu&25>58W%?h#^nN)R!Esfk|Y*ikpE3qel#`Td-+bgISRGNs3jE!E*Z-UH(5epHX}h aD1L={^U|dD@Ehpn7?zfrp3<1S=gddrC`TFq literal 0 HcmV?d00001 diff --git a/crates/xfl/tests/corpus/colour/golden/frame-006.png b/crates/xfl/tests/corpus/colour/golden/frame-006.png new file mode 100644 index 0000000000000000000000000000000000000000..3ab331dbd8153ec14ce746e612774309fee8989d GIT binary patch literal 2782 zcmeH}ZA?>F7{^&mhN*MJ$kJqFUR@U@V%CjqVp8C42vRT;ahhfu_AUeG=Egc^v=k^O zz7Qf6YnKQrSeUCLi;;$rfQ))OU)nOE)Uh!nl@^LnE47!>mcHDVvtzPlnTem~KA1E) z_dLmc?#X%1FaP_0&av&=@|W{o}o1&dO&V z{Jf<7mG_&>ekk`f4h(gCy|uKn+}`uo`0Tj0sZg&?f8%9e^kDD4s_*MXpN|&xSa(U- z@Z0}6>{oPA%sx)QUZ-o{6gJ41i})-)Qcn)01PIB3|mTNp&9w?D|MaHvG4ChJAs&b{k`|7AV_^mK- z(~wFA_}QnRn4&)+22`#J8N0~jS9y!zCSe2K?|vSYdF?=kUv~717Wcx(&gdwUAFB_u zpGuRR5eXOqx+LWp$!wngoN@jKw9uJB=SY*))pNaWe54e_EQ(@gJWD>0d0y!3KL!M4 z_RMBJJ*-D8a08W(SeT8mQcj?}H)u!~Hc(7m(F{I9ljHn_^Obi#G-g4~D*88kSmm<$ z`i?-c{;P?1nUpp5**?Q5;vB~)hJ+?Our((#S9850?}h_Xo({VQVO*K?<#7>lLrhg2>Rn0gPT zNZDeYA$3*w519?2HiteuVP2wYICGwSU%RrCfRpH_}!U}Yt(y2x)8bQc{Fx_fa z>_M2K%i3-NU0B&Iyqo90+*@1C39=SDKr7$WHnBeuYNS&?wL~&sO*(C?t7{Q(!-zZ_#ep1GCq2GO&;0n3K&8Tz0QUjF&Hb4y- zXf}QWuObJ=?(HUGCgdhZ02^k&!lP?IyIkqvBhO6YLe2pEg(m$Lj03tlU;Gl^AW&9xP%-%JuP3%11zc=`!EsU>Dqr z+8}z^TCZo%O{3ey@3tuKZ)IkByR%O~aS_|9pL{5slK5x; fE0D+f5Vzt6R=B#!wt5q~w3N@aw!x_el4r!MHo-O`_-Jg;S(Ew9UkNk)Yd$+L%8DRk9VE8 z|CPhzK_KvTO-%KFu&qhWvuppl-uYB~Qt_Vj-a z&7vWHdJjpfZwc?>9HANo!!e64H%eqp1 zh`OZ*u>7gFxD!&>K7J;eX0~|iz*A@^cHXlF%Dk|@BFO(_Z=YxRO(J1UGn4JH%-fto zBF@IAa8-fi2;0pF9ybKOg&z_XscKH4OnhV5gISvJq)Aktwp9rN$l`kS`3{`6(_Yz2 zP0eT^3ry!{LKfqOWD`k~{648GLp%NHwz>t(lG59#%O{1`UNckyd2#AzY)0xb`$j$n zEY16K&!;zRvb#rgvx3$qft++ou%lFC1!+Yfrf0eC9*D_<9()+c9kFSBH`O@rNZy2h zJF6u3aSHJR<{~Jw?Z$g9BF9#4UNGuIgD_j*PyGa01U2LrfQ2N>G*eO+9e2J2Q+j^1 zO;=hR`;~9TRVFelgQCxfeb+I|=0?Ff@Z5w}^e7rV&Yi|pxR8)R7F~G61TkId743qU z5_!tYxGE+&gZ{<{o*ix#leDU6KYomARL(W826B$`TwlDRT05P!Ox7}4%iNhR)41P? z7woj(*$@E^C3yu2!e&M+Gziyjw7UmDOz(U||2b?L(Pm^)O0ku*Glp0`KiC61zz@pQ z%bZmc+C)KEjb>c%WXwQ{)k$;qg)E1E=ZAhQ%!Gr>C=jjxCr4p1Bk~pZ7+_)X ztGKxV?1p1Ek;s4GtM)JfcLQp5#NO*?aR6}l3Z8LSLhRnQMNmo>7M zdu|CFSpuVo*hRo%DJqWKtIO%;HCurgi(WF!V-|Yl(gU~a=YJsV+>&861o!s928g=y>hyDO`#jj`p literal 0 HcmV?d00001 diff --git a/crates/xfl/tests/corpus/symbols/golden/frame-000.png b/crates/xfl/tests/corpus/symbols/golden/frame-000.png index 29a5bb2d16beb8090582e4cadf31e8c392a4e7e1..de5a3e3ce26b0794b9726baa94affef2e188b72a 100644 GIT binary patch delta 1869 zcmb`IZB&!z8OL?A)6PKzj$}AUy7@v|i=m}xsgPJL&GB$F?K~ap7>Vea9A+UnIugjs zU4s=R+UQ|zEPY0v`gF8o^IXl*#vy2G&~!KC2w^rMg5XBEpzP^tyr5LS=icT z9Cc-%*%d{7K&Dc2ciKW!pcX|_F!+OU*A6?@$R9k9)w@l*1)1IwpJ6G{g~gS6%}rf1 zf30=*KS3Tr0vX@TD|Q77-T`-Cca$vgB|C;U==%zZarAs(oH?tGDq z0yJ_Qfhqduxd3}4G7`GOZ|@v-B>=Ezy^gJazWrmq|8putJNU&7q==4n;Z6;n&ZtpJ zt}9&|jSFcnv^}gB+YHcv{Uz9yjr>|Zhg~?yQ(m3;XrJ=zMi;muz(3PC77STLo6UEb zF<2bY;g81!e!A1ukR+XNww-mCM~=V_^{53P+Ee4p(6E9%{>{8wmXIV8LvDc);uqqv zrs6Wo(BLWGU_Oz4*en#+2fVY=1QWpVellW*sYd)AU+rB$`NRZ&4v{z-Y{{i+3QFht~3X-0iG8 zS3uM+jgyTXj>Qrc^}pNTIwQtvAh$@{tW!y}VC)!d@pV=4!#7zji_cgE6s$@`$Z@&^ z+z0t%Wu^=wMM}7}lZDd#c%GP`?xu-{V#s)CaSpn}AaO0qM?U9>whkH|>?Y&+6`oeT zWk5Og%qr|`|BLoe7S3M077{YJmvS*9JZX2_=6Qp{YPMmW#rxgP@~53?Au7jJ3I-t1 zN0r)&)WjEepgyH!CdSIMhC9Nu+Qls;qW)q$?;lLenGr-OF1w@P_7O1_#lOGt!xc}+ zC*C!}qOf9~4I^Crb6Qkl?}hrlrOds=(z&CJlUm{mOScR!otVzD$=5I5w3F)_ZyplvTv& z?}sE5^73ji>XX$8I>Me@QI>7;9Y)Vav@kT*vj=}f4-^XQJy1X0U=ktwKrljn`D!|m z!kq2ZPENnQ%y@1O{Z?zi@(b`DVOBZOb3h(p2L2$tm&3dOPdV0x3@fw86*Pg-U(zHLmQttPM4HVJIR(_su!$ph#`< zG2+kb5+Nc+->dQz1hl{E;VjL*9KE7LdGp)}@k5<>T{~vIbXSQ#$@O=66{*Ym2Iu&l zGtHgL5%^SQ-{)!Xil^=W^Ys72(%^eMjg7F#H0d;=m;y3E#e?J6JtcTXttwW}cW??} z$67{BLtI`ax}7fD*7z(Fm+V4K5X*m6=*)$&MfmkMnvbdq@ul%Z4-L6G{JOEHii=ln z`?|5eN%F*vDgkO;$;E|FxOI&1h~;nJ>@PzrLc|VmTd$(_<)pN@(^@3?H8Sdto+j_E zmfz@M29X&`q@nhiZu22y;E=sOE|6hS6#IlD<71*o#)Cle#E6PhHgrJCjt!}HgzFfO z-4SSNgUX#F696cRIa}L)a?#}dnt^+H=I327Qg0qtveSsfZ_5|3>&KN)yoY7jp9JaR%)x(O@KZpf^uf@!X$;f z<6Le>4p!0GaRPy0pG(IR^ns>%N{atsN+~aW&_-k2>$K+bc@DcRX-Il0uP{}6l%R|~ zqARR5T?7a{#--y%HA{rETr%W>1N&C=NTVPCUjk5ZakJGoCYa4E z-7Q;rhphQWEix=kH|y3IcaF_1Z?^>LxA5P4U&@;=92$*CfSu(u@MAgY>0Mz51JD=}D= zf&-kX08|0QLuKt_)@`xwjWju<+ZF+tW!McycOU}WgU!$l;;@T4F70Mda3>zc^$DAV zD`rs7#~l3s`@SBcYDc6QKDqBNWV&T#ezkjU@Hn^U z%uq)q5Z9Eo*4R`8;VOYKUC~uJ-jFgC`jeX9ginJTnSRJ&Hd@*M*X|ZnFqP}Pfq$cF z{5#bNX))2OJ6i?BQrw^CyD8nUiW4ud3^Sfv#VNy9WX=Hw-i&4`%rQ`8Opt;{k==ii zOpO|5rUYvqHJUH`NzTy$#^%E))(!6>+~u_RyBWeA z(_H3#WS*p=D*9t7_-h-{C$dKz$IhZGXQD*7o8(`T-RHGwK{e)?U0~Bp zhgx|bikZ;l!Owd4sw&{2LzvGS#@Qr8=jdFVz3cYoeAlNiT=%g)j5EVvoCm_VX=wnR8{$76dEVAa5eNHqL!zh+ZCx;Zw?Np7ECLDSWQ);{K4NtmS;t#AIy@>-DTb z!GQv}9r@A-db#Lq-!}QakbIjs;_yY>+Y%dL1oCYtE%#3 zcsd(=TJ{*ZtUDjjqdG}&BM8*s_w{_;3-{eAY)u-pAV#7b&L8QDTyDk7HHix@FYv@K zLT*kXTNh>;zjCGpINKGz1lskJyX3;i-#-UE{vMyabXU)g&|Je`s$**oN=UX3G_0ag y@aD6H-O^QkKAL>3D55$qdjIOR<@_ihV3D5_Wj(O?&md&=966N!cFS8im;VZ$>DL1Q diff --git a/crates/xfl/tests/corpus/symbols/golden/frame-005.png b/crates/xfl/tests/corpus/symbols/golden/frame-005.png index 3284d917225c041e8b0982f9d3fb262402b20b1e..451cc997fa7d979aa4a3b6ed2efc6218be833ac9 100644 GIT binary patch delta 1869 zcmZ9Mdr(tn8pg%S(rRgn6{6fS9i-TGV!Tu?a>-VA7rRVhcbv*hkp!0_Q;`P5H3>=1 zaiL<1mDJ4&mMF1U#Z^OeXayn3kqsd&ASqHBZpk4xqJTNM5R#LeoUXJ*p4YhsXM`62Ct`9`?>k3! z68*|~E%5~fz|1{x`(eN$H8kvri<55?&29$4c?*w*N7LEQoSWU)%gz{0qKenX+0s}C zhOK`7XWM=D=WODkq-@9nP?n$2R6J-P&(-dqrW1RBr%s_6tYdRWO409I!0&Mk~!Xt^MYw{WUJG7k>-vl8edeJZh(HPp6=`v5vg9 zICjTn;t!O77#gMMxhdX0pyE8GcDVc4;q|oJZ0swEX+@EZe`l~?q>WYv`miZI+d;9; zUrhj(Lpj*M(}6>XsclBLIWsE*Ue1}k!&mKx3>y$&+AbVK8mIh!?!!+|UO493f+KJF>O z>#?z`Y}b7VUCjECET6A%_mXN~Ct_u|Xg&EbmX!-lTHN=*-dSkqfVC7O$Q_C?l(-Z$qn6e&WW3R-M$GX5e=YeHt-U7K0+`Z zS8XqQfOd0+ONCZJzA~P+W)*=jz!zF`1&(QZm0adjp(Qc%6~)mcPJaURThc8PfwJYR?^5hHBsVm|k9 z&gClB(Y}}HYa(DrAvhw@3nGYEa5)iCzZ9H6h?mBH3aPwBf*P(L2w9NA{6~WgXt(d% z0`%49;Ut`D2LmH5#y4r`PMn&0-4>uM=gZeTeNxqrWeR?v5K;7?C8ZjYDs39WLS=f6 z#LaU4e{kVw7tcNyhc5`xu0CXrX%-sH3eGji9|TKUV~H4w$Ed41wGF2#Jz~=2){+hsVro*Ne(=|c0C}WoCVmZ%B*sUFOse|P#W7ZCMbbCWW z{CAWMGi}vzM9dwq0N~~;u=>!}CYLrb0hQSG0vyEgHRRupO(?uoP{i|ia{x9`{}Y83 zDTcfPQpiK_xJ;9owUFEc|2F-^7wPNqfA{s+nrg5j4AU}ITI|!1YK(Rw%Xc#rJK)iQ zXPG$4w1TkdUCGLyukgOA#Hj|?WGPo7qG^65V2qVx-ol?o@Kn4gdP?}d`Qz_dP!E4Tb4BE^9bh>3?Gri zVDu}%LZPs_Dg=4aiDG7&x!zz+y7w4r*s8RoKy}(m@Y7vH?0&xLeU{pzPyLnQ-!1;k zX^{j!w&$eJ0kV_k3w-OMGKXLwzCCpHa~=}GEUdQ$%SDrIqeFC3)8E*+>29$yC&F{~fzPd7Oc(e90`)Om~B z9(*4^#!aI&wtRR*TYem#KfO}J5 zo>S&~m?zX+w&i}-oxZZ!;2s$M>n3c&k2j2UXrccBgjOisETSQB^|BTn>#mJ^;BOr=D%$shik*Z{#OHl`(uvbCL~F4vgJMRvlk=O~O7A zUsSc=FI_(0M7DI!AoDh0sl_(~VG(wvIdM%V^lTr)RmS|Hn{zJB*dUhK!XNTxZ7p8O z0R67r+Ez_Dv)Eh7H~~;u^5DTvt7C@>?1L=_Tcom?I?;-xLDT27i>$ zLRTGP(_G)`i(k`RB-V?IH3x(g+fhwH)daY2^~hdm8oVeG42ig!TzbQoJqx$NWRaZ2 g7A=upi@}n%-%5YdH^*FF6MFCcDgTe1`%CKn2Lb$8=>Px# delta 1888 zcmbu9`%_bA8pm1cPTDe%!D3L6L^oP>SxC1EVNKw;J6h_vg`IT^w$*c7-Re-pfW3rV z$g8+TXo_)+HnvpLS%&R)Xi06WA>;;fi3o_G7$}4j2??l#~%F|@bJySN@nPrFYH(_EGyXTsE z%v5u?@nKb%8O#LKF~aZS*htp(d9G+N>+{hO=k9WK|7yjKw_gNA3FtzJLD#kZ0Jl~n zy=3#>7WrS^wSta)uejw9^-RtY-%20#F4TLmhs>R6M5;rITFumM^_JD5!oI0w3(Yr> zUx@?%XbJz-9yscwT6eABt!UkT;3fKWZjcYIK&^rNIWhTw1uc9c>i;?k{)-Ra26cI5 zGNQ!n;3A)o1;yd-jXo!IyI&w6X5KQZ|CO8%0GK=^nQ{=IC@nL<5QE$5?6uM(8e zx|#U{+#EJSl3#g{yf*9!r(Iy`VQ105UP;{7v0ctN0j?iu1t+>0=H9$R^&oza+#v?P zv|=vs_fjfzBi76b7p@Z+`r}S5FLP?ET1*?X?lm$^3)*`?mWtxlqE73BCOI1Ni?C5$ zP-^OEfUBb9XpYz)4;F32s6*`cVR=3b7T)z17?iTPY@4-ffF?4DzJeN{9H4K4?lYnt zljvj-Ad7IfmVTW|pYX?{HFb)5pwvi*ZS(Jl7EYRCW`@ez2?qYq2A$J|1CUFx0dt6g z9^qu?9_l*mj#|zx#VM}aU8(HFl|nsaoKCPj)KQlqV>E$Er)F{{lnm)OBK)+2+(few zT=JzPa_@PX1(0B4-T`pXg-$kEAD6Uv*XS`3HpC0g3-Jw14?6i-NFb!svL{;k#SJLkK?`um|9gaZ4-V1n$#ev0GJk( zW+78?>r7bR;;G(eA{pkbyqM(+N#I19tTz#dj2V*Mz4KcOoj!44ZM${&|8wW(>SX?B zcTz~twyW)5l5?WKP9)r_8)zD@;L>b$`3w8O6H7D=ujA0%;{n}K;M)Kcy)L^Bo*F}C^lk$*3GYm!|`x+jT2ceAnTBx z>_-AuK$Ji3>y+P7S%$~H9S#wBh9}NbJiG&P@_gpAbOKN2eP8}#lVvUccqztvgJ&NX zPfLQl)bHSgm_Am{m@UiT>E74J+6JE=6O|G(Ar6)dc7T(%()d&LC$^f#(>^e{jH0r@ znK<69Z`b_}gf^YaNMBRPjUi1(Tq9Nc?3@PVJ=1!zL&1kaN35MF<%Y^asiBxM@-;hl zffqe&>Jpfqm&jQn99^e9C(Bs2#iOvPnj;7Y;0H6P7=} zp`m>0n0Eee6WE|?!^Y;;$H;T)JIuG$v&{7@`q}O4vW8xH_I6s#(%Z8;e^>J#4psdd D;^SM# diff --git a/crates/xfl/tests/corpus/tweens/golden/frame-006.png b/crates/xfl/tests/corpus/tweens/golden/frame-006.png index 3510c5e8bd8be9a39b49c79a0de672aefb9d25a7..402e0c160b0ff4363b4f7546934742f9fb917dde 100644 GIT binary patch delta 2175 zcmaKsdsLJ68OH%D9L-oty`&aQ%4M>S*32PBmq0pJ%jnJ_V;+oWK;jLVrZk`vLV)*& zRzPGJkx>pJ#EvShsi55;AR&PQB0>mq5!XP%O`<@|jSyb)=6#npUfAVq`6qw;-rx86 zKHtytdkQueZ@v`dK78jV`5xfg{fy}}&>f0S8r%c}MXhfTg$utOQ0Wq^^=Ch=lyHI? zVXMLMV{~d1T9-TD_)E9vd){^zG}8ndI9Rxr7@c4Z_*J7a4hv8t52PRvIOvKVb@*R( zi;;|h=Id}_Fj2P1Yu(OYL@5`7>Q+ep>e-v%VLfD%n#vVuFOaEc$7OC8?*EquY2!`3|a39ltho9Lm|KHA{J#=SP?oQL=@Q)Dc1+-pSWoOm3LD$Xt%o%zfEjG}VF~npgqd zvLFM}BkqZ#Zu~B#PWUC{u**y7=ma}cQs7CwU_cAb%u_6vWtL#DjotdY`;EprT&y^=!-l%O%B&;>dZJd8 zD9|eHjGp}Pl+d62bZijmEcN27G;qpkLX5cgEw-Zwmo4htr9fM??Ofyss(b4Aey_H0 zuRu4d&6EHAyh3O9FLZLnJK-jQ1GfbCrqPS>80zG2EK>Xje{|$W$V@3p&XwlO6b06; z&_2Xr|I8CIM+233>@?l2{!blBnLd!~mo}n!3y-j5%W_Y!BOII@)iVY{##2N2_WPtL z=RD=Q=4th+N)<8=ULObGys>~aO!zB>j`jR*6=}BYv!;p{b%j3f;+!9}u_B%s;L?`Q zbbC#o(8l`I5#}x*wu68-O*lFcEMBxBJ&96F{mav-u1lS9)HiWka#thO%;x!Yw830Q zNZ2QgK(_*I^`)jc7_Y7BSXJkS81Cls>4dfhqP#=|YNf$JbwV;8*`BvwcZcwvB$A9N z$(h%9lo@-%J$&5T_kE6e=bhN* z^|&tO1WY6~=?K_a2e+k4Cwartef6N_i7FLIq1>Ad;r3$taGFfemuCP08QD{m_P@x! zo~1&UhYYp@F|whKSZ|c#+H6pMmfT2fGVsuRASo_aC?e?_fT|Yl(0P?eP3ay$;)r+vJ1UW7Ug) zV0NuUw;)j$j)W7jJX$h(e;T3WJE@?`?T)EX!M!ZZ6Wg+jgT6yXi}?N6A(!&PalWnB z578td$(cr*Jc7>8CSXyn*h;PYsHRS~Bl8EOfCLOaHE)g_lp8-tkU#Cj?E*DA{{kQF7|1###%CljMVqP@W4%JIxP;C zO^HlmpubTs2#b+-*SymE09#_PAcuI8sSX78TNTWupqC~ZCb!rblV!l~3at8lOrKz3 zTC-`>%VJLNfxzhk~j+=`~`jRhJ-NLl9U{U(Q2jsrb<4BFVh=EDECJ z2BQx|77zU0fpU7pB(d2T&YEC;vZr+-R^fOw%-f9c&4;z{2!n|khL$r*1x8z|6B!VMVrtw-m`cTz8KPdOVsDZlWAvEyIEW-)L@LiUO&dT~!Z;XWxngq?lL-=2RMv>2vpHtuKkCz&!BwPg-hb{N@4e4? z&htC($#vnn$8RJ)8dZOjFvF+mVXYOSs+)L76j(4s6mKki`Ylorh>GG zRW~|9C@jSuhB6|_EK2druT?Xyd|g_B2Eir=NXo!o2z35r@VwVmhd6ep^h1u~c~9{g z;c_IiCk)$#%LbenZ|~!??N2uK&lR+Qj{PvG`&Osf(v1bULQH7Gaz5^?_BVU#M*si5z*dZI2|4H=2zOmdAs z7X6^RX}kf4>p$1b9i+^J@{}t=y}onR46R8#H%TB@XpC=s)(6J$_wRvOYgLzRw|Igd~_> zL^{Gn`kP6&-C~r{MAO)}6{vlCO`Y1_OIsMS#6}gBgQosBr@HgUELhiDY*883Mx+AS zH-6YDR=<7aJ}ME*V}@7~O96Oo)wxx5;q}DuCQ+HaWjf^TZE)|P(-s<)fRo?8+8tUw zSLtA^siHioCNviCK)HytyE1tb?&U+IPm-t$WhFmx*g5*khkTLv3DD`NZN z@hGGZn?n4jG^WCa7@%T!YU+=WDfUd&{_h zF!Fb+RdU8wxLByUT7mx|mYkN~8c~^8t61nq@hE~KS7SXa{8w|g_>~7^dt4v92A^r# z-*9NaO3n6dq}TDT;1a7VJ8cawC9Wk5TZ;?ITh6%i;by3=NWzem-S7Q0Z{fQ#{%qDp z7c#44;LaI)T$fOda2;g&Oz;pD4)y56GE85d{KYgE<%`x3zSLhAPGI|RnndNVi%@|d z@YnIqeoX&N?+SHHEwcBMhNnjFti^cN-l1kH!{{no^ajmv-=i)@^8xw%sd>UnCH4+3 zp-C{fp?M9EN@`rpew9}WE4_UUN`exzwVvKb8uXNj6P%rdTx`8MgNwAg-CI!i>%n&1 zrceC)A;~`rz*T-|HMPeM5CB>b1^TY zY(aY&5nG2uW#{I(!V6R*1n?DVE|sC7a9b-e*$XRHFO*UY%;Bpmf=&!G=?myW5%%}0 zV8KWzynF~DX5tH^Pxe?oWE{#@LcNbX!@HWnY_}1z%2ib7TtY`fp(aq{q**!^gQ{t& z*B*q2Wc5-fx~|PAP3WbGw~>H+Jak3x24M3^Fe=pwUKPOR=Z}f(Yi~@v)cz-xukD03 zbt6&xNRbpnoF+T_O)-o20^B>t3;UucW#E%obChHa#< zMdffrDRzK9;|G_lE8!>>fo;;55b-73Sef`O=K|@Fz+8?5`x#sa$|G`JJ;IzjFE{m3 zp3Hl|geE62(Z;g1M%}eTpyi%1@=03a?H}mcJ95q?wYLN6!@8$IF7gE+NzPN+xH~s5;i<8W0|M7`pNbQSBt-7D>ES!)t&YDE3?|Xj! yif#AmXx4w6e$5+57Ob3Ewe(aM0c8UF_)VeX0m diff --git a/src/a11y.rs b/src/a11y.rs index 2e829dc5..ac2b2c3b 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -369,6 +369,18 @@ mod tests { let filters: Vec<_> = anicraft_engine::doc::Filter::KINDS.iter().map(|(k, _)| serde_json::json!({"type": k})).collect(); assert!(a.run("element.set_filters", serde_json::json!({"filters": filters})).is_some()); })); + // Each colour effect style's controls (ADR 0056), and the Motion Editor's colour rows. + for style in ["brightness", "tint", "advanced", "alpha"] { + found.extend(check(&format!("colour effect {style}"), |a, _| { + a.run("layer.select", serde_json::json!({"index": 0})); + a.run("edit.select_all", serde_json::json!({})); + assert!(a.run("element.set_color_effect", serde_json::json!({"style": style})).is_some()); + })); + } + found.extend(check("motion editor colour rows", |a, _| { + a.open_panel(Some("motionedit")); + a.me_styles = vec![anicraft_engine::doc::ColorStyle::Tint, anicraft_engine::doc::ColorStyle::Advanced, anicraft_engine::doc::ColorStyle::Brightness]; + })); found.extend(check("high contrast at 200%", |a, ctx| { let mut p = a.prefs.clone(); p.theme = crate::theme::Palette::HighContrast; diff --git a/src/app.rs b/src/app.rs index 37151273..f67c11fe 100644 --- a/src/app.rs +++ b/src/app.rs @@ -367,6 +367,8 @@ pub struct App { pub me_key: Option, pub me_drag: Option, pub me_vscroll: f32, + /// Colour effect styles the Motion Editor lists besides those the tween uses (ADR 0056). + pub me_styles: Vec, /// The frame grid was clicked more recently than the stage: Ctrl+X/C/V act on frames. pub timeline_focus: bool, /// A destructive command waiting for the user's decision (ADR 0004). @@ -530,6 +532,7 @@ impl App { me_key: None, me_drag: None, me_vscroll: 0.0, + me_styles: Vec::new(), timeline_focus: false, confirm: None, skip_confirm: HashSet::new(), diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 971a0377..8a29f683 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -120,6 +120,7 @@ fn all_keys() -> BTreeSet { } add(&doc::Easing::Linear.label()); doc::Property::ALL.iter().for_each(|p| add(p.label())); + doc::ColorStyle::ALL.iter().for_each(|s| add(s.label())); doc::ProfilePreset::ALL.iter().for_each(|p| add(p.label())); doc::Cap::ALL.iter().for_each(|c| add(c.label())); doc::Join::ALL.iter().for_each(|j| add(j.label())); @@ -578,6 +579,14 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("symbol.set_kind", serde_json::json!({"symbol": symbol, "kind": "movie_clip"})); a.run("element.set_filters", serde_json::json!({"filters": [{"type": "drop_shadow"}, {"type": "gradient_glow"}]})); })); + // Every colour effect style's controls in Properties (ADR 0056). + for style in ["brightness", "tint", "advanced", "alpha"] { + found.extend(click_everything(&format!("colour effect {style}"), |a, _| { + a.run("layer.select", serde_json::json!({"index": 0})); + a.run("edit.select_all", serde_json::json!({})); + a.run("element.set_color_effect", serde_json::json!({"style": style})); + })); + } for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } @@ -754,6 +763,13 @@ fn screen_reader_names_are_translated_too() { } crate::actions_panel::open(a, crate::actions_panel::Tab::Instance); })); + for style in ["brightness", "tint", "advanced", "alpha"] { + found.extend(untranslated_names(&format!("colour effect {style}"), |a, _| { + a.run("layer.select", serde_json::json!({"index": 0})); + a.run("edit.select_all", serde_json::json!({})); + a.run("element.set_color_effect", serde_json::json!({"style": style})); + })); + } found.extend(untranslated_names("close guard", |a, _| { a.run("layer.new", serde_json::json!({})); a.close_dialog = true; diff --git a/src/mixed.rs b/src/mixed.rs index 8fff5b41..82a35b54 100644 --- a/src/mixed.rs +++ b/src/mixed.rs @@ -5,7 +5,7 @@ //! it edits (Blending only movie clips and buttons, Looping only graphics, Fill only shapes), so //! a shape beside a movie clip never makes Blending mixed. Pure, so every row is tested here. -use anicraft_engine::doc::{Document, Element, ElementKind, Paint, Shape, SymbolKind}; +use anicraft_engine::doc::{ColorEffect, Document, Element, ElementKind, Paint, Shape, SymbolKind}; use std::sync::Arc; /// The rows whose values differ across the selection. @@ -13,8 +13,8 @@ use std::sync::Arc; pub struct Mixed { pub scale: bool, pub rotation: bool, - /// The colour effect (the Alpha row). - pub alpha: bool, + /// The colour effect's rows (ADR 0056). + pub color: ColorMixed, /// The instances show different symbols (the Symbol row, Swap…). pub symbol: bool, /// Their symbols are of different types. @@ -33,6 +33,46 @@ pub struct Mixed { pub style: bool, } +/// Which colour effect rows differ. Each value compares the elements as the first one's style +/// sees them (an element in another style counts as that style's value it would start from), +/// which is what a change sets on all of them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ColorMixed { + pub style: bool, + pub alpha: bool, + pub brightness: bool, + pub tint: bool, + pub tint_amount: bool, + /// Red, green, blue, alpha multipliers, then their offsets. + pub advanced: [bool; 8], +} + +fn color_mixed(all: &[Arc]) -> ColorMixed { + let Some(first) = all.first() else { return ColorMixed::default() }; + let style = first.color.style(); + let seen: Vec = all.iter().map(|e| e.color.to_style(style)).collect(); + let mut m = ColorMixed { style: differ(all.iter().map(|e| e.color.style())), ..ColorMixed::default() }; + match style { + anicraft_engine::doc::ColorStyle::None => {} + anicraft_engine::doc::ColorStyle::Alpha => m.alpha = differ_f32(seen.iter().map(ColorEffect::alpha)), + anicraft_engine::doc::ColorStyle::Brightness => { + m.brightness = differ_f32(seen.iter().map(|f| if let ColorEffect::Brightness(b) = f { *b } else { 0.0 })); + } + anicraft_engine::doc::ColorStyle::Tint => { + let tints: Vec<_> = seen.iter().filter_map(|f| if let ColorEffect::Tint { color, amount } = f { Some((*color, *amount)) } else { None }).collect(); + m.tint = differ(tints.iter().map(|t| t.0.to_hex())); + m.tint_amount = differ_f32(tints.iter().map(|t| t.1)); + } + anicraft_engine::doc::ColorStyle::Advanced => { + let ts: Vec<_> = seen.iter().map(ColorEffect::transform).collect(); + for (i, slot) in m.advanced.iter_mut().enumerate() { + *slot = differ_f32(ts.iter().map(|t| if i < 4 { t.mul.get(i).copied().unwrap_or(1.0) } else { t.add.get(i - 4).copied().unwrap_or(0.0) })); + } + } + } + m +} + /// Whether `values` holds two that differ. fn differ(mut values: impl Iterator) -> bool { match values.next() { @@ -76,7 +116,7 @@ pub fn of(doc: &Document, all: &[Arc]) -> Mixed { Mixed { scale: differ_f32(decomposed.iter().map(|d| d.sx)) || differ_f32(decomposed.iter().map(|d| d.sy)), rotation: differ_f32(decomposed.iter().map(|d| d.rotation)), - alpha: differ_f32(all.iter().map(|e| e.color.alpha)), + color: color_mixed(all), symbol: differ(instances().filter_map(|e| match &e.kind { ElementKind::Symbol { symbol, .. } => Some(*symbol), _ => None, @@ -174,17 +214,46 @@ mod tests { select(&mut s, &[b]); run(&mut s, "element.set_transform", json!({"sx": 2.0})); select(&mut s, &[a, b, g]); - assert!(mixed(&s).scale && !mixed(&s).rotation && !mixed(&s).alpha); + assert!(mixed(&s).scale && !mixed(&s).rotation && mixed(&s).color == ColorMixed::default()); select(&mut s, &[g]); run(&mut s, "element.set_transform", json!({"rotation": 30})); run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); select(&mut s, &[a, g]); let m = mixed(&s); - assert!(m.rotation && m.alpha && !m.scale); + assert!(m.rotation && m.color.style && !m.scale); // Editing a mixed row sets all: then it isn't mixed any more. run(&mut s, "element.set_alpha", json!({"alpha": 0.25})); run(&mut s, "element.set_transform", json!({"rotation": 0})); - assert!(!mixed(&s).alpha && !mixed(&s).rotation); + assert!(mixed(&s).color == ColorMixed::default() && !mixed(&s).rotation); + } + + #[test] + fn colour_effect_rows_compare_in_the_first_ones_style() { + let (mut s, [a, b, g], _) = session(); + select(&mut s, &[a]); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + select(&mut s, &[b]); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 20})); + select(&mut s, &[a, b]); + let m = mixed(&s).color; + assert!(!m.style && !m.tint && m.tint_amount); + // An element in another style differs in style, and counts as a tint of 0 % of white. + select(&mut s, &[a, g]); + let m = mixed(&s).color; + assert!(m.style && m.tint && m.tint_amount); + // Setting the amount on all makes them alike tints of their own colours. + run(&mut s, "element.set_color_effect", json!({"tint_amount": 30})); + let m = mixed(&s).color; + assert!(!m.style && !m.tint_amount && m.tint); + // Advanced: only the channel that differs. + select(&mut s, &[a, b]); + run(&mut s, "element.set_color_effect", json!({"tint_amount": 30})); + run(&mut s, "element.set_color_effect", json!({"style": "advanced"})); + assert_eq!(mixed(&s).color, ColorMixed::default(), "the same tint, as Advanced"); + select(&mut s, &[b]); + run(&mut s, "element.set_color_effect", json!({"green_offset": 40})); + select(&mut s, &[a, b]); + assert_eq!(mixed(&s).color.advanced, [false, false, false, false, false, true, false, false]); } #[test] diff --git a/src/motion_editor.rs b/src/motion_editor.rs index 2400e223..c0f31e29 100644 --- a/src/motion_editor.rs +++ b/src/motion_editor.rs @@ -14,7 +14,7 @@ use crate::a11y::{self, Named}; use crate::app::App; use crate::theme::{SQUARE, T, TARGET, Type, color, font, text, with_type}; -use anicraft_engine::doc::{Easing, MotionTween, Pin, Property, Props, Track}; +use anicraft_engine::doc::{ColorStyle, Easing, MotionTween, Pin, Property, Props, Track}; use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, WidgetType, pos2, vec2}; use serde_json::json; @@ -40,12 +40,24 @@ pub enum MeDrag { Scrub, } -/// The motion tween at the playhead on the active layer: its first frame, length and data. -fn current(app: &App) -> Option<(u32, u32, MotionTween, Props)> { +/// The motion tween at the playhead on the active layer: its first frame, length and data, and +/// the colour effect styles it shows (ADR 0056). +fn current(app: &App) -> Option<(u32, u32, MotionTween, Props, Vec)> { let k = app.s.active_layer()?.keyframe_at(app.s.frame)?; let m = k.motion.clone()?; - let base = m.target_index(&k.elements).and_then(|i| k.elements.get(i)).map(|e| Props::of(e))?; - Some((k.start, k.duration, m, base)) + let target = m.target_index(&k.elements).and_then(|i| k.elements.get(i))?; + let styles = m.colour_styles(&target.color); + Some((k.start, k.duration, m, Props::of(target), styles)) +} + +/// The properties the list shows: position and transform, and the colour effect styles the +/// tween uses or the artist added (Alpha when there are none). +fn listed(used: &[ColorStyle], added: &[ColorStyle]) -> Vec { + let mut shown: Vec = used.iter().chain(added).copied().collect(); + if shown.is_empty() { + shown.push(ColorStyle::Alpha); + } + Property::ALL.into_iter().filter(|p| p.style().is_none_or(|s| shown.contains(&s))).collect() } /// A readable step for grid lines across `span` (1, 2 or 5 × 10ⁿ). @@ -106,7 +118,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_filled(body, 0.0, T.panel); painter.line_segment([body.left_top(), body.right_top()], Stroke::new(1.0, T.border)); - let Some((start, frames, m, base)) = current(app) else { + let Some((start, frames, m, base, used)) = current(app) else { empty_state(app, ui, body); return; }; @@ -127,7 +139,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let rows_top = list.top() + RULER_H; // Rows that don't fit scroll with the wheel over the list. let fit = (((list.bottom() - rows_top) / ROW_H).floor() as usize).max(1); - let n = Property::ALL.len(); + let rows = listed(&used, &app.me_styles); + if !rows.contains(&app.me_prop) { + app.me_prop = Property::X; + } + let n = rows.len(); if ui.rect_contains_pointer(list) { let d = ui.input(|i| i.smooth_scroll_delta.y); app.me_vscroll = (app.me_vscroll - d / ROW_H).clamp(0.0, n.saturating_sub(fit) as f32); @@ -135,7 +151,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.me_vscroll = app.me_vscroll.min(n.saturating_sub(fit) as f32); let first = app.me_vscroll.floor() as usize; let mut last_group = ""; - for (r, p) in Property::ALL.into_iter().enumerate().skip(first).take(fit) { + for (r, p) in rows.iter().copied().enumerate().skip(first).take(fit) { let y = rows_top + (r - first) as f32 * ROW_H; let row = Rect::from_min_size(pos2(list.left(), y), vec2(LIST_W, ROW_H)); let selected = app.me_prop == p; @@ -404,7 +420,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { None => gr.on_hover_text_at_pointer(tr!("Drag a key up or down to change it, or a handle to shape the ease. Double-click to add a key.")), }; - footer(app, ui, body, track, sel_key, start); + footer(app, ui, body, track, sel_key, start, &rows); } /// Whether `q` is a pin between the ends (which can be let go). @@ -425,7 +441,7 @@ fn diamond(p: &egui::Painter, c: Pos2, r: f32, fill: Color32, stroke: Stroke) { } /// The ease of the selected segment, and the tween's own actions. -fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, sel_key: Option, start: u32) { +fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, sel_key: Option, start: u32, rows: &[Property]) { let bar = Rect::from_min_max(pos2(body.left(), body.bottom() - FOOTER_H), body.right_bottom()); ui.painter().rect_filled(bar, SQUARE, T.panel_alt); ui.painter().line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, T.border)); @@ -454,6 +470,21 @@ fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, s } } ui.separator(); + // Animate's "+" for colour effects: list another style's properties (keying one adds it). + let missing: Vec = [ColorStyle::Alpha, ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced].into_iter().filter(|s| !rows.iter().any(|p| p.style() == Some(*s))).collect(); + if !missing.is_empty() { + ui.menu_button(tr!("Add Colour Effect"), |ui| { + for st in missing { + if ui.button(crate::i18n::t(st.label())).clicked() { + app.me_styles.push(st); + app.me_prop = Property::ALL.into_iter().find(|p| p.style() == Some(st)).unwrap_or(Property::Alpha); + ui.close(); + } + } + }) + .response + .on_hover_text(tr!("List a colour effect style's properties here; keying one adds it to the tween")); + } if ui.button(tr!("Remove Tween")).on_hover_text(tr!("The object stays as it is on the span's first frame ({undo} to undo)", undo = app.undo_key())).clicked() { app.run("timeline.remove_tween", json!({})); } diff --git a/src/panels.rs b/src/panels.rs index e944c954..2ca9dd6d 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -3,7 +3,7 @@ use crate::app::{App, Tool}; use crate::icons::{self, Icon}; use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, section, text, to_color32, with_type}; -use anicraft_engine::doc::{ElementKind, LibraryItem, Paint, Rgba, SymbolKind, evaluate_layer_elements}; +use anicraft_engine::doc::{ColorEffect, ColorStyle, ElementKind, LibraryItem, Paint, Rgba, SymbolKind, evaluate_layer_elements}; use crate::a11y::{self, Named}; use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; use serde_json::{Value, json}; @@ -482,6 +482,81 @@ fn mixed(ui: &mut egui::Ui, differs: bool) { } } +/// The colour effect (ADR 0056): Animate's Style menu, then the chosen style's controls. Each +/// change sets that value on every selected element (ADR 0053), as one undo step per drag. +fn colour_effect_rows(app: &mut App, ui: &mut egui::Ui, fx: &ColorEffect, m: crate::mixed::ColorMixed) { + let current = fx.style(); + row_prose(ui, tr!("Colour effect"), |ui| { + egui::ComboBox::from_id_salt("prop_color_style").selected_text(crate::i18n::t(current.label())).show_ui(ui, |ui| { + for st in ColorStyle::ALL { + if ui.selectable_label(st == current, crate::i18n::t(st.label())).clicked() && (st != current || m.style) { + app.run("element.set_color_effect", json!({"style": st.key()})); + } + } + }) + .response + .set_name(tr!("Colour effect style")); + mixed(ui, m.style); + }); + let pct = a11y::SliderLook { suffix: " %", max_decimals: Some(0), ..Default::default() }; + let set = |app: &mut App, p: Value| live(app, tr_noop!("Colour Effect"), "element.set_color_effect", p); + match *fx { + ColorEffect::None => {} + ColorEffect::Alpha(a) => { + let mut v = a * 100.0; + row(ui, tr!("Alpha"), |ui| { + if a11y::slider(ui, &mut v, 0.0..=100.0, tr!("Alpha"), pct).changed() { + set(app, json!({"alpha": v})); + } + mixed(ui, m.alpha); + }); + } + ColorEffect::Brightness(b) => { + let mut v = b * 100.0; + row(ui, tr!("Brightness"), |ui| { + if a11y::slider(ui, &mut v, -100.0..=100.0, tr!("Brightness"), pct).changed() { + set(app, json!({"brightness": v})); + } + mixed(ui, m.brightness); + }); + } + ColorEffect::Tint { color, amount } => { + let mut c = rgb(color); + row(ui, tr!("Tint"), |ui| { + if ui.color_edit_button_srgb(&mut c).named(tr!("Tint colour")).changed() { + set(app, json!({"tint": hex(c)})); + } + ui.label(text(Type::Data, hex(c))); + mixed(ui, m.tint); + }); + let mut v = amount * 100.0; + row(ui, tr!("Tint amount"), |ui| { + if a11y::slider(ui, &mut v, 0.0..=100.0, tr!("Tint amount"), pct).changed() { + set(app, json!({"tint_amount": v})); + } + mixed(ui, m.tint_amount); + }); + } + ColorEffect::Advanced(t) => { + // Each channel: its multiplier in percent, then the offset added (−255..255). + let channels = [(tr!("Red"), tr!("Red multiplier"), tr!("Red offset"), "red"), (tr!("Green"), tr!("Green multiplier"), tr!("Green offset"), "green"), (tr!("Blue"), tr!("Blue multiplier"), tr!("Blue offset"), "blue"), (tr!("Alpha"), tr!("Alpha multiplier"), tr!("Alpha offset"), "alpha")]; + for (i, (label, mul_name, off_name, key)) in channels.into_iter().enumerate() { + let mut mv = t.mul.get(i).copied().unwrap_or(1.0) * 100.0; + let mut ov = t.add.get(i).copied().unwrap_or(0.0) * 255.0; + row(ui, label, |ui| { + if ui.add(egui::DragValue::new(&mut mv).suffix(" %").speed(0.5).range(-100.0..=100.0).max_decimals(0)).named(mul_name).changed() { + set(app, json!({format!("{key}_multiplier"): mv})); + } + if ui.add(egui::DragValue::new(&mut ov).prefix("+ ").speed(1.0).range(-255.0..=255.0).max_decimals(0)).named(off_name).changed() { + set(app, json!({format!("{key}_offset"): ov})); + } + mixed(ui, m.advanced.get(i).copied().unwrap_or(false) || m.advanced.get(i + 4).copied().unwrap_or(false)); + }); + } + } + } +} + /// The selection's properties: `e` is the first selected element, `all` the whole selection. fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Element, all: &[std::sync::Arc]) { let many = all.len() > 1; @@ -531,13 +606,9 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E } mixed(ui, m.rotation); }); - let mut alpha = e.color.alpha * 100.0; - row(ui, tr!("Alpha"), |ui| { - if a11y::slider(ui, &mut alpha, 0.0..=100.0, tr!("Alpha"), a11y::SliderLook { suffix: " %", max_decimals: Some(0), ..Default::default() }).changed() { - live(app, tr_noop!("Alpha"), "element.set_alpha", json!({"alpha": alpha / 100.0})); - } - mixed(ui, m.alpha); - }); + if !matches!(e.kind, ElementKind::Camera) { + colour_effect_rows(app, ui, &e.color, m.color); + } // Blending and filters, on movie clips and buttons as in Animate. if let ElementKind::Symbol { symbol, filters, .. } = &e.kind && app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic) From 9367b7431db1230cc5404b4f9ab69c22618a6544 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 04:52:11 -0700 Subject: [PATCH 018/192] fix(shell): name the 9-slice controls' id key plainly (M2) --- src/panels.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/panels.rs b/src/panels.rs index 44d6bbb3..82b3e487 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -277,11 +277,11 @@ pub(crate) fn live(app: &mut App, label: &str, id: &str, p: Value) { /// A symbol's 9-slice guides (ADR 0055): Animate's "Enable guides for 9-slice scaling" and, /// when on, where the four guides are (in the symbol's space; also dragged on the stage while -/// the symbol is open). `salt` keeps two copies of the controls apart (Library, Properties). -pub(crate) fn scale_grid_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::SymbolId, salt: &str) { +/// the symbol is open). `place` keeps two copies of the controls apart (Library, Properties). +pub(crate) fn scale_grid_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::SymbolId, place: &str) { let Some(grid) = app.s.doc.symbol(id).map(|s| s.scale_grid) else { return }; let mut on = grid.is_some(); - ui.push_id(salt, |ui| { + ui.push_id(place, |ui| { let tip = tr!("Scaled instances keep the corners outside the guides unscaled, stretch the edges one way and the centre both ways (for buttons and panels). Edit the symbol to drag the guides"); if crate::theme::checkbox(ui, &mut on, tr!("Enable guides for 9-slice scaling")).on_hover_text(tip).changed() { app.run("symbol.set_scale_grid", json!({"symbol": id.0, "on": on})); From 6c30eb519ccfabb629999a11e73e5ceda7bd6412 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 04:56:50 -0700 Subject: [PATCH 019/192] test(engine): colour effect commands, tweens, renders, SVG and Lottie; a screenshot state (M2) --- crates/doc/src/motion.rs | 10 +- crates/engine/src/cmds_motion.rs | 4 +- crates/engine/src/color_tests.rs | 245 +++++++++++++++++++++++++++++++ crates/engine/src/lib.rs | 2 + crates/render/src/lib.rs | 40 +++++ crates/render/src/lottie.rs | 23 ++- crates/render/src/svg.rs | 15 ++ src/app.rs | 14 ++ src/main.rs | 2 +- src/panels.rs | 2 +- 10 files changed, 349 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/color_tests.rs diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index 685d5ae6..75c6beab 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -1034,11 +1034,15 @@ impl MotionTween { el } - /// The colour effect styles the target shows over the span: those with keyed properties, - /// and its own style (unless None). + /// The colour effect styles the target shows over the span. As in Animate, a motion tween + /// has one colour effect: the style its colour properties are keyed in, replacing the + /// target's own (which shows while none are keyed). Keys in several styles (older files + /// keyed alpha and tint together) compose into Advanced. pub fn colour_styles(&self, own: &ColorEffect) -> Vec { let mut out: Vec = Vec::new(); - for s in self.tracks.iter().filter_map(|t| t.property.style()).chain((own.style() != ColorStyle::None).then_some(own.style())) { + let keyed = self.tracks.iter().filter_map(|t| t.property.style()); + let own = (own.style() != ColorStyle::None && !self.tracks.iter().any(|t| t.property.style().is_some())).then_some(own.style()); + for s in keyed.chain(own) { if !out.contains(&s) { out.push(s); } diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 35527e4a..6823578c 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -131,8 +131,8 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { }; base.color = match (base_color, e.offset == 0 && !tracks_color) { (true, true) => base.color, - // The base's style and the edit's, from the new values (ADR 0056). - (true, false) => new_base.color_effect(&[e.base.color.style(), base.color.style()]), + // The edit's style, from the new values (ADR 0056). + (true, false) => new_base.color_effect(&[base.color.style()]), (false, _) => e.base.color, }; if let Some(slot) = kf.elements.get_mut(idx) { diff --git a/crates/engine/src/color_tests.rs b/crates/engine/src/color_tests.rs new file mode 100644 index 00000000..d96daab6 --- /dev/null +++ b/crates/engine/src/color_tests.rs @@ -0,0 +1,245 @@ +//! Colour effects through the command registry (ADR 0056): every style, switching styles, +//! values on a mixed selection, classic and motion tweens, undo, the file round trip and the +//! renders they give. + +use super::*; +use anicraft_doc::{ColorEffect, ColorStyle, ColorTransform, Property, Rgba}; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A white 20 × 20 square at the origin, selected. +fn square() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "fill": "#336699", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + s +} + +fn effect(s: &Session) -> ColorEffect { + s.visible_elements().first().map(|e| e.color).unwrap_or_default() +} + +/// The square's colour at the stage centre of its frame (CPU oracle, 1:1), 0–255. +fn pixel(s: &Session, frame: u32) -> [u8; 4] { + let pm = anicraft_render::render_frame(&s.doc, frame, 1.0).unwrap(); + let px = pm.to_rgba8(); + let i = ((10 * pm.width + 10) * 4) as usize; + [px[i], px[i + 1], px[i + 2], px[i + 3]] +} + +fn near(a: [u8; 4], b: [u8; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 1) +} + +#[test] +fn every_style_is_set_and_reported() { + let mut s = square(); + let v = run(&mut s, "element.set_color_effect", json!({"brightness": -50})); + assert_eq!(v, json!({"style": "brightness", "brightness": -50.0})); + assert_eq!(effect(&s), ColorEffect::Brightness(-0.5)); + let v = run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 25})); + assert_eq!(v, json!({"style": "tint", "tint": "#ff0000", "tint_amount": 25.0})); + let v = run(&mut s, "element.set_color_effect", json!({"alpha": 40})); + assert_eq!(v, json!({"style": "alpha", "alpha": 40.0})); + run(&mut s, "element.set_color_effect", json!({"red_multiplier": -100, "red_offset": 255, "alpha_offset": -10.5})); + assert_eq!(effect(&s), ColorEffect::Advanced(ColorTransform { mul: [-1.0, 1.0, 1.0, 0.4], add: [1.0, 0.0, 0.0, -10.5 / 255.0] }), "Advanced starts from the alpha it had"); + let v = run(&mut s, "element.set_color_effect", json!({"style": "none"})); + assert_eq!(v, json!({"style": "none"})); + assert_eq!(effect(&s), ColorEffect::None); +} + +#[test] +fn a_new_style_keeps_the_look_it_can() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#00ff00", "tint_amount": 60})); + let before = pixel(&s, 0); + run(&mut s, "element.set_color_effect", json!({"style": "advanced"})); + assert_eq!(effect(&s).style(), ColorStyle::Advanced); + assert!(near(pixel(&s, 0), before), "Advanced is exactly the tint"); + run(&mut s, "element.set_color_effect", json!({"style": "brightness"})); + assert_eq!(effect(&s), ColorEffect::Brightness(0.0)); + run(&mut s, "element.set_color_effect", json!({"style": "tint"})); + assert_eq!(effect(&s), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 }); +} + +#[test] +fn bad_params_change_nothing() { + let mut s = square(); + let before = s.doc.clone(); + for p in [ + json!({}), + json!({"style": "sepia"}), + json!({"brightness": 101}), + json!({"tint_amount": -1}), + json!({"red_offset": 300}), + json!({"alpha": 50, "brightness": 10}), + json!({"style": "tint", "alpha": 50}), + json!({"tint": "red"}), + json!({"alpha": f64::NAN}), + ] { + assert!(s.execute("element.set_color_effect", &p).is_err(), "{p}"); + } + assert_eq!(s.doc, before); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("element.set_color_effect", &json!({"style": "alpha"})).is_err(), "nothing selected"); +} + +#[test] +fn renders_follow_the_arithmetic() { + // #336699 = (51, 102, 153). + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": 50})); + assert!(near(pixel(&s, 0), [153, 179, 204, 255]), "{:?}", pixel(&s, 0)); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + assert!(near(pixel(&s, 0), [153, 51, 77, 255]), "{:?}", pixel(&s, 0)); + run(&mut s, "element.set_color_effect", json!({"style": "advanced", "red_multiplier": -100, "red_offset": 255, "green_multiplier": 50, "blue_offset": -100})); + // The tint carried over into Advanced (×50 %, +127.5 red), then these channels changed. + let fx = effect(&s).transform(); + assert_eq!((fx.mul[0], fx.add[0], fx.mul[1], fx.add[2]), (-1.0, 1.0, 0.5, -100.0 / 255.0)); + assert!(near(pixel(&s, 0), [204, 51, 0, 255]), "{:?}", pixel(&s, 0)); +} + +#[test] +fn a_change_on_a_mixed_selection_sets_only_that_value() { + let mut s = Session::default(); + let a = run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + let b = run(&mut s, "draw.rect", json!({"x": 20, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "element.select", json!({"ids": [a]})); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + run(&mut s, "element.select", json!({"ids": [b]})); + run(&mut s, "element.set_color_effect", json!({"tint": "#0000ff", "tint_amount": 10})); + run(&mut s, "element.select", json!({"ids": [a, b]})); + run(&mut s, "element.set_color_effect", json!({"tint_amount": 80})); + let fx: Vec = s.visible_elements().iter().map(|e| e.color).collect(); + assert_eq!(fx, [ColorEffect::Tint { color: Rgba::hex(0xff0000), amount: 0.8 }, ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.8 }], "each keeps its colour"); + // One undo step puts both back. + s.undo().unwrap(); + assert_eq!(s.visible_elements()[1].color, ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.1 }); +} + +#[test] +fn set_alpha_keeps_the_rest_of_the_effect() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": 20})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + assert_eq!(effect(&s).transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::brightness(0.2))); + run(&mut s, "element.set_color_effect", json!({"style": "none"})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + assert_eq!(effect(&s), ColorEffect::Alpha(0.5)); +} + +#[test] +fn a_classic_tween_between_styles_travels_in_the_advanced_space() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 100})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.set_color_effect", json!({"alpha": 50})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + s.set_frame(5); + let mid = effect(&s); + assert_eq!(mid.style(), ColorStyle::Advanced); + let want = ColorTransform::tint(Rgba::hex(0xff0000), 1.0).lerp(&ColorTransform::alpha(0.5), 0.5); + let got = mid.transform(); + assert!(got.mul.iter().zip(want.mul).chain(got.add.iter().zip(want.add)).all(|(a, b)| (a - b).abs() < 1e-5), "{got:?} vs {want:?}"); + // Within one style the value itself travels: brightness −100 % to +100 % is 0 halfway. + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": -100})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.set_color_effect", json!({"brightness": 100})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Brightness(0.0)); + assert!(near(pixel(&s, 5), [51, 102, 153, 255])); +} + +#[test] +fn motion_tweens_key_brightness_tint_and_advanced() { + let mut s = square(); + run(&mut s, "timeline.create_motion_tween", json!({})); + run(&mut s, "motion.set_key", json!({"property": "brightness", "frame": 10, "value": 60})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Brightness(0.3)); + // A second style composes with the first into Advanced, exactly. + run(&mut s, "motion.set_key", json!({"property": "tint", "frame": 10, "value": 50})); + run(&mut s, "motion.set_key", json!({"property": "tint_red", "frame": 0, "value": 255})); + run(&mut s, "motion.set_key", json!({"property": "tint_green", "frame": 0, "value": 0})); + run(&mut s, "motion.set_key", json!({"property": "tint_blue", "frame": 0, "value": 0})); + s.set_frame(10); + let want = ColorTransform::brightness(0.6).concat(&ColorTransform::tint(Rgba::hex(0xff0000), 0.5)); + assert_eq!(effect(&s).transform(), want); + // Advanced channels on their own curves. + let mut s = square(); + run(&mut s, "timeline.create_motion_tween", json!({})); + run(&mut s, "motion.set_key", json!({"property": "red_offset", "frame": 10, "value": 255})); + run(&mut s, "motion.set_key", json!({"property": "alpha_multiplier", "frame": 10, "value": 0})); + s.set_frame(5); + let fx = effect(&s); + assert_eq!(fx.style(), ColorStyle::Advanced); + assert_eq!(fx.transform(), ColorTransform { mul: [1.0, 1.0, 1.0, 0.5], add: [0.5, 0.0, 0.0, 0.0] }); + assert!(s.execute("motion.set_key", &json!({"property": "red_offset", "frame": 3, "value": 256})).is_err()); + // Info lists the keys by their names. + let info = run(&mut s, "motion.info", json!({})); + assert!(info.to_string().contains("red_offset"), "{info}"); +} + +#[test] +fn a_motion_tween_has_one_colour_effect_style() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#00ff00", "tint_amount": 40})); + run(&mut s, "timeline.create_motion_tween", json!({})); + // Untracked, the target's own tint shows all along. + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Tint { color: Rgba::hex(0x00ff00), amount: 0.4 }); + // Keying alpha makes it an alpha tween, as in Animate. + run(&mut s, "motion.set_key", json!({"property": "alpha", "frame": 10, "value": 0})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Alpha(0.5)); + // Changing the alpha in Properties inside the span keys it there. + s.set_frame(4); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.set_color_effect", json!({"alpha": 90})); + s.set_frame(4); + assert!((effect(&s).alpha() - 0.9).abs() < 1e-4, "{:?}", effect(&s)); + assert!(layer_motion_has(&s, Property::Alpha) && !layer_motion_has(&s, Property::Tint)); + // Keying tint as well composes the two (older files keyed both); the tint colour is the + // target's own. + run(&mut s, "motion.set_key", json!({"property": "tint", "frame": 10, "value": 50})); + s.set_frame(10); + assert_eq!(effect(&s).transform(), ColorTransform::alpha(0.0).concat(&ColorTransform::tint(Rgba::hex(0x00ff00), 0.5)), "the tint keys start from the target's own colour"); +} + +fn layer_motion_has(s: &Session, p: Property) -> bool { + s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.as_ref()).is_some_and(|m| m.track(p).is_some()) +} + +#[test] +fn files_keep_every_style() { + let mut s = Session::default(); + for (i, p) in [json!({"brightness": -30}), json!({"tint": "#123456", "tint_amount": 0}), json!({"style": "advanced", "blue_multiplier": -40, "green_offset": 12}), json!({"alpha": 100})].into_iter().enumerate() { + let id = run(&mut s, "draw.rect", json!({"x": i * 20, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "element.select", json!({"ids": [id]})); + run(&mut s, "element.set_color_effect", p); + } + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + let styles: Vec = back.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| e.color.style()).collect(); + assert_eq!(styles, [ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha]); +} + +#[test] +fn plug_ins_may_set_colour_effects() { + assert!(crate::cmds_plugin::plugin_may_call("element.set_color_effect").is_ok()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4c3e4947..aa78afa4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -945,6 +945,8 @@ mod tests; #[cfg(test)] mod motion_tests; #[cfg(test)] +mod color_tests; +#[cfg(test)] mod motion_path_tests; #[cfg(test)] mod motion_pin_tests; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 467fe9bc..24ecf00b 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -963,6 +963,46 @@ mod tests { assert!((alpha_sum(&pm2) - (800.0 + area / 2.0)).abs() < 8.0, "{}", alpha_sum(&pm2)); } + #[test] + fn colour_transforms_apply_to_solids_gradients_and_bitmaps_alike() { + // ADR 0056: each straight channel c·mul + add, clamped, on every kind of paint. + let fx = ColorTransform { mul: [-1.0, 0.5, 1.0, 0.8], add: [1.0, 0.25, -0.5, 0.0] }; + let want = |c: Rgba| { + let o = fx.apply(c); + [o.r * o.a, o.g * o.a, o.b * o.a, o.a] + }; + let near = |p: [f32; 4], q: [f32; 4]| p.iter().zip(q).all(|(a, b)| (a - b).abs() < 2e-3); + let c = Rgba::new(0.2, 0.6, 0.9, 1.0); + // Solid. + let mut solid = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(c)); + solid.color = fx; + let (pm, _) = render(&list(vec![solid]), &view(4, 4)).unwrap(); + assert!(near(pm.pixel(2, 2).unwrap(), want(c)), "{:?} vs {:?}", pm.pixel(2, 2), want(c)); + // A two-stop gradient of one colour is that colour, through the transform. + let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: c }, anicraft_doc::GradientStop { offset: 1.0, color: c }]; + let mut grad = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(4.0, 0.0), stops }); + grad.color = fx; + let (pm, _) = render(&list(vec![grad]), &view(4, 4)).unwrap(); + assert!(near(pm.pixel(1, 2).unwrap(), want(c))); + // A bitmap of one colour, sampled anywhere. + let px = Arc::new(anicraft_doc::Pixels { width: 2, height: 2, rgba: [51u8, 153, 230, 255].repeat(4) }); + let b = Rgba::new(51.0 / 255.0, 153.0 / 255.0, 230.0 / 255.0, 1.0); + let mut bmp = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY }); + bmp.image = Some(px); + bmp.color = fx; + let (pm, _) = render(&list(vec![bmp]), &view(4, 4)).unwrap(); + assert!(near(pm.pixel(1, 1).unwrap(), want(b)), "{:?} vs {:?}", pm.pixel(1, 1), want(b)); + // Nested transforms compose exactly: drawing through the composition is drawing through + // one then the other. + let inner = ColorTransform::tint(Rgba::new(1.0, 0.0, 0.0, 1.0), 0.5); + let outer = ColorTransform::brightness(-0.4); + let mut nested = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(c)); + nested.color = outer.concat(&inner); + let (pm, _) = render(&list(vec![nested]), &view(4, 4)).unwrap(); + let o = outer.apply(inner.apply(c)); + assert!(near(pm.pixel(2, 2).unwrap(), [o.r, o.g, o.b, 1.0])); + } + #[test] fn groups_fade_as_one() { // A red square under a blue one, overlapping, in a group at 50% over white. diff --git a/crates/render/src/lottie.rs b/crates/render/src/lottie.rs index 654d4716..ce0d2af9 100644 --- a/crates/render/src/lottie.rs +++ b/crates/render/src/lottie.rs @@ -4,7 +4,8 @@ //! Frame-accurate rather than re-keyed: each frame is evaluated, and every piece of artwork //! that persists from frame to frame (same layer, element and path structure) becomes one //! shape layer, its outline baked into stage space. Whatever changes (outline, colours, -//! gradient points, stroke width, opacity, masks) is written as hold keyframes at the frames +//! gradient points, stroke width, opacity, masks; colour effects of every style are baked into +//! the colours, ADR 0056) is written as hold keyframes at the frames //! where it changes, so any Lottie player shows exactly AniCraft's frames. Strokes keep their //! caps, joins, miter limit and dashes (dash lengths scaled like the width, dots as zero-length //! round dashes; ADR 0046); variable-width strokes are filled outlines (the polygons the @@ -674,6 +675,26 @@ mod tests { assert!(part["layers"].as_array().unwrap().iter().all(|l| l["ty"] == 4), "transparent: no stage layer"); } + #[test] + fn every_colour_effect_style_is_baked_into_the_colours() { + // ADR 0056: Lottie has no colour transform, so the effect is in each fill colour (and + // tweening effects become colour keyframes); nothing is reported lost. + use anicraft_doc::{ColorEffect, ColorTransform, Document, Element, ElementId, ElementKind, Shape}; + let mut doc = Document::default(); + let fx = ColorEffect::Advanced(ColorTransform { mul: [-1.0, 0.5, 1.0, 1.0], add: [1.0, 0.0, 0.0, 0.0] }); + let shape = Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::new(0.2, 0.4, 0.6, 1.0))); + let el = Element { id: ElementId(77), name: String::new(), transform: Affine::IDENTITY, color: fx, kind: ElementKind::Shape(shape) }; + let layer = std::sync::Arc::make_mut(&mut doc.timeline_mut(0).layers[0]); + layer.keyframe_mut(0).unwrap().elements.push(std::sync::Arc::new(el)); + let e = to_lottie(&doc, "fx", 0, 0, false); + let v = parse(&e); + let it = v["layers"][0]["shapes"][0]["it"].as_array().unwrap(); + let fill = it.iter().find(|i| i["ty"] == "fl").expect("a fill"); + let c: Vec = fill["c"]["k"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect(); + assert!((c[0] - 0.8).abs() < 1e-3 && (c[1] - 0.2).abs() < 1e-3 && (c[2] - 0.6).abs() < 1e-3, "{c:?}"); + assert!(e.report.is_empty(), "nothing lost: {:?}", e.report); + } + #[test] fn variable_width_strokes_export_as_filled_outlines() { use anicraft_doc::{Document, Element, ElementId, ElementKind, ProfilePreset, Shape, Stroke}; diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index e5fa7e4e..44b1c7bc 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -470,6 +470,21 @@ mod tests { Stage { width: 100, height: 50, fps: 24.0, background: Rgba::WHITE } } + #[test] + fn bitmaps_take_colour_effects_as_a_colour_matrix() { + // ADR 0056: alpha alone is fill-opacity; anything more is an feColorMatrix on the image. + let px = Arc::new(anicraft_doc::Pixels { width: 1, height: 1, rgba: vec![10, 20, 30, 255] }); + let mut b = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY })); + b.image = Some(px); + b.color = ColorTransform::alpha(0.5); + let svg = to_svg(&DisplayList { items: vec![b.clone()], ..Default::default() }, &stage()); + assert!(svg.contains("fill-opacity=\"0.5\"") && !svg.contains("feColorMatrix"), "{svg}"); + b.color = ColorTransform { mul: [-1.0, 0.5, 1.0, 0.8], add: [1.0, 0.25, 0.0, 0.1] }; + let svg = to_svg(&DisplayList { items: vec![b], ..Default::default() }, &stage()); + assert!(svg.contains(""), "{svg}"); + assert!(svg.contains("filter=\"url(#cm") && !svg.contains("fill-opacity"), "{svg}"); + } + #[test] fn shapes_strokes_and_effects_come_out_in_stage_space() { let mut a = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::Solid(Rgba::hex(0xff0000)))); diff --git a/src/app.rs b/src/app.rs index f67c11fe..b07fc979 100644 --- a/src/app.rs +++ b/src/app.rs @@ -825,6 +825,20 @@ impl App { self.run("element.select", json!({"ids": [a, b]})); } } + Some("colour") => { + // A row of instances in each colour effect style (ADR 0056), the Advanced one + // selected: Properties shows the Style menu and its channel rows. + if let Some(ball) = self.s.doc.library.first().map(|s| s.id.0) { + self.run("edit.deselect", json!({})); + let id = |v: Option| v.and_then(|v| v["element"].as_u64()).unwrap_or(0); + let styles = [json!({"brightness": 45}), json!({"tint": "#2a9d8f", "tint_amount": 70}), json!({"alpha": 40}), json!({"style": "advanced", "red_multiplier": -100, "red_offset": 255, "green_multiplier": 60, "blue_offset": -40})]; + for (i, fx) in styles.into_iter().enumerate() { + let e = id(self.run("library.place", json!({"symbol": ball, "x": 640 + 130 * i, "y": 470}))); + self.run("element.select", json!({"ids": [e]})); + self.run("element.set_color_effect", fx); + } + } + } Some("bitmap") => { // Two placed bitmaps of different images, selected: the Bitmap row with Swap… // says "mixed" (ADR 0053). diff --git a/src/main.rs b/src/main.rs index 3f5dde9d..ee5e68f5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -179,7 +179,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu|colour]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/panels.rs b/src/panels.rs index 2ca9dd6d..449d02e6 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -547,7 +547,7 @@ fn colour_effect_rows(app: &mut App, ui: &mut egui::Ui, fx: &ColorEffect, m: cra if ui.add(egui::DragValue::new(&mut mv).suffix(" %").speed(0.5).range(-100.0..=100.0).max_decimals(0)).named(mul_name).changed() { set(app, json!({format!("{key}_multiplier"): mv})); } - if ui.add(egui::DragValue::new(&mut ov).prefix("+ ").speed(1.0).range(-255.0..=255.0).max_decimals(0)).named(off_name).changed() { + if ui.add(egui::DragValue::new(&mut ov).custom_formatter(|v, _| format!("{v:+.0}")).speed(1.0).range(-255.0..=255.0).max_decimals(0)).named(off_name).changed() { set(app, json!({format!("{key}_offset"): ov})); } mixed(ui, m.advanced.get(i).copied().unwrap_or(false) || m.advanced.get(i + 4).copied().unwrap_or(false)); From 7fea98c8fdd02e59ba04546a61a2d8d75b923c76 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 04:58:34 -0700 Subject: [PATCH 020/192] docs: ADR 0056 colour effects, ADR 0016 note, roadmap, changelog, attribution (M2) --- ATTRIBUTION.md | 1 + CHANGELOG.md | 21 ++++++ docs/adr/0016-motion-tweens.md | 5 +- docs/adr/0056-colour-effects.md | 115 ++++++++++++++++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 4 +- 6 files changed, 142 insertions(+), 5 deletions(-) create mode 100644 docs/adr/0056-colour-effects.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7cc10202..e084dc54 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -87,6 +87,7 @@ OR Apache-2.0) is noted in the table. | Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. | | Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs`, `crates/gpu/src/fine.wgsl` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. | | Adjust Color filter (brightness, contrast, saturation and hue as colour matrices) | `crates/render/src/filters.rs` | Paul Haeberli, *Matrix Operations for Image Processing* (Silicon Graphics, 1993) | Public description; standard matrix operations. | +| Colour effects (per-channel multiply and offset; brightness and tint as such transforms) | `crates/doc/src/color_effect.rs`, `crates/gpu/src/fine.wgsl`, `crates/render/src/svg.rs` | Adobe, *ActionScript 3.0 Reference: flash.geom.ColorTransform* (public documentation); W3C *Filter Effects Module Level 1*, `feColorMatrix` | Behaviour learned from the public descriptions; no code or assets used (ADR 0056). | | Blur, drop shadow and glow by repeated box blurs | `crates/render/src/filters.rs` | Standard image processing (repeated box filters approach a Gaussian, central limit theorem) | Public; no specific implementation followed. | | Bevel and Gradient Bevel by offset differences of the blurred opacity; Gradient Glow and Gradient Bevel through a colour ramp | `crates/render/src/filters.rs` | Standard image processing: embossing as the difference of an image offset along the light direction (a directional derivative; e.g. R. C. Gonzalez & R. E. Woods, *Digital Image Processing*); parameters and behaviour from Adobe's public Animate user guide and ActionScript 3.0 reference (`BevelFilter`, `GradientGlowFilter`, `GradientBevelFilter`) | Public descriptions only; no Adobe code or assets (ADR 0025). | | Bevel and gradient filters in SVG export (`feComposite` arithmetic, `feComponentTransfer` tables) | `crates/render/src/svg.rs` | W3C Filter Effects Module Level 1 / SVG 1.1 filters | W3C Royalty-Free Patent Policy. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f4393c8..8a406492 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ ## Unreleased +* **Colour effects, complete** (ADR 0056, M2). + * **Properties › Colour effect**: Animate's Style menu (None, Brightness, Tint, Advanced, + Alpha) with each style's controls: brightness −100..100 %, tint colour and amount, + Advanced's multiplier and offset for red, green, blue and alpha. Every row says "mixed" + when the selection differs, and a change sets only that value on all of them. Switching + style keeps the look where it can (Advanced starts as exactly the effect before). + * One exact colour transform behind every style: nested effects compose exactly (a + brightness around a tint shows both), and the CPU renderer, the GPU stage (bitmaps + included, pixel-identical), SVG (`feColorMatrix` on bitmaps), HTML canvas (bitmaps + recoloured, no longer reported) and Lottie (baked into the colours) draw the same. + * Classic tweens interpolate within a style (a brightness tween passes through 0) and across + styles in the Advanced space, as Animate does. + * Motion tweens key **Brightness**, **Tint** colour (red, green, blue) beside its amount, and + the eight **Advanced** values; the Motion Editor lists the styles in use and adds others + with **Add Colour Effect**. A tween has one colour effect style, as in Animate. + * XFL/FLA import brings every `Color` style across (Advanced no longer keeps only its + alpha); a new `colour` corpus package with goldens. + * `element.set_color_effect` for the CLI, MCP and plug-ins; `element.set_alpha` now keeps + the rest of the effect. Older files open unchanged, and None, Alpha and Tint effects are + still written exactly as before. + * **Library and Properties polish** (ADR 0053, M2). * **Drag Library items onto the stage**: symbols and bitmaps land at the pointer on the active layer at the playhead, a sound goes onto that layer's keyframe; drag several at once. diff --git a/docs/adr/0016-motion-tweens.md b/docs/adr/0016-motion-tweens.md index 0beb8ce5..087b8d86 100644 --- a/docs/adr/0016-motion-tweens.md +++ b/docs/adr/0016-motion-tweens.md @@ -77,8 +77,9 @@ Headless: `timeline.create_motion_tween`, `timeline.remove_tween`, `motion.set_k * Resizing a span does not rescale its property keys yet: keys past a shortened end are kept but not reached, and a lengthened span holds its last values. * Motion paths drawn and edited on the stage, with orient to path, came in ADR 0030. +* Tint colour (red, green, blue), brightness and the eight Advanced properties came in ADR + 0056, with one colour effect style per tween as in Animate (keys in several styles compose). * Not yet (later PRs): dragging keys in time in the Motion Editor, ease presets with - strengths and saved custom eases, separate tint colour and brightness/advanced colour - properties, 3D rotation and position, Split Motion and joining tweens as commands, Lottie + strengths and saved custom eases, 3D rotation and position, Split Motion and joining tweens as commands, Lottie export of property curves as eased keyframes (it exports frame-accurate hold keys today), and importing motion tweens from XFL (`motionObjectXML`; still reported, kept as keyframes). diff --git a/docs/adr/0056-colour-effects.md b/docs/adr/0056-colour-effects.md new file mode 100644 index 00000000..e82e0af3 --- /dev/null +++ b/docs/adr/0056-colour-effects.md @@ -0,0 +1,115 @@ +# ADR 0056: Colour effects: one colour transform for every style + +* Status: accepted (2026-11-11) +* Relates to: ADR 0016 (motion tweens), ADR 0019 and 0032 (GPU stage), ADR 0027 (camera tint), + ADR 0035 (XFL corpus), ADR 0053 (mixed Properties rows), roadmap M2 + +## Context + +An instance's colour effect was `{alpha, tint, tint_amount}`. Brightness came in as a tint towards +white or black (ADR 0035), Animate's Advanced style kept only its alpha (reported), there was no +command or Properties control for anything but alpha, nested tints composed by keeping the stronger +one, and the motion tween slice (ADR 0016) had alpha and tint amount tracks only, the tint colour +left out. + +Animate's Properties offers five styles: None, Brightness, Tint, Advanced (a multiplier in percent +and an offset in −255..255 for each of red, green, blue and alpha) and Alpha. Its public +documentation (ActionScript 3 `ColorTransform`, the XFL `Color` element's attributes) describes all +of them as one operation on each straight colour channel: `c ↦ c·multiplier + offset`, clamped. + +## Decision + +1. **Two types, authored and drawn** (`crates/doc/src/color_effect.rs`). + * `ColorEffect` is what an element stores: an enum of the five styles with that style's values + (`Brightness(b)`, `Tint { color, amount }`, `Advanced(ColorTransform)`, `Alpha(a)`, `None`). + Properties shows the style the artist chose, and a tint keeps its colour at 0 %. + * `ColorTransform { mul: [f32; 4], add: [f32; 4] }` is what everything draws with. Each style is + a transform: brightness `b` is a tint towards white (`b > 0`) or black by `|b|`; a tint of `t` + by `k` multiplies colour channels by `1 − k` and adds `k·t`; alpha multiplies alpha. + * `DisplayItem::color` is a `ColorTransform`. Nested instances, the camera's tint and onion skin + compose by `concat`, the exact composition of the two maps (no clamp between). The old "the + stronger tint wins" rule is gone: a brightness around a tint now shows both, as in Animate. + +2. **One arithmetic in every renderer.** The CPU oracle applies `clamp(c·mul + add)` to straight + colour before premultiplying (solids, gradient ramps and each bitmap sample). The GPU stage + carries a bitmap's transform as two entries of its ramp table (no new buffer, the record layout + unchanged) and applies the same expression in `fine.wgsl`; solids and gradients arrive already + transformed. Parity on the bitmap colour cases, Advanced with a negative multiplier and an + alpha offset included, is exact (0 of 3072 pixels differ). NaN multipliers or offsets draw a + channel of 0, as a NaN colour always did. + +3. **Groups.** An instance whose transform only multiplies alpha still fades as one group at that + alpha. An alpha *offset* changes each item's alpha on its own, so it + stays in the items' transform and the group (for a blend or filters) is opaque. + +4. **Files.** `ColorEffect` writes the fields older files have (`alpha`, `tint`, `tint_amount`, + the look as near as they can say it), so None, Alpha and Tint are written byte for byte as + before, and older builds open Brightness as the tint it looks like and Advanced as its alpha. + `style` (with `brightness`, or `multiply` and `offset` as fractions, offset 1 = 255) is added + only when those fields alone would read back as something else. A file without `style` reads as + it always looked: a tint, an alpha, both together (Advanced: alpha after tint), or none. Values + are clamped into Animate's ranges on read. + +5. **Commands.** `element.set_color_effect {style?, alpha?, brightness?, tint?, tint_amount?, + red_multiplier? … alpha_offset?}` on every selected element (per layer, one undo step). The + style defaults to the one the given values belong to, else each element's own, so a change on + a mixed selection sets only that value (ADR 0053). A new style starts from the look it can keep: + Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at + 0 % (switching never jumps, except to None). `element.set_alpha` (plug-ins, ActionScript's + `alpha`, tier 2 unchanged) sets the alpha multiplier and keeps the rest: None becomes Alpha; + Brightness and Tint become Advanced below 1. Element listings report `color_effect`. + +6. **Classic tweens.** Within one style its values travel (a tint's colour and amount, the + brightness itself: −100 % to +100 % is 0 halfway); None meets any style as that style's rest + value; any other change of style travels in the Advanced space (multipliers and offsets + interpolated), as Animate does. + +7. **Motion tweens.** New properties: `brightness`, `tint_red`/`tint_green`/`tint_blue` (0–255, + beside the existing `tint` amount), and the eight Advanced ones (`red_multiplier` … + `alpha_offset`). As in Animate a motion tween has one colour effect: the style its colour + properties are keyed in replaces the target's own (which shows while none are keyed). Keys in + several styles (older files keyed alpha and tint together, and the Motion Editor allows it) + compose into Advanced, alpha outermost, then brightness, tint, Advanced. A style's properties + start from the target's own values (a tinted target's tint keys start from its colour). The + Motion Editor lists the styles in use (Alpha when none) and adds others with **Add Colour + Effect**. + +8. **Exports and import.** + * SVG: colours and stops carry the effect (as before, now every style); a bitmap fill with more + than alpha draws its image through an `feColorMatrix` (`sRGB`, the same matrix). + * HTML canvas: the exported effect is the 8-number transform; the player composes it exactly + (`player.js` mirrors `concat`) and a bitmap with more than alpha is drawn from a recoloured + copy of its pixels (cached per bitmap and effect), so the old "tints on bitmaps" report entry + is gone. JS parity with `evaluate_player` is tested under boa, Brightness, Tint and Advanced + with an alpha offset included. + * Lottie has no colour transform: every style is baked into the colours (tweens become colour + keyframes), which maps fully; bitmap fills stay unexported as before. + * XFL: a `Color` with `tintMultiplier`/`tintColor` is Tint, with `brightness` Brightness, with + any other multiplier or an offset (−255..255) Advanced, with `alphaMultiplier` alone Alpha. The + "advanced colour effects (only alpha kept)" report entry is gone. A new `colour` corpus package + (every style, a brightness around a tint, a tint-to-Advanced and a brightness tween) has goldens + and hand-worked probes; the `symbols` and `tweens` goldens were regenerated (the Advanced + instance now draws its channels; None-to-Tint now keeps the tint's colour all the way). + +9. **Properties.** A **Colour effect** row with the Style menu (None, Brightness, Tint, Advanced, + Alpha), then the style's controls: an Alpha slider; a Brightness slider (−100..100 %); Tint's + colour swatch and amount; Advanced's four channel rows, multiplier (%) and signed offset. Every + row is mixed-aware (each value compared as the first element's style sees them). The camera + keeps its own tint row. + +## Consequences + +* One representation reaches every output; adding a sixth style (none planned) is a new + `ColorEffect` arm and a transform. +* Composition of nested effects changes for nested *tints*: older documents with a tint inside a + tint now show both, exactly, instead of the stronger one. This is Animate's behaviour. +* An older motion tween with both alpha and tint tracks looks as it did; a tint track on an + element whose tint colour was stored at 0 % (possible only through XFL import) now starts from + white. +* `Props` holds 20 values; `Property::ALL` grew from 8 to 20. + +## Not in this slice + +* Colour effects on the camera beyond its tint (ADR 0027). +* A per-channel colour picker for the Motion Editor's tint colour (three 0–255 tracks for now). +* Lottie bitmaps (not exported at all yet). diff --git a/docs/adr/README.md b/docs/adr/README.md index 2dba5749..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0056 | m2/colour-effects | Colour effects: one colour transform for every style | diff --git a/docs/roadmap.md b/docs/roadmap.md index 9e5bdb81..dbb51ba6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,7 +16,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). Not yet: ActionScript variables, conditions, reading properties, `removeEventListener`, enter-frame and keyboard events, functions from other frames, event bubbling, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | @@ -33,7 +33,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---|---| | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | -| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | +| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: camera colour effects beyond tint, a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | From 1897f901d2cb0c817d61a278d4f32ff88f6aebef Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:40:07 +0100 Subject: [PATCH 021/192] fix(gpu): wrap repeating bitmaps without a signed remainder, undefined on GL (M3) The fine shader wrapped a repeating bitmap's taps with ((q % size) + size) % size. naga (30.0.1) writes WGSL's integer % as GLSL's, which is undefined for negative operands, and the bilinear tap left of or above the edge is -1. On the GL backend (llvmpipe in the FreeBSD VM, which has no Vulkan driver) the edge texels came out wrong: bitmap repeated max 79, filtered bitmap max 16, so FreeBSD x86_64 has failed since bitmap fills landed (0dae205). Vulkan, DX12 and Metal define the remainder, so Linux CI passed. wrap() takes the unsigned remainder of |i| instead, defined on every backend. shaders_take_no_signed_remainder parses every shader with naga and fails on a % whose left operand is a signed integer; it fails on fine.wgsl before this. --- CHANGELOG.md | 4 ++++ Cargo.lock | 1 + Cargo.toml | 2 ++ crates/gpu/Cargo.toml | 4 ++++ crates/gpu/src/fine.wgsl | 11 ++++++++++- crates/gpu/src/tests.rs | 33 +++++++++++++++++++++++++++++++++ 6 files changed, 54 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f4393c8..064c6305 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +* **Repeating bitmap fills on the GL backend** (M3): the GPU stage wrapped a repeating + bitmap with a signed remainder, which GLSL leaves undefined for negative values, so on + OpenGL (llvmpipe in the FreeBSD VM) the texels at the bitmap's left and top edges came out + wrong. It now wraps without one, and a test keeps every shader free of signed remainders. * **Library and Properties polish** (ADR 0053, M2). * **Drag Library items onto the stage**: symbols and bitmaps land at the pointer on the active layer at the playhead, a sound goes onto that layer's keyframe; drag several at once. diff --git a/Cargo.lock b/Cargo.lock index 83ed3ad2..c6dc21ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -312,6 +312,7 @@ dependencies = [ "bytemuck", "pollster 1.0.1", "rayon", + "naga", "thiserror 2.0.21", "web-time", "wgpu", diff --git a/Cargo.toml b/Cargo.toml index 15bb9237..778449e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,8 @@ anicraft-gpu = { path = "crates/gpu" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" +# The WGSL front end wgpu already builds, for checking the shaders in tests. +naga = { version = "30", features = ["wgsl-in"] } pollster = "1" bytemuck = "1" anicraft-actions = { path = "crates/actions" } diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 9a0a5325..925b51b6 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -21,5 +21,9 @@ rayon.workspace = true web-time.workspace = true thiserror.workspace = true +[dev-dependencies] +# The shaders' types, to keep them free of what a backend leaves undefined (wgpu's own naga). +naga.workspace = true + [lints] workspace = true diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 374e5b20..b49a7473 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -156,12 +156,21 @@ fn finite(v: f32) -> bool { return (bitcast(v) & 0x7f800000u) != 0x7f800000u; } +// Rust's `rem_euclid` for i32 and `n` >= 1, without `%` on a negative operand: naga writes +// WGSL's `%` as GLSL's, which leaves negative operands undefined, so on the GL backend +// (llvmpipe in the FreeBSD VM) the texel left of or above a repeating bitmap's edge, -1, came +// out wrong. The unsigned remainder is defined everywhere. +fn wrap(i: i32, n: i32) -> i32 { + let r = i32(u32(abs(i)) % u32(n)); + return select(r, select(n - r, 0, r == 0), i < 0); +} + // One bitmap tap at integer (x, y) (wrapped when repeating, then clamped to the edges as // `Pixels::at` does), through the colour effect, premultiplied. fn tap(slot: u32, x: i32, y: i32, size: vec2, repeat: bool, fx: vec4, tint: vec4) -> vec4 { var q = vec2(x, y); if repeat { - q = ((q % size) + size) % size; + q = vec2(wrap(q.x, size.x), wrap(q.y, size.y)); } q = clamp(q, vec2(0), size - vec2(1)); let c = texel(slot, q); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 214cd49c..bcae9ad4 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -623,6 +623,39 @@ fn degenerate_geometry_bins_without_trouble() { // ----- the real GPU ---------------------------------------------------------------------------- +/// The shaders, as `pipelines` and the stage build them. +const SHADERS: [(&str, &str); 4] = [ + ("fine.wgsl", include_str!("fine.wgsl")), + ("bin.wgsl", include_str!("bin.wgsl")), + ("scan.wgsl", include_str!("scan.wgsl")), + ("filters.wgsl", include_str!("filters.wgsl")), +]; + +#[test] +fn shaders_take_no_signed_remainder() { + // naga writes WGSL's `%` on integers as GLSL's, which is undefined when an operand is + // negative: on the GL backend (llvmpipe in the FreeBSD VM) a repeating bitmap's wrap, + // `((q % size) + size) % size` at q = -1, picked the wrong texel at its edges (bitmap + // repeated: max 79). Unsigned remainders and float ones (written as `a - b * trunc(a / b)`) + // are defined on every backend. + for (name, src) in SHADERS { + let module = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(src))); + let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()) + .validate(&module) + .unwrap_or_else(|e| panic!("{name}: {e:?}")); + let functions = module.functions.iter().map(|(h, f)| (f, &info[h])); + let entries = module.entry_points.iter().enumerate().map(|(i, e)| (&e.function, info.get_entry_point(i))); + for (f, fi) in functions.chain(entries) { + for (h, e) in f.expressions.iter() { + if let naga::Expression::Binary { op: naga::BinaryOperator::Modulo, left, .. } = *e { + let kind = fi[left].ty.inner_with(&module.types).scalar_kind(); + assert_ne!(kind, Some(naga::ScalarKind::Sint), "{name}: `%` on a signed integer in {:?} ({h:?})", f.name); + } + } + } + } +} + /// One device for all tests: the graphics card, or else the software adapter (CI runners have /// lavapipe or WARP); `None` (with the reasons printed) when there is neither. /// `ANICRAFT_TEST_GPU=software` tests on the software adapter even where there is a card. From bf1df47bda6aeee4e3a73b908a5e8e13516de5e6 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:55:48 +0100 Subject: [PATCH 022/192] fix(gpu): sort naga into anicraft-gpu's Cargo.lock dependencies (M3) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index c6dc21ad..40e86ecb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -310,9 +310,9 @@ dependencies = [ "anicraft-geom", "anicraft-render", "bytemuck", + "naga", "pollster 1.0.1", "rayon", - "naga", "thiserror 2.0.21", "web-time", "wgpu", From 6dbf120661c741e915a960a97c6c0084363b4c02 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:35:45 +0100 Subject: [PATCH 023/192] Release: AniCraft v0.2.0 (#157) --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 40e86ecb..dd0754e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -207,7 +207,7 @@ dependencies = [ [[package]] name = "anicraft" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-audio", "anicraft-doc", @@ -233,7 +233,7 @@ dependencies = [ [[package]] name = "anicraft-actions" -version = "0.1.0" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -241,7 +241,7 @@ dependencies = [ [[package]] name = "anicraft-audio" -version = "0.1.0" +version = "0.2.0" dependencies = [ "lewton", "nanomp3", @@ -249,7 +249,7 @@ dependencies = [ [[package]] name = "anicraft-cli" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-doc", "anicraft-engine", @@ -260,7 +260,7 @@ dependencies = [ [[package]] name = "anicraft-doc" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-actions", "anicraft-audio", @@ -273,7 +273,7 @@ dependencies = [ [[package]] name = "anicraft-engine" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -296,7 +296,7 @@ dependencies = [ [[package]] name = "anicraft-geom" -version = "0.1.0" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -304,7 +304,7 @@ dependencies = [ [[package]] name = "anicraft-gpu" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -320,7 +320,7 @@ dependencies = [ [[package]] name = "anicraft-plugins" -version = "0.1.0" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -331,7 +331,7 @@ dependencies = [ [[package]] name = "anicraft-render" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -344,7 +344,7 @@ dependencies = [ [[package]] name = "anicraft-svg" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -355,7 +355,7 @@ dependencies = [ [[package]] name = "anicraft-text" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-geom", "fontdb", @@ -365,7 +365,7 @@ dependencies = [ [[package]] name = "anicraft-xfl" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -378,7 +378,7 @@ dependencies = [ [[package]] name = "anicraft-xml" -version = "0.1.0" +version = "0.2.0" dependencies = [ "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 778449e1..562023b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ default-members = [".", "crates/*"] [workspace.package] # 0.1.0 is the early alpha (release stage in src/app.rs, RELEASE_STAGE); see CHANGELOG.md # and docs/release.md. -version = "0.1.0" +version = "0.2.0" edition = "2024" license = "MIT OR Apache-2.0" # An application, not a library: not published to crates.io. From d78d8e9727dff78e41f7ce819c073d4b95613705 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 12:08:43 -0500 Subject: [PATCH 024/192] ci: run Harden-Runner on every job (#162) Adds step-security/harden-runner (audit, pinned to v2.22.4 like craft-common-actions) as the first step of each job that did not have it, so every workflow in the org's public repos reports its egress to StepSecurity. Audit, not block: block-mode allow lists come from each job's observed traffic. --- .github/workflows/packaging-lint.yml | 4 ++++ .github/workflows/web.yml | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 32b4a1ea..691cee24 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -27,6 +27,10 @@ jobs: name: Windows installation policy (no app build) runs-on: windows-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml index 4c02bdcd..132201c4 100644 --- a/.github/workflows/web.yml +++ b/.github/workflows/web.yml @@ -26,6 +26,10 @@ jobs: env: CARGO_TERM_COLOR: always steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false From 072fa2e641f6348360ea1b21950f94a60e8aff47 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 13:51:38 -0700 Subject: [PATCH 025/192] docs(adr): reserve ADR 0057 for button sounds and hit areas (M5) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..32101b85 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0057 | (M5 track, button sounds) | Sounds on button frames and hit-area editing | From 0936d34eafd7b8c0a6b5c8fbdf67e236dd230a2f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 13:56:46 -0700 Subject: [PATCH 026/192] docs(adr): reserve ADR 0058 for Find and Replace and the Movie Explorer (M8) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..ed3d9110 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0058 | M8 track: find and replace, Movie Explorer | Find and Replace, Movie Explorer | From f4bc3eee6c1bbba1ccb1a0ff6bb0284caf9a1047 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 13:58:09 -0700 Subject: [PATCH 027/192] feat(player): sounds on button frames play as the button changes state (M5) --- crates/doc/src/player.rs | 165 +++++++++++++++++++++++++++++++-- crates/doc/src/player_tests.rs | 90 ++++++++++++++++++ 2 files changed, 245 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index b156b70a..9d5c2bd5 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -20,7 +20,7 @@ use crate::actions::as3::{Compiled, Decls, Problem}; 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 crate::{BlendMode, ColorEffect, DisplayList, Document, Element, ElementId, ElementKind, Group, LayerKind, MAX_SYMBOL_DEPTH, Rgba, SoundSync, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Vec2}; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; @@ -214,21 +214,63 @@ impl PlayerState { /// The frame a button shows: Up (0), Over (1) under the pointer, Down (2) while pressed on /// it; a button whose timeline is shorter shows its last frame. pub fn button_frame(&self, path: &[ElementId], len: u32) -> u32 { - let over = self.hover.as_deref() == Some(path); - let f = match (over, self.down && self.pressed.as_deref() == Some(path)) { - (true, true) => 2, - (true, false) => 1, - (false, _) => 0, + let f = match self.button_state(path) { + ButtonState::Down => 2, + ButtonState::Over => 1, + ButtonState::Up | ButtonState::OutDown => 0, }; f.min(len.max(1) - 1) } + /// Where the pointer leaves a button: [`ButtonState`]. + pub fn button_state(&self, path: &[ElementId]) -> ButtonState { + ButtonState::of(self.hover.as_deref(), self.pressed.as_deref(), self.down, path) + } + /// A timeline's playhead: the main timeline's for the empty path. pub fn playhead(&self, path: &[ElementId]) -> Option { if path.is_empty() { Some(self.root) } else { self.clips.get(path).copied() } } } +/// Where the pointer is for one button, as the SWF file format names a button's states: away +/// (Up), over it (Over), pressed on it (Down), or pressed on it and dragged off (shown Up). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ButtonState { + Up, + Over, + Down, + OutDown, +} + +impl ButtonState { + /// The state of the button at `path` with the pointer over `hover`, pressed on `pressed`, + /// and down or not. + pub fn of(hover: Option<&[ElementId]>, pressed: Option<&[ElementId]>, down: bool, path: &[ElementId]) -> ButtonState { + match (hover == Some(path), down && pressed == Some(path)) { + (true, true) => ButtonState::Down, + (true, false) => ButtonState::Over, + (false, true) => ButtonState::OutDown, + (false, false) => ButtonState::Up, + } + } +} + +/// The frame of a button whose sound plays when the button goes from state `from` to `to` +/// (ADR 0057), as the SWF format's button sounds are kept: the Over frame's going over it, the +/// Up frame's leaving it, the Down frame's pressing it, and the Hit frame's letting go over it. +/// Dragging off a pressed button and back plays nothing. +pub fn button_sound_frame(from: ButtonState, to: ButtonState) -> Option { + use ButtonState::*; + match (from, to) { + (Up, Over) => Some(1), + (Over, Up) => Some(0), + (Over, Down) => Some(2), + (Down, Over) => Some(3), + _ => None, + } +} + /// A pointer event, in stage coordinates. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Event { @@ -393,6 +435,62 @@ pub fn hit(doc: &Document, st: &PlayerState, p: Vec2) -> Option { hit_in(doc, st, &tree(doc, st), p) } +/// The frame of a button's timeline, `len` frames long, that answers the pointer: the Hit +/// frame (the fourth) when it has one, otherwise the Up frame. +pub fn hit_frame(len: u32) -> u32 { + if len > 3 { 3 } else { 0 } +} + +/// The area of a button with timeline `tl` that answers the pointer, placed by `xf`: its +/// [`hit_frame`]'s artwork without guides and mask artwork (masks don't cut hit areas, and +/// shapes count however faint they are drawn). The hit test and Test Movie's hit-area overlay +/// both use it. +pub fn hit_area(doc: &Document, tl: &Timeline, xf: Affine) -> DisplayList { + let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None); + dl.items.retain(|i| !i.guide && i.masks.is_none()); + for i in &mut dl.items { + i.clip = None; + } + for g in &mut dl.groups { + g.clip = None; + } + dl +} + +/// `dl` drawn as one translucent area: every item filled and stroked in `tint` at full +/// strength, composited together and laid over what is below at `alpha`, so overlapping shapes +/// don't darken each other. +pub fn tinted(dl: DisplayList, tint: Rgba, alpha: f32) -> DisplayList { + let mut out = DisplayList::default(); + let alpha = if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 }; + out.groups.push(Group { parent: None, alpha, blend: BlendMode::default(), filters: Arc::from(Vec::new()), clip: None }); + out.append(dl); + for g in out.groups.iter_mut().skip(1) { + g.alpha = 1.0; + g.blend = BlendMode::default(); + g.filters = Arc::from(Vec::new()); + g.parent = Some(g.parent.unwrap_or(0)); + } + for it in &mut out.items { + it.color = ColorEffect { alpha: 1.0, tint, tint_amount: 1.0 }; + it.outline = None; + it.group = Some(it.group.unwrap_or(0)); + } + out +} + +/// Every button's hit area at `st`, each a translucent area in `tint` (Test Movie's Show Hit +/// Areas): where the pointer finds the buttons, drawn over the movie. +pub fn hit_overlay(doc: &Document, st: &PlayerState, tint: Rgba, alpha: f32) -> DisplayList { + let mut out = DisplayList::default(); + for n in tree(doc, st).iter().filter(|n| n.kind == NodeKind::Button && n.hittable) { + if let Some(sym) = n.symbol.and_then(|s| doc.symbol(s)) { + out.append(tinted(hit_area(doc, &sym.timeline, n.xf), tint, alpha)); + } + } + out +} + /// Whether timeline layer `index` takes part in playback: shown, not a folder or guide, not in /// a hidden folder (what is drawn is what plays). fn plays(tl: &Timeline, index: usize) -> bool { @@ -452,9 +550,7 @@ fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2) -> Option 3 { 3 } else { 0 }; - evaluate_symbol(doc, &sym.timeline, f, n.xf, None) + hit_area(doc, &sym.timeline, n.xf) } else { evaluate_symbol(doc, &sym.timeline, n.frame, n.xf, Some(&Play { state: st, path: n.path.clone() })) }; @@ -519,12 +615,55 @@ impl<'a, 'h> Run<'a, 'h> { /// The sounds on keyframes of `tl` starting at `frame` (every layer but guides, as the /// soundtrack has them), at volume `gain` times their layer's. fn sounds_at(&mut self, tl: &Timeline, frame: u32, gain: f32) { + self.sounds_on(tl, frame, gain, false); + } + + /// [`Run::sounds_at`]; on a button's frame (`button`) a stream sound plays as an event, + /// since a button's frame has no span to stream over (ADR 0057). + fn sounds_on(&mut self, tl: &Timeline, frame: u32, gain: f32, button: bool) { for layer in tl.layers.iter().filter(|l| !matches!(l.kind, LayerKind::Guide | LayerKind::Folder | LayerKind::Camera)) { let Some(k) = layer.keyframe_starting_at(frame).and_then(|i| layer.keyframes.get(i)) else { continue }; if let Some(fs) = &k.sound && self.sounds.len() < MAX_SOUNDS_PER_STEP { - self.sounds.push(Started { sound: fs.clone(), gain: gain * layer.sound_gain(), span: k.duration }); + let mut sound = fs.clone(); + if button && sound.sync == SoundSync::Stream { + sound.sync = SoundSync::Event; + } + self.sounds.push(Started { sound, gain: gain * layer.sound_gain(), span: k.duration }); + } + } + } + + /// Where the pointer is, for [`Run::button_sounds`]: what it is over, what it went down + /// on, and whether it is down. + fn pointer_now(&self) -> (Option, Option, bool) { + (self.st.hover.clone(), self.st.pressed.clone(), self.st.down) + } + + /// Starts the sounds of the buttons whose state changed since `before` ([`pointer_now`] + /// then): the frame [`button_sound_frame`] gives for each change. + /// + /// [`pointer_now`]: Run::pointer_now + fn button_sounds(&mut self, before: (Option, Option, bool)) { + if before == self.pointer_now() { + return; + } + self.refresh(); + let (h, p, d) = &before; + let mut paths: Vec = Vec::new(); + for path in [h, p, &self.st.hover, &self.st.pressed].into_iter().flatten() { + if !paths.contains(path) { + paths.push(path.clone()); + } + } + for path in paths { + let from = ButtonState::of(h.as_deref(), p.as_deref(), *d, &path); + let Some(frame) = button_sound_frame(from, self.st.button_state(&path)) else { continue }; + let Some(n) = self.index_of(&path).and_then(|i| self.nodes.get(i)).filter(|n| n.kind == NodeKind::Button) else { continue }; + let (gain, symbol) = (n.gain, n.symbol); + if let Some(sym) = symbol.and_then(|s| self.doc.symbol(s)) { + self.sounds_on(&sym.timeline, frame, gain, true); } } } @@ -1112,18 +1251,22 @@ impl<'a, 'h> Run<'a, 'h> { Event::Move(p) => self.pointer(Some(p)), Event::Down(p) => { self.pointer(Some(p)); + let before = self.pointer_now(); self.st.down = true; self.st.pressed = self.st.hover.clone(); self.dirty = true; + self.button_sounds(before); if let Some(h) = self.st.hover.clone() { self.fire(&h, ButtonEvent::Press); } } Event::Up(p) => { self.pointer(Some(p)); + let before = self.pointer_now(); self.st.down = false; let pressed = self.st.pressed.take(); self.dirty = true; + self.button_sounds(before); if let Some(h) = self.st.hover.clone() { self.fire(&h, ButtonEvent::Release); if pressed.as_ref() == Some(&h) { @@ -1146,8 +1289,10 @@ impl<'a, 'h> Run<'a, 'h> { } let now = p.and_then(|p| hit_in(self.doc, &self.st, &self.nodes, p)); if now != self.st.hover { + let before = self.pointer_now(); let old = std::mem::replace(&mut self.st.hover, now.clone()); self.dirty = true; + self.button_sounds(before); if let Some(o) = old { self.fire(&o, ButtonEvent::Out); } diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 51d57e58..23767cdc 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -342,6 +342,96 @@ fn entered_keyframes_start_their_sounds_in_clips_and_graphics_with_layer_volumes assert_eq!(started(&start(&m, &mut NoScripts)), vec![(1, 1.0), (3, 0.0)]); } +// ----- Sounds on button frames (ADR 0057) -------------------------------------------------------- + +/// [`button_doc`] with a sound on each state frame (ids 10 Up, 11 Over, 12 Down, 13 Hit; Over's +/// a stream), on a layer at half volume, the button on a layer at half volume too. +fn sounding_button() -> Document { + use crate::SoundSync::{Event, Stream}; + let mut d = button_doc(); + let art = |id| vec![rect(id, 0.0, 0.0, 10.0, 10.0)]; + let mut sounds = (*layer(34, vec![with_sound(kf(0, 1, vec![], vec![], ""), 10, Event), with_sound(kf(1, 1, vec![], vec![], ""), 11, Stream), with_sound(kf(2, 1, vec![], vec![], ""), 12, Event), with_sound(kf(3, 1, vec![], vec![], ""), 13, Event)])).clone(); + sounds.volume = 0.5; + let states = layer(31, vec![kf(0, 1, art(32), vec![], ""), kf(1, 1, art(32), vec![], ""), kf(2, 1, art(32), vec![], ""), kf(3, 1, vec![rect(33, 0.0, 0.0, 100.0, 100.0)], vec![], "")]); + d.library = vec![symbol(300, SymbolKind::Button, vec![Arc::new(sounds), states])]; + Arc::make_mut(&mut d.timeline_mut(0).layers[1]).volume = 0.5; + let tone: Vec = (0..800).map(|i| (i as f32 * 0.1).sin() * 0.5).collect(); + for id in 10..14 { + let data = anicraft_audio::wav::encode(8000, 1, &tone, anicraft_audio::wav::Bits::Float32); + d.sounds.push(Arc::new(crate::Sound::from_data(crate::SoundId(id), format!("s{id}.wav"), data).expect("a WAV"))); + } + d +} + +#[test] +fn a_button_plays_the_sound_of_the_state_it_enters() { + let d = sounding_button(); + let at = |x, y| Vec2::new(x, y); + let s = start(&d, &mut NoScripts); + assert!(s.sounds.is_empty(), "a button on the stage is silent until the pointer comes"); + // Over: the Over frame's sound, as an event (a button frame has no span to stream over), at + // the volumes of both layers. + let s = step(&d, &s.state, &[Event::Move(at(150.0, 150.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(11, 0.25)]); + assert_eq!(s.sounds[0].sound.sync, crate::SoundSync::Event); + // Moving about inside it plays nothing more. + let s = step(&d, &s.state, &[Event::Move(at(160.0, 150.0))], &mut NoScripts); + assert!(s.sounds.is_empty()); + // Pressed: Down's. Released over it: Hit's (the SWF format's Down → Over sound). + let s = input(&d, &s.state, &[Event::Down(at(160.0, 150.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(12, 0.25)]); + let s = input(&d, &s.state, &[Event::Up(at(160.0, 150.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(13, 0.25)]); + // Left: Up's. + let s = step(&d, &s.state, &[Event::Leave], &mut NoScripts); + assert_eq!(started(&s), vec![(10, 0.25)]); + // Arriving and pressing in one event: Over's, then Down's. + let s = input(&d, &s.state, &[Event::Down(at(150.0, 150.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(11, 0.25), (12, 0.25)]); + // Dragged off while pressed, back on and released off: nothing (no state with a sound). + let s = input(&d, &s.state, &[Event::Move(at(400.0, 400.0)), Event::Move(at(150.0, 150.0)), Event::Move(at(400.0, 400.0)), Event::Up(at(400.0, 400.0))], &mut NoScripts); + assert!(s.sounds.is_empty(), "{:?}", started(&s)); +} + +#[test] +fn button_sounds_follow_the_frames_a_button_has_and_stay_out_of_the_soundtrack() { + // A two-frame button (Up and Over): pressing it shows Over still, and plays nothing. + let mut d = sounding_button(); + let short = Timeline { layers: d.library[0].timeline.layers.iter().map(|l| { + let mut l = (**l).clone(); + l.keyframes.truncate(2); + Arc::new(l) + }).collect() }; + Arc::make_mut(&mut d.library[0]).timeline = short; + let s = start(&d, &mut NoScripts); + // Its Up frame is its hit area (10 × 10 at 100, 100). + let s = input(&d, &s.state, &[Event::Move(Vec2::new(105.0, 105.0)), Event::Down(Vec2::new(105.0, 105.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(11, 0.25)]); + // The mix and every export leave buttons out: they only sound under the pointer. + assert!(crate::sound::voices(&sounding_button(), 48_000).is_empty()); +} + +#[test] +fn the_hit_overlay_is_the_area_the_pointer_finds() { + let d = button_doc(); + let s = start(&d, &mut NoScripts); + let tint = Rgba::new(1.0, 0.0, 0.0, 1.0); + let dl = hit_overlay(&d, &s.state, tint, 0.4); + // One area: the Hit frame's 100 × 100 square at (100, 100), tinted, in one group at 40 %. + assert_eq!(dl.items.len(), 1); + assert_eq!(dl.groups.first().map(|g| g.alpha), Some(0.4)); + let i = &dl.items[0]; + assert_eq!((i.color.tint, i.color.tint_amount, i.group), (tint, 1.0, Some(0))); + for p in [Vec2::new(101.0, 101.0), Vec2::new(199.0, 150.0), Vec2::new(50.0, 50.0), Vec2::new(201.0, 150.0)] { + assert_eq!(i.path.contains(p, &i.transform, i.fill_rule), hit(&d, &s.state, p).is_some(), "{p:?}"); + } + // A hidden button has no area; a movie without buttons none at all. + assert!(hit_overlay(&doc(vec![], vec![]), &PlayerState::default(), tint, 0.4).items.is_empty()); + assert_eq!(hit_frame(4), 3); + assert_eq!(hit_frame(3), 0); + assert_eq!(hit_frame(0), 0); +} + // ----- ActionScript (ADR 0013 tier 2) ----------------------------------------------------------- /// `k` with a kept ActionScript 3.0 script in place of its actions. From 54c27ef0d4ac16e48290c24980eb2ae034dc3b33 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:00:10 -0700 Subject: [PATCH 028/192] fix(symbol): 9-slice guides switched off are kept and come back when switched on (M5) --- crates/doc/src/armature_tests.rs | 2 +- crates/doc/src/camera_tests.rs | 2 +- crates/doc/src/eval_tests.rs | 6 ++-- crates/doc/src/lib.rs | 8 +++++ crates/doc/src/library.rs | 2 +- crates/doc/src/library_tests.rs | 2 +- crates/doc/src/nine_slice_tests.rs | 4 +-- crates/doc/src/player_tests.rs | 2 +- crates/doc/src/sample.rs | 8 ++--- crates/doc/src/sound.rs | 2 +- crates/doc/src/sound_tests.rs | 2 +- crates/engine/src/cmds_draw.rs | 15 ++++++--- crates/engine/src/editing.rs | 2 +- crates/engine/src/scale_grid_tests.rs | 44 ++++++++++++++++++++++++--- crates/engine/src/tests_bone.rs | 2 +- crates/engine/src/tests_sound.rs | 2 +- crates/gpu/src/tests.rs | 2 +- crates/render/src/html_tests.rs | 8 ++--- crates/render/src/nine_slice_tests.rs | 2 +- crates/xfl/src/import.rs | 2 +- 20 files changed, 83 insertions(+), 36 deletions(-) diff --git a/crates/doc/src/armature_tests.rs b/crates/doc/src/armature_tests.rs index b385f977..2e4c6f4d 100644 --- a/crates/doc/src/armature_tests.rs +++ b/crates/doc/src/armature_tests.rs @@ -173,7 +173,7 @@ fn every_export_sees_the_pose() { let mut k = Keyframe::new(0, 1); k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) })); seg.keyframes = vec![Arc::new(k)]; - d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(seg)] } })); + d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(seg)] } })); d.timeline_mut(0).layers = vec![Arc::new(armature_layer(Easing::Linear))]; d.sanitize(); let dl = evaluate(&d, 10); diff --git a/crates/doc/src/camera_tests.rs b/crates/doc/src/camera_tests.rs index 75889596..1a56af56 100644 --- a/crates/doc/src/camera_tests.rs +++ b/crates/doc/src/camera_tests.rs @@ -141,7 +141,7 @@ fn the_camera_stays_on_top_alone_and_old_files_read_without_one() { // A symbol's camera layer is a normal layer. let mut sl = Layer::new(LayerId(80), "in symbol"); sl.kind = LayerKind::Camera; - d.library.push(Arc::new(Symbol { id: SymbolId(81), name: "S".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(sl)] } })); + d.library.push(Arc::new(Symbol { id: SymbolId(81), name: "S".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(sl)] } })); d.sanitize(); assert_eq!(d.library[0].timeline.layers[0].kind, LayerKind::Normal); // Depth round-trips, is left out when 0, and an old file reads at 0; hostile depths clamp. diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index 8f080194..1c42c7da 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -85,7 +85,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { }, ); tl.layers.push(Arc::new(layer)); - d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: tl })); + d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: tl })); push( layer0(&mut d), 0, @@ -140,7 +140,7 @@ fn masks_inside_symbols_nest_in_the_instance_clip() { // The main timeline's masked layer holds an instance of a symbol that has its own mask. let mut d = mask_doc(); let sid = SymbolId(99); - d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: mask_doc().timeline(0).clone() })); + d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: mask_doc().timeline(0).clone() })); let inst = Element { id: ElementId(60), name: String::new(), @@ -295,7 +295,7 @@ fn movie_clips_play_their_own_timeline_graphics_keep_step_buttons_hold_up() { }) .collect(); let mut d = Document::default(); - d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(st)] } })); + d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(st)] } })); // The same instance on two keyframes back to back (frames 0–4 and 5–11), moved on the second. let inst = |x: f32| Element { id: ElementId(60), diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 58573767..4e4a8f94 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1025,6 +1025,10 @@ pub struct Symbol { /// unscaled. `None`: the symbol scales as a whole. #[serde(default, skip_serializing_if = "Option::is_none")] pub scale_grid: Option, + /// The guides as they were when 9-slice scaling was switched off (ADR 0057): switching it on + /// again brings them back where they were. Only kept, never drawn or applied. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_grid_kept: Option, pub timeline: Timeline, } @@ -1317,6 +1321,10 @@ impl Document { if sym.scale_grid.as_ref().is_some_and(|g| g.check().is_err()) { Arc::make_mut(sym).scale_grid = None; } + // Kept guides (ADR 0057) only while 9-slice is off, and only usable ones. + if sym.scale_grid_kept.as_ref().is_some_and(|g| sym.scale_grid.is_some() || g.check().is_err()) { + Arc::make_mut(sym).scale_grid_kept = None; + } let tl = &mut Arc::make_mut(sym).timeline; for l in &mut tl.layers { Arc::make_mut(l).normalize(); diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index 9a3c6763..b0a47fa9 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -388,7 +388,7 @@ impl Document { let src = self.library.get(at)?.clone(); let new_id = SymbolId(self.alloc_id()); let timeline = fresh_ids(&src.timeline, &mut || self.alloc_id()); - let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, scale_grid: src.scale_grid, timeline }; + let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, scale_grid_kept: src.scale_grid_kept, scale_grid: src.scale_grid, timeline }; self.library.insert(at + 1, Arc::new(copy)); if let Some(f) = self.library_tree.placed.get(&LibraryItem::Symbol(id)).copied() { Arc::make_mut(&mut self.library_tree).placed.insert(LibraryItem::Symbol(new_id), f); diff --git a/crates/doc/src/library_tests.rs b/crates/doc/src/library_tests.rs index 5fefbbd1..d737b7ab 100644 --- a/crates/doc/src/library_tests.rs +++ b/crates/doc/src/library_tests.rs @@ -19,7 +19,7 @@ fn add_symbol(d: &mut Document, name: &str, inside: &[SymbolId]) -> SymbolId { if let Some(k) = layer.keyframe_mut(0) { k.elements = els; } - d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); + d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); id } diff --git a/crates/doc/src/nine_slice_tests.rs b/crates/doc/src/nine_slice_tests.rs index 83484f19..79029bc3 100644 --- a/crates/doc/src/nine_slice_tests.rs +++ b/crates/doc/src/nine_slice_tests.rs @@ -25,7 +25,7 @@ fn doc(xf: Affine, grid: Option, extra: Vec) -> Document { k.elements.extend(extra.into_iter().map(Arc::new)); let mut layer = Layer::new(LayerId(901), "art"); layer.keyframes = vec![Arc::new(k)]; - d.library.push(Arc::new(Symbol { id: SYM, name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(layer)] } })); + d.library.push(Arc::new(Symbol { id: SYM, name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(layer)] } })); let mut k = Keyframe::new(0, 1); k.elements.push(Arc::new(instance(SYM, xf))); Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k)]; @@ -147,7 +147,7 @@ fn unscaled_instances_and_nested_symbols_draw_as_they_are() { k.elements.push(Arc::new(el(3, Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::WHITE)))))); let mut l = Layer::new(LayerId(951), "dot"); l.keyframes = vec![Arc::new(k)]; - d.library.push(Arc::new(Symbol { id: SymbolId(950), name: "Dot".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(l)] } })); + d.library.push(Arc::new(Symbol { id: SymbolId(950), name: "Dot".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(l)] } })); let dl = evaluate(&d, 0); let dot = dl.items.iter().find(|i| i.path.bounds().width() == 4.0).unwrap(); assert_eq!(dot.transform, Affine::scale(3.0, 3.0).mul(&Affine::translate(50.0, 20.0))); diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 23767cdc..3da52f74 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -33,7 +33,7 @@ fn layer(id: u64, keys: Vec>) -> Arc { } fn symbol(id: u64, kind: SymbolKind, layers: Vec>) -> Arc { - Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid: None, timeline: Timeline { layers } }) + Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers } }) } fn doc(root: Vec>, library: Vec>) -> Document { diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 039d057e..afae67fd 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -53,7 +53,7 @@ pub fn demo() -> Document { .with_stroke(Rgba::hex(0x5a1410), 3.0); let ball_el = el(&mut d, "ball body", Affine::IDENTITY, ElementKind::Shape(ball_shape)); let ball_layer = layer(d.alloc_id(), "body", 0x4fa3ff, vec![key(0, 1, vec![ball_el], None)]); - d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![ball_layer] } })); + d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![ball_layer] } })); let star_id = SymbolId(d.alloc_id()); let star_shape = Shape::filled(Path::star(0.0, 0.0, 60.0, 26.0, 5), Paint::Solid(Rgba::hex(0xfff6a8))).with_stroke(Rgba::hex(0xe0a400), 2.5); @@ -67,7 +67,7 @@ pub fn demo() -> Document { }) .collect(); let star_layer = layer(d.alloc_id(), "spin", 0x4fa3ff, star_keys); - d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![star_layer] } })); + d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![star_layer] } })); // --- main timeline (index 0 = top) --------------------------------------------------- const LEN: u32 = 48; @@ -161,7 +161,7 @@ pub fn interactive() -> Document { let (up, over, down) = (face(&mut d, 0x3d8bfd), face(&mut d, 0x6aa8ff), face(&mut d, 0x2a64c0)); let hit_area = el(&mut d, "hit", Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(-120.0, -50.0, 240.0, 100.0), solid(0x000000)))); let states = layer(d.alloc_id(), "states", 0x4fa3ff, vec![key(0, 1, up, None), key(1, 1, over, None), key(2, 1, down, None), key(3, 1, vec![hit_area], None)]); - d.library.push(Arc::new(Symbol { id: button_id, name: "Play Button".into(), kind: SymbolKind::Button, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![states] } })); + d.library.push(Arc::new(Symbol { id: button_id, name: "Play Button".into(), kind: SymbolKind::Button, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![states] } })); // A movie clip that spins on its own timeline. let spinner_id = SymbolId(d.alloc_id()); @@ -175,7 +175,7 @@ pub fn interactive() -> Document { }) .collect(); let spin = layer(d.alloc_id(), "spin", 0xffd54a, spin_keys); - d.library.push(Arc::new(Symbol { id: spinner_id, name: "Spinner".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![spin] } })); + d.library.push(Arc::new(Symbol { id: spinner_id, name: "Spinner".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![spin] } })); // Main timeline: actions on top, then the button (menu frame), the show, the backdrop. let mut menu = key(0, 1, Vec::new(), None); diff --git a/crates/doc/src/sound.rs b/crates/doc/src/sound.rs index da00a9c4..5ccd71b2 100644 --- a/crates/doc/src/sound.rs +++ b/crates/doc/src/sound.rs @@ -565,7 +565,7 @@ impl<'a> Layout<'a> { let enters = pa == s0 || (pa == st.l0 && st.enters); self.looped(tl, g, (pa - s0) % len, n, len, enters, gain, depth); } - // Buttons wait for the pointer: their sounds are not in this slice (ADR 0039). + // Buttons sound only under the pointer, in the interactive player (ADR 0057). (SymbolKind::Button, _) => {} } } diff --git a/crates/doc/src/sound_tests.rs b/crates/doc/src/sound_tests.rs index ea4a2efb..0d3e2cb5 100644 --- a/crates/doc/src/sound_tests.rs +++ b/crates/doc/src/sound_tests.rs @@ -194,7 +194,7 @@ fn nested(kind: SymbolKind, len: u32, inner: &[(u32, u32, Option)], // Pad the symbol's timeline to `len` frames with a second, silent layer. let mut pad = Layer::new(LayerId(11), "pad"); pad.keyframes = vec![Arc::new(Keyframe::new(0, len))]; - d.library.push(Arc::new(Symbol { linkage: None, scale_grid: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } })); + d.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } })); let mut l = Layer::new(LayerId(1), "outer"); l.keyframes = instances .iter() diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index d6ef936a..75a6cae7 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "9-Slice Scaling", "", None, - "{symbol?: id (default: the symbol open for editing, else the selected instance's), on?: bool, left?, right?, top?, bottom? (guide positions in the symbol's space)} turns a symbol's guides for 9-slice scaling on or off, or moves them (ADR 0055). Turning them on puts them a quarter of the way in from each edge of the symbol's artwork; moving one turns them on. Scaled instances then keep the corners outside the guides unscaled, stretch the edges one way and the centre both ways → {symbol, scale_grid: {left, right, top, bottom} | null}", + "{symbol?: id (default: the symbol open for editing, else the selected instance's), on?: bool, left?, right?, top?, bottom? (guide positions in the symbol's space)} turns a symbol's guides for 9-slice scaling on or off, or moves them (ADR 0055). Turning them on brings back the guides it had when they were turned off (ADR 0057), else puts them a quarter of the way in from each edge of the symbol's artwork; moving one turns them on. Scaled instances then keep the corners outside the guides unscaled, stretch the edges one way and the centre both ways → {symbol, scale_grid: {left, right, top, bottom} | null}", true, set_scale_grid, ), @@ -602,7 +602,8 @@ fn set_scale_grid(s: &mut Session, p: &Value) -> Result { } None } else { - let start = sym.scale_grid.unwrap_or_else(|| { + // Switched on again, the guides come back where they were (ADR 0057). + let start = sym.scale_grid.or(sym.scale_grid_kept).unwrap_or_else(|| { let b = anicraft_doc::symbol_box(&s.doc, sym); ScaleGrid::inset(&if b.is_empty() { anicraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0) } else { b }) }); @@ -611,10 +612,14 @@ fn set_scale_grid(s: &mut Session, p: &Value) -> Result { g.check().map_err(EngineError::Param)?; Some(g) }; + // Off, the guides are kept (only hidden), so switching back on finds them. + let kept = if grid.is_none() { sym.scale_grid.or(sym.scale_grid_kept) } else { None }; if let Some(sym) = s.doc.library.iter_mut().find(|x| x.id == id) - && sym.scale_grid != grid + && (sym.scale_grid != grid || sym.scale_grid_kept != kept) { - Arc::make_mut(sym).scale_grid = grid; + let sym = Arc::make_mut(sym); + sym.scale_grid = grid; + sym.scale_grid_kept = kept; } Ok(json!({"symbol": id.0, "scale_grid": grid.map(|g| json!({"left": g.left, "right": g.right, "top": g.top, "bottom": g.bottom}))})) } @@ -767,7 +772,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { } inner.push(Arc::new(layer)); } - s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, scale_grid: None, timeline: Timeline { layers: inner } })); + s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: inner } })); if folder.is_some() { s.doc.place_entry(LibraryEntry::Item(LibraryItem::Symbol(sym_id)), folder); } diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index a5078824..f1b61b02 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -215,7 +215,7 @@ impl Session { /// at opacity `alpha` (a symbol added to `doc`, which is only drawn). fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, alpha: f32) -> Arc { let symbol = SymbolId(doc.alloc_id()); - doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline })); + doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline })); let mut k = Keyframe::new(0, 1); k.elements.push(Arc::new(Element { id: ElementId(doc.alloc_id()), diff --git a/crates/engine/src/scale_grid_tests.rs b/crates/engine/src/scale_grid_tests.rs index 14a25453..74b1ca2e 100644 --- a/crates/engine/src/scale_grid_tests.rs +++ b/crates/engine/src/scale_grid_tests.rs @@ -38,13 +38,45 @@ fn turning_guides_on_puts_them_a_quarter_in_and_moving_one_keeps_the_rest() { run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); run(&mut s, "symbol.set_scale_grid", json!({"top": -12})); assert_eq!(grid(&s, id), Some(ScaleGrid { left: -40.0, right: 40.0, top: -12.0, bottom: 10.0 })); - // Off forgets them (as in Animate, turning them on again starts from the artwork). + // Off hides them: the symbol scales as a whole (ADR 0057). let v = run(&mut s, "symbol.set_scale_grid", json!({"on": false})); assert_eq!(v["scale_grid"], Value::Null); assert_eq!(grid(&s, id), None); - // Moving a guide turns them on. + // Moving a guide turns them on, from where they were. run(&mut s, "symbol.set_scale_grid", json!({"symbol": id.0, "left": -45})); - assert_eq!(grid(&s, id).map(|g| g.left), Some(-45.0)); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -45.0, right: 40.0, top: -12.0, bottom: 10.0 })); +} + +#[test] +fn guides_switched_off_and_on_again_come_back_where_they_were() { + let (mut s, id) = panel(); + let moved = ScaleGrid { left: -40.0, right: 30.0, top: -12.0, bottom: 6.0 }; + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 30, "top": -12, "bottom": 6})); + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let kept = |s: &Session| s.doc.symbol(id).and_then(|x| x.scale_grid_kept); + assert_eq!((grid(&s, id), kept(&s)), (None, Some(moved)), "kept, not applied"); + // Off twice keeps them still; saved and opened, they are still there. + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let file = crate::format::to_json(&s.doc).unwrap(); + assert!(file.contains("scale_grid_kept")); + let mut s = Session::new(crate::format::from_json(&file).unwrap()); + assert_eq!(kept(&s), Some(moved)); + run(&mut s, "symbol.set_scale_grid", json!({"symbol": id.0, "on": true})); + assert_eq!((grid(&s, id), kept(&s)), (Some(moved), None), "on again: back where they were"); + // Undo goes back to off with the guides kept. + s.undo().unwrap(); + assert_eq!((grid(&s, id), kept(&s)), (None, Some(moved))); + // A kept grid that isn't usable, or kept beside guides that are on, is dropped on load. + let mut d = s.doc.clone(); + let sym = std::sync::Arc::make_mut(&mut d.library[0]); + sym.scale_grid_kept = Some(ScaleGrid { left: 5.0, right: -5.0, top: 0.0, bottom: 1.0 }); + let d = crate::format::from_json(&crate::format::to_json(&d).unwrap()).unwrap(); + assert_eq!(d.library[0].scale_grid_kept, None); + let mut d = s.doc.clone(); + let sym = std::sync::Arc::make_mut(&mut d.library[0]); + sym.scale_grid = Some(moved); + let d = crate::format::from_json(&crate::format::to_json(&d).unwrap()).unwrap(); + assert_eq!((d.library[0].scale_grid, d.library[0].scale_grid_kept), (Some(moved), None)); } #[test] @@ -101,10 +133,12 @@ fn the_guides_survive_the_file_and_older_files_open_without_them() { assert!(text.contains("\"scale_grid\"")); let back = crate::format::from_json(&text).unwrap(); assert_eq!(back.symbol(id).and_then(|x| x.scale_grid), grid(&s, id)); - // A symbol without guides writes nothing for them, so older files read the same. + // A symbol whose guides are off keeps them apart (ADR 0057), and one that never had any + // writes nothing for them, so older files read the same. run(&mut s, "symbol.set_scale_grid", json!({"on": false})); let text = crate::format::to_json(&s.doc).unwrap(); - assert!(!text.contains("scale_grid")); + assert!(!text.contains("\"scale_grid\"") && text.contains("\"scale_grid_kept\"")); + assert!(!crate::format::to_json(&panel().0.doc).unwrap().contains("scale_grid")); assert_eq!(crate::format::from_json(&text).unwrap().symbol(id).and_then(|x| x.scale_grid), None); // Unusable guides in a file are dropped, not drawn. let mut doc = s.doc.clone(); diff --git a/crates/engine/src/tests_bone.rs b/crates/engine/src/tests_bone.rs index 3f841149..54b7f6e5 100644 --- a/crates/engine/src/tests_bone.rs +++ b/crates/engine/src/tests_bone.rs @@ -31,7 +31,7 @@ pub(crate) fn three_bars() -> Session { k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) })); k }); - d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let inst = |id: u64, x: f32| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 100.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: bar, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } }); let shape = Arc::new(Element { id: ElementId(SHAPE), name: String::new(), transform: Affine::translate(100.0, 250.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::BLACK))) }); let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); diff --git a/crates/engine/src/tests_sound.rs b/crates/engine/src/tests_sound.rs index 0e11a7ec..657679c5 100644 --- a/crates/engine/src/tests_sound.rs +++ b/crates/engine/src/tests_sound.rs @@ -308,7 +308,7 @@ fn sounds_inside_symbols_are_in_the_exported_soundtrack_at_their_offset_and_loop let mut k = Keyframe::new(1, 3); k.sound = Some(FrameSound::new(SoundId(id))); inner.keyframes = vec![Arc::new(Keyframe::new(0, 1)), Arc::new(k)]; - s.doc.library.push(Arc::new(Symbol { linkage: None, scale_grid: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + s.doc.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let mut k = Keyframe::new(1, 8); k.elements.push(Arc::new(Element { id: ElementId(502), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(501), loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } })); let mut outer = Layer::new(LayerId(503), "puppet"); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 9320bc6f..d3d63fea 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -476,7 +476,7 @@ fn nine_slice_sample() -> anicraft_doc::Document { k.elements.push(el(2, Affine::IDENTITY, ElementKind::Shape(shape))); let mut l = Layer::new(LayerId(3), "art"); l.keyframes = vec![std::sync::Arc::new(k)]; - d.library.push(std::sync::Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: Some(ScaleGrid { left: 8.0, right: 52.0, top: 8.0, bottom: 22.0 }), timeline: Timeline { layers: vec![std::sync::Arc::new(l)] } })); + d.library.push(std::sync::Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: Some(ScaleGrid { left: 8.0, right: 52.0, top: 8.0, bottom: 22.0 }), timeline: Timeline { layers: vec![std::sync::Arc::new(l)] } })); let inst = |id, xf| el(id, xf, ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }); let mut k = Keyframe::new(0, 1); k.elements.push(inst(5, Affine::translate(10.0, 10.0).mul(&Affine::scale(4.5, 1.2)))); diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 1a22e460..3afbc3fa 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -36,7 +36,7 @@ fn layer(id: u64, keys: Vec>) -> Arc { } fn symbol(id: u64, kind: SymbolKind, layers: Vec>) -> Arc { - Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid: None, timeline: Timeline { layers } }) + Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers } }) } fn this() -> Target { @@ -463,7 +463,7 @@ fn frames_are_baked_and_stored_once() { assert!(m.stats.paths < 40, "{:?}", m.stats); // Unused library symbols stay out. let mut d = doc.clone(); - d.library.push(Arc::new(Symbol { id: SymbolId(999_999), name: "unused".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, timeline: Timeline::default() })); + d.library.push(Arc::new(Symbol { id: SymbolId(999_999), name: "unused".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline::default() })); assert_eq!(movie(&d, &HtmlOptions::default()).json["symbols"], m.json["symbols"]); } @@ -608,8 +608,8 @@ fn sounds_carry_their_envelopes_and_volumes_and_start_in_graphics_and_clips_as_i let inst = |id, symbol| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } }); // A graphic with a fading sound on its frame 1 (of 2), a clip with a left-channel one on its // frame 0 (of 3), both on a layer at half volume; a sound of the main timeline's own. - doc.library.push(Arc::new(Symbol { linkage: None, scale_grid: None, id: SymbolId(20), name: "g".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![layer(21, vec![key(0, 1, None, vec![]), key(1, 1, snd(SoundSync::Event, SoundEffect::FadeOut), vec![])], 1.0)] } })); - doc.library.push(Arc::new(Symbol { linkage: None, scale_grid: None, id: SymbolId(30), name: "c".into(), kind: SymbolKind::MovieClip, timeline: Timeline { layers: vec![layer(31, vec![key(0, 3, snd(SoundSync::Stream, SoundEffect::LeftChannel), vec![])], 0.5)] } })); + doc.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(20), name: "g".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![layer(21, vec![key(0, 1, None, vec![]), key(1, 1, snd(SoundSync::Event, SoundEffect::FadeOut), vec![])], 1.0)] } })); + doc.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(30), name: "c".into(), kind: SymbolKind::MovieClip, timeline: Timeline { layers: vec![layer(31, vec![key(0, 3, snd(SoundSync::Stream, SoundEffect::LeftChannel), vec![])], 0.5)] } })); doc.timeline_mut(0).layers = vec![layer(1, vec![key(0, 6, snd(SoundSync::Event, SoundEffect::None), vec![])], 1.0), layer(2, vec![key(0, 6, None, vec![inst(40, 20), inst(41, 30)])], 0.5)]; let m = movie(&doc, &HtmlOptions::default()); // The fade's points span one play (half a second); the clip's span its 3 frames. diff --git a/crates/render/src/nine_slice_tests.rs b/crates/render/src/nine_slice_tests.rs index 75a92b54..2ebc5801 100644 --- a/crates/render/src/nine_slice_tests.rs +++ b/crates/render/src/nine_slice_tests.rs @@ -16,7 +16,7 @@ fn panel(sx: f32, sy: f32, guides: bool) -> Document { let mut l = Layer::new(LayerId(3), "art"); l.keyframes = vec![Arc::new(k)]; let grid = guides.then_some(ScaleGrid { left: 10.0, right: 90.0, top: 10.0, bottom: 30.0 }); - d.library.push(Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(l)] } })); + d.library.push(Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(l)] } })); let inst = Element { id: ElementId(5), name: String::new(), diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 04f57878..e37b711c 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -824,7 +824,7 @@ impl<'a> Builder<'a> { }; let short = name.rsplit('/').next().unwrap_or(&name).to_string(); let scale_grid = self.scale_grid(&item); - self.doc.library.push(Arc::new(Symbol { id, name: short, kind, linkage, scale_grid, timeline })); + self.doc.library.push(Arc::new(Symbol { id, name: short, kind, linkage, scale_grid, scale_grid_kept: None, timeline })); self.place_in_folder(&name, anicraft_doc::LibraryItem::Symbol(id)); } } From 7877a09c04237ff26e65d1701a9fe9fe32430301 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:03:34 -0700 Subject: [PATCH 029/192] feat(engine): an open button shows its hit area; Test Movie lists the sounds it starts (M5) --- crates/engine/src/cmds_actions.rs | 21 ++++++++++- crates/engine/src/editing.rs | 57 ++++++++++++++++++++++++++---- crates/engine/src/editing_tests.rs | 53 +++++++++++++++++++++++++++ crates/engine/src/lib.rs | 5 +++ crates/engine/src/tests_sound.rs | 25 +++++++++++++ 5 files changed, 154 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index 9a94a454..229167a8 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -17,7 +17,7 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y} or {tick, type: key_down|key_up|key, key: code|letter|LEFT…}], seed?: Math.random()'s seed (default 0)} plays the movie with its actions and frame scripts from the first frame; returns the output and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn), + c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y} or {tick, type: key_down|key_up|key, key: code|letter|LEFT…}], seed?: Math.random()'s seed (default 0)} plays the movie with its actions and frame scripts from the first frame; returns the output, the sounds it started ({tick, sound, name, sync, gain}; buttons' as the pointer changes their state) and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn), c("actions.set", "Set Actions", "", None, "{actions: [{op: stop|play|goto_and_play|goto_and_stop|next_frame|prev_frame|next_scene|prev_scene|trace|set_property, target?, frame?, scene?, message?, property?, value?}] | plugin: id, entry?, symbol?: id (a movie clip's timeline), layer?, frame?} sets what the keyframe at the frame runs; or {element, event: click|press|release|over|out, actions} sets an instance's event handler. An empty list clears it", true, set), c("actions.clear", "Clear Actions", "", None, "{symbol?, layer?, frame?} clears the keyframe's actions; {element, event?} clears an instance's handlers (one event, or all)", true, clear), c("actions.list", "List Actions", "", None, "{} every keyframe with actions or a frame script and every instance with event handlers, in every scene and symbol", false, list), @@ -241,6 +241,8 @@ fn set_name(s: &mut Session, p: &Value) -> Result { /// Most steps and events of a headless test. const MAX_TEST_STEPS: u32 = 10_000; const MAX_TEST_EVENTS: usize = 10_000; +/// Most started sounds `control.test_movie` lists (the rest are counted). +const MAX_TEST_SOUNDS: usize = 10_000; fn test_movie(s: &mut Session, p: &Value) -> Result { let fps = s.doc.stage.fps.max(1.0); @@ -262,14 +264,31 @@ fn test_movie(s: &mut Session, p: &Value) -> Result { let seed = opt_u64(p, "seed")?.unwrap_or(anicraft_doc::player::DEFAULT_SEED); let mut runner = ScriptRunner::new(&s.plugins); let mut movie = Movie::start_seeded(&s.doc, seed, &mut runner); + // The sounds the movie started (buttons' under the pointer too, ADR 0057), in order. + let mut sounds: Vec = Vec::new(); + let mut more = 0usize; + let mut heard = |movie: &mut Movie, doc: &anicraft_doc::Document| { + for (tick, st) in movie.take_sounds() { + if sounds.len() >= MAX_TEST_SOUNDS { + more += 1; + continue; + } + let name = doc.sound(st.sound.sound).map(|x| x.name.clone()); + sounds.push(json!({"tick": tick, "sound": st.sound.sound.0, "name": name, "sync": st.sound.sync.key(), "gain": st.gain})); + } + }; + heard(&mut movie, &s.doc); for tick in 1..=u64::from(frames) { let events: Vec<_> = timed.iter().filter(|(t, _)| *t == tick).flat_map(|(_, e)| e.iter().copied()).collect(); movie.step(&s.doc, &events, &mut runner); + heard(&mut movie, &s.doc); } let nodes = anicraft_doc::player::tree(&s.doc, &movie.state); Ok(json!({ "steps": frames, "output": movie.output.iter().map(|(t, l)| json!({"tick": t, "line": l})).collect::>(), + "sounds": sounds, + "more_sounds": more, "state": state_view(&s.doc, &movie.state, &nodes, None), "script_runs": runner.runs, "script_fuel": runner.fuel_used, diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index f1b61b02..60e981d1 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -13,7 +13,7 @@ use crate::history::StateId; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Selection, Session}; -use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LoopMode, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Symbol, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Vec2}; use serde_json::{Value, json}; use std::hash::{Hash, Hasher}; @@ -177,6 +177,8 @@ impl Session { for l in &self.editing { (l.symbol, l.instance, l.frame, l.transform.m.map(f32::to_bits)).hash(&mut h); } + let hit = self.hit_overlay(); + hit.map(|(c, a)| [c.r, c.g, c.b, c.a, a].map(f32::to_bits)).hash(&mut h); let key = h.finish(); if let Some((k, pic)) = &*self.picture_cache.borrow() && *k == key @@ -188,7 +190,12 @@ impl Session { // The open symbol, in front. let at = Affine::translate(view.origin.x, view.origin.y).mul(&Affine::scale(view.scale, view.scale)); let open = self.timeline().clone(); - let layer = placed(&mut doc, open.clone(), at, self.frame, 1.0); + // A button's hit area over the state being edited, translucent (ADR 0057). + if let Some((tint, alpha)) = hit { + let frame = anicraft_doc::player::hit_frame(open.frame_count()); + tl.layers.push(placed(&mut doc, hit_timeline(&open), at, frame, ColorEffect { alpha, tint, tint_amount: 1.0 })); + } + let layer = placed(&mut doc, open.clone(), at, self.frame, ColorEffect::default()); let front = Arc::new(Front { layer: layer.id, timeline: open, frame: self.frame, at }); tl.layers.push(layer); // Around it, dimmed: each timeline below, without the instance opened from it. @@ -200,7 +207,7 @@ impl Session { Some(p) => self.doc.symbol(p.symbol).map(|s| s.timeline.clone()).unwrap_or_default(), }; let xf = parent.map_or(Affine::IDENTITY, |p| p.transform); - tl.layers.push(placed(&mut doc, without(below, l.instance), xf, l.frame, DIM)); + tl.layers.push(placed(&mut doc, without(below, l.instance), xf, l.frame, ColorEffect { alpha: DIM, ..ColorEffect::default() })); } } *doc.timeline_mut(self.scene) = tl; @@ -211,9 +218,47 @@ impl Session { } } +impl Session { + /// The tint and opacity the stage draws the open button's hit area in (ADR 0057): while a + /// button is open and its playhead is on another frame than the one that answers the + /// pointer (the Hit frame, or Up when it has none), and [`Session::hit_area`] is set. + pub fn hit_overlay(&self) -> Option<(anicraft_doc::Rgba, f32)> { + let (tint, alpha) = self.hit_area?; + let sym = self.editing_symbol().and_then(|id| self.doc.symbol(id))?; + let frame = anicraft_doc::player::hit_frame(sym.timeline.frame_count()); + (sym.kind == SymbolKind::Button && self.frame != frame && alpha.is_finite() && alpha > 0.0).then_some((tint, alpha.min(1.0))) + } +} + +/// What answers the pointer on a button with timeline `tl`, as a timeline to draw (the hit test's +/// rules, `doc::player::hit_area`): mask layers go and what they masked is whole again, guide +/// layers are hidden (they still steer what follows them). +fn hit_timeline(tl: &Timeline) -> Timeline { + let masks: Vec = tl.layers.iter().filter(|l| l.kind == LayerKind::Mask).map(|l| l.id).collect(); + let layers = tl + .layers + .iter() + .filter(|l| l.kind != LayerKind::Mask) + .map(|l| { + if l.kind != LayerKind::Guide && !l.parent.is_some_and(|p| masks.contains(&p)) { + return l.clone(); + } + let mut l = (**l).clone(); + if l.kind == LayerKind::Guide { + l.visible = false; + } + if l.parent.is_some_and(|p| masks.contains(&p)) { + l.parent = None; + } + Arc::new(l) + }) + .collect(); + Timeline { layers } +} + /// A layer holding `timeline` as a graphic symbol's instance at `transform`, showing its `frame` -/// at opacity `alpha` (a symbol added to `doc`, which is only drawn). -fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, alpha: f32) -> Arc { +/// with colour effect `color` (a symbol added to `doc`, which is only drawn). +fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, color: ColorEffect) -> Arc { let symbol = SymbolId(doc.alloc_id()); doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline })); let mut k = Keyframe::new(0, 1); @@ -221,7 +266,7 @@ fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, id: ElementId(doc.alloc_id()), name: String::new(), transform, - color: ColorEffect { alpha, ..ColorEffect::default() }, + color, kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, })); let mut layer = Layer::new(LayerId(doc.alloc_id()), ""); diff --git a/crates/engine/src/editing_tests.rs b/crates/engine/src/editing_tests.rs index 18b6a459..4b38fa91 100644 --- a/crates/engine/src/editing_tests.rs +++ b/crates/engine/src/editing_tests.rs @@ -106,6 +106,59 @@ fn opening_from_the_library_and_guards() { assert!(s.editing.is_empty()); } +/// The sample's Play button open from the Library (at the stage's centre, 640 × 360): its face is +/// 220 × 80, its Hit frame 240 × 100. +fn open_button(hit: Option<(anicraft_doc::Rgba, f32)>) -> Session { + let mut s = Session::new(anicraft_doc::sample::interactive()); + let id = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id).unwrap_or_else(|| panic!("a button")); + run(&mut s, "symbol.edit", json!({"symbol": id.0})); + s.hit_area = hit; + s +} + +#[test] +fn an_open_button_shows_its_hit_area_over_its_other_states() { + let red = anicraft_doc::Rgba::new(1.0, 0.0, 0.0, 1.0); + let render = |s: &Session| { + let pic = s.stage_picture(); + anicraft_render::render_frame(&pic.doc, pic.frame, 1.0).unwrap_or_else(|e| panic!("{e}")) + }; + let plain = render(&open_button(None)); + let mut s = open_button(Some((red, 0.5))); + assert_eq!(s.hit_overlay(), Some((red, 0.5)), "on the Up frame"); + let shown = render(&s); + let px = |p: &anicraft_render::Pixmap, x: u32, y: u32| p.pixel(x, y).unwrap_or_else(|| panic!("({x}, {y}) in the picture")); + // Inside the Hit frame but outside the face (x = 640 + 115): the background, half red now. + let (bg, over) = (px(&plain, 755, 360), px(&shown, 755, 360)); + for c in 0..3 { + let want = bg[c] * 0.5 + if c == 0 { 0.5 } else { 0.0 }; + assert!((over[c] - want).abs() < 0.02, "channel {c}: {over:?} vs {want} (background {bg:?})"); + } + // Over the face (blue) and its arrow (white) alike: half red over what the state shows. + for (x, y) in [(600, 360), (640, 360)] { + let (art, over) = (px(&plain, x, y), px(&shown, x, y)); + for c in 0..3 { + let want = art[c] * 0.5 + if c == 0 { 0.5 } else { 0.0 }; + assert!((over[c] - want).abs() < 0.02, "({x}, {y}) channel {c}: {over:?} vs {want}"); + } + } + // Outside the Hit frame: untouched. + assert_eq!(px(&shown, 775, 360), px(&plain, 775, 360)); + // On the Hit frame itself, nothing over it; it isn't in the document either. + s.set_frame(3); + assert_eq!(s.hit_overlay(), None); + let on_hit = render(&s); + s.hit_area = None; + assert_eq!(on_hit.to_rgba8(), render(&s).to_rgba8()); + assert_eq!(s.doc.library.len(), anicraft_doc::sample::interactive().library.len()); + // Only buttons: a movie clip open shows none. + let mut s = Session::new(anicraft_doc::sample::interactive()); + let clip = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::MovieClip).map(|x| x.id).unwrap_or_else(|| panic!("a clip")); + run(&mut s, "symbol.edit", json!({"symbol": clip.0})); + s.hit_area = Some((red, 0.5)); + assert_eq!(s.hit_overlay(), None); +} + #[test] fn the_stage_shows_the_open_symbol_in_place_over_the_dimmed_stage() { let (mut s, _, _) = boxed(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 17e44ea9..e154ab5f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -294,6 +294,10 @@ pub struct Session { pub(crate) pending_cut: Option<(CutOrigin, Vec)>, /// The open gesture began on a provisional cut: the document with the cut. gesture_cut: Option, + /// How a button open for editing shows its hit area over its other states (ADR 0057): the + /// tint and opacity, or `None` for no overlay (the default; the app sets it from its theme). + /// View state, like the playhead: never in the document or its undo history. + pub hit_area: Option<(anicraft_doc::Rgba, f32)>, /// The last picture of an open symbol in place, by its key (ADR 0045). picture_cache: RefCell)>>, } @@ -360,6 +364,7 @@ impl Session { provisional: None, pending_cut: None, gesture_cut: None, + hit_area: None, picture_cache: RefCell::new(None), } } diff --git a/crates/engine/src/tests_sound.rs b/crates/engine/src/tests_sound.rs index 657679c5..686c8aef 100644 --- a/crates/engine/src/tests_sound.rs +++ b/crates/engine/src/tests_sound.rs @@ -328,3 +328,28 @@ fn sounds_inside_symbols_are_in_the_exported_soundtrack_at_their_offset_and_loop } let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn sounds_on_a_button_s_frames_play_in_test_movie_and_stay_out_of_the_soundtrack() { + let dir = temp_dir("button"); + let wav = dir.join("click.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &source())).unwrap(); + let mut s = Session::new(anicraft_doc::sample::interactive()); + let id = run(&mut s, "file.import_to_library", json!({"path": wav.display().to_string()}))["sound"].as_u64().unwrap(); + // Inside the Play button, a click on its Over frame and another on its Down frame. + let button = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id).unwrap(); + run(&mut s, "symbol.edit", json!({"symbol": button.0})); + run(&mut s, "sound.place", json!({"sound": id, "frame": 1})); + run(&mut s, "sound.place", json!({"sound": id, "frame": 2, "sync": "stream"})); + run(&mut s, "symbol.exit", json!({})); + // The button stands at (640, 400) on the menu. + let v = run(&mut s, "control.test_movie", json!({"frames": 6, "events": [{"tick": 2, "type": "move", "x": 640, "y": 400}, {"tick": 4, "type": "down", "x": 640, "y": 400}]})); + let heard: Vec<(u64, &str)> = v["sounds"].as_array().unwrap().iter().map(|x| (x["tick"].as_u64().unwrap(), x["sync"].as_str().unwrap())).collect(); + assert_eq!(heard, [(2, "event"), (4, "event")], "Over, then Down (a stream plays as an event): {v}"); + assert_eq!(v["sounds"][0]["name"], "click.wav"); + // Nothing on the timelines plays them: the exported soundtrack is silent. + let out = dir.join("silent.wav"); + run(&mut s, "file.export_audio", json!({"path": out.display().to_string(), "rate": 8000, "bits": 32, "confirm": true})); + let pcm = audio::decode(&std::fs::read(&out).unwrap()).unwrap(); + assert!(pcm.samples.iter().all(|x| *x == 0.0)); +} From e60f65e8005dae2f320a5288fda6b7f873e6bbef Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:04:59 -0700 Subject: [PATCH 030/192] feat(html): the page plays sounds on button frames with Web Audio, as Test Movie does (M5) --- crates/render/src/html.rs | 4 --- crates/render/src/html/player.js | 57 +++++++++++++++++++++++++++++--- crates/render/src/html_tests.rs | 56 +++++++++++++++++++++++++++++++ 3 files changed, 108 insertions(+), 9 deletions(-) diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 1eeb964e..6ec7d206 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -95,7 +95,6 @@ const FILTERS: &str = "filters (not exported; drawn without them)"; 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 outside the ActionScript subset (not run; kept in the document only)"; const NINE_SLICE: &str = "9-slice scaling (scaled as a whole)"; const OUTSIDE_CALLS: &str = "script calls that reach outside the movie (ignored)"; @@ -706,9 +705,6 @@ pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie { frames += sym.timeline.frame_count() as usize; let decls = (sym.kind == SymbolKind::MovieClip).then(|| anicraft_doc::player::decls(doc, TimelineRef::Symbol(*id))); timelines.push(b.timeline(&sym.timeline, false, decls.as_ref())); - if b.sound && sym.kind == SymbolKind::Button && sym.timeline.layers.iter().any(|l| l.has_sounds()) { - b.notes.entry(BUTTON_SOUNDS).or_default().insert(sym.id.0); - } let kind = match sym.kind { SymbolKind::Graphic => "graphic", SymbolKind::MovieClip => "movieclip", diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index 7e488cdc..8e9de0df 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -163,10 +163,26 @@ var AniCraft = (function () { const c = st.clips.get(key); return Math.min(c ? c.frame : 0, Math.max(len, 1) - 1); } + // Where the pointer leaves a button (player.rs `ButtonState`): Up (0), Over (1), Down (2), or + // pressed on it and dragged off (3, shown Up). + function buttonState(hover, pressed, down, path) { + const held = down && samePath(pressed, path); + return samePath(hover, path) ? (held ? 2 : 1) : held ? 3 : 0; + } + // The frame whose sound plays as a button goes from state `a` to `b` (player.rs + // `button_sound_frame`, ADR 0057): Over's going over it, Up's leaving, Down's pressing, Hit's + // letting go over it; -1 for none. + function buttonSoundFrame(a, b) { + if (a === 0 && b === 1) return 1; + if (a === 1 && b === 0) return 0; + if (a === 1 && b === 2) return 2; + if (a === 2 && b === 1) return 3; + return -1; + } // Up (0), Over (1) under the pointer, Down (2) while pressed on it. function buttonFrame(st, path, len) { - const over = samePath(st.hover, path); - const f = over ? (st.down && samePath(st.pressed, path) ? 2 : 1) : 0; + const s = buttonState(st.hover, st.pressed, st.down, path); + const f = s === 1 || s === 2 ? s : 0; return Math.min(f, Math.max(len, 1) - 1); } @@ -1063,10 +1079,34 @@ var AniCraft = (function () { }; // The sounds of timeline `tl`'s keyframes starting at `frame`, as // [sound, sync, repeat, loop, span, gain, envelope], the gain times `gain`. - Run.prototype.soundsAt = function (tl, frame, gain) { + // On a button's frame (`button`) a stream plays as an event: the frame has no span to stream + // over (ADR 0057). + Run.prototype.soundsAt = function (tl, frame, gain, button) { for (const s of (tl.snd && tl.snd[frame]) || []) { if (this.sounds.length >= MAX_SOUNDS_PER_STEP) return; - this.sounds.push([s[0], s[1], s[2], s[3], s[4], (s[5] === undefined ? 1 : s[5]) * gain, s[6] || null]); + const sync = button && s[1] === "stream" ? "event" : s[1]; + this.sounds.push([s[0], sync, s[2], s[3], s[4], (s[5] === undefined ? 1 : s[5]) * gain, s[6] || null]); + } + }; + // Where the pointer is, for buttonSounds. + Run.prototype.pointerNow = function () { + return { hover: this.st.hover, pressed: this.st.pressed, down: this.st.down }; + }; + // Starts the sounds of the buttons whose state changed since `before` (pointerNow then). + Run.prototype.buttonSounds = function (before) { + const st = this.st; + const same = (a, b) => (a === null ? b === null : samePath(a, b)); + if (same(before.hover, st.hover) && same(before.pressed, st.pressed) && before.down === st.down) return; + this.refresh(); + const paths = []; + for (const p of [before.hover, before.pressed, st.hover, st.pressed]) if (p !== null && !paths.some((q) => samePath(q, p))) paths.push(p); + for (const path of paths) { + const f = buttonSoundFrame(buttonState(before.hover, before.pressed, before.down, path), buttonState(st.hover, st.pressed, st.down, path)); + if (f < 0) continue; + const i = this.indexOf(path); + if (i < 0 || this.nodes[i].kind !== BUTTON) continue; + const s = this.M.symbols[this.nodes[i].sym]; + if (s) this.soundsAt(this.M.timelines[s.tl], f, this.nodes[i].gain, true); } }; Run.prototype.out = function (line) { @@ -1577,19 +1617,24 @@ var AniCraft = (function () { case "move": this.pointer(e); break; - case "down": + case "down": { this.pointer(e); + const before = this.pointerNow(); st.down = true; st.pressed = st.hover; this.dirty = true; + this.buttonSounds(before); if (st.hover !== null) this.fire(st.hover, "press"); break; + } case "up": { this.pointer(e); + const before = this.pointerNow(); st.down = false; const pressed = st.pressed; st.pressed = null; this.dirty = true; + this.buttonSounds(before); if (st.hover !== null) { const h = st.hover; this.fire(h, "release"); @@ -1617,9 +1662,11 @@ var AniCraft = (function () { const now = p ? hitIn(this.M, st, this.nodes, this.host, p.x, p.y) : null; const same = now === null ? st.hover === null : samePath(now, st.hover); if (!same) { + const before = this.pointerNow(); const old = st.hover; st.hover = now; this.dirty = true; + this.buttonSounds(before); if (old !== null) this.fire(old, "out"); if (now !== null) this.fire(now, "over"); } diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 3afbc3fa..b557daaf 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -630,6 +630,62 @@ fn sounds_carry_their_envelopes_and_volumes_and_start_in_graphics_and_clips_as_i } } +#[test] +fn button_sounds_start_in_the_page_as_in_the_player() { + use anicraft_doc::{FrameSound, Sound, SoundId, SoundSync}; + // A button at (100, 100), 10 × 10 art, a 100 × 100 Hit frame; a sound on each of its frames + // (Over's a stream) on a layer at half volume; the button's own layer at half volume too. + let mut d = Document::default(); + for (i, name) in ["up", "over", "down", "hit"].iter().enumerate() { + let wav = anicraft_doc::audio::wav::encode(8000, 1, &[0.25; 800], anicraft_doc::audio::wav::Bits::Int16); + d.sounds.push(Arc::new(Sound::from_data(SoundId(60 + i as u64), *name, wav).unwrap())); + } + let with = |k: Arc, i: u64, sync| { + let mut k = (*k).clone(); + k.sound = Some(FrameSound { sync, ..FrameSound::new(SoundId(60 + i)) }); + Arc::new(k) + }; + let mut sounds = (*layer(34, vec![with(kf(0, 1, vec![], vec![], ""), 0, SoundSync::Event), with(kf(1, 1, vec![], vec![], ""), 1, SoundSync::Stream), with(kf(2, 1, vec![], vec![], ""), 2, SoundSync::Event), with(kf(3, 1, vec![], vec![], ""), 3, SoundSync::Event)])).clone(); + sounds.volume = 0.5; + let art = || vec![rect(32, 0.0, 0.0, 10.0, 10.0, 0x336699)]; + let states = layer(31, vec![kf(0, 1, art(), vec![], ""), kf(1, 1, art(), vec![], ""), kf(2, 1, art(), vec![], ""), kf(3, 1, vec![rect(33, 0.0, 0.0, 100.0, 100.0, 0)], vec![], "")]); + d.library.push(symbol(300, SymbolKind::Button, vec![Arc::new(sounds), states])); + let mut holder = (*layer(2, vec![kf(0, 4, vec![inst(3, 300, "go", Affine::translate(100.0, 100.0), vec![])], vec![], "")])).clone(); + holder.volume = 0.5; + d.timeline_mut(0).layers = vec![Arc::new(holder)]; + let m = movie(&d, &HtmlOptions::default()); + let names: Vec = m.json["sounds"].as_array().unwrap().iter().map(|s| s["name"].as_str().unwrap().to_string()).collect(); + assert_eq!(names.len(), 4, "every button sound is embedded"); + assert!(m.report.keys().all(|n| !n.contains("button")), "nothing reported: {:?}", m.report); + let mut js = Js::new(&m); + let mut r = start(&d, &mut NoScripts); + js.eval("P.start()"); + let at = |x, y| Vec2::new(x, y); + // Over, about, Down, Hit (released), Up (left), Over and Down at once, dragged off and back. + let batches: Vec> = vec![ + vec![Event::Move(at(150.0, 150.0))], + vec![Event::Move(at(160.0, 150.0))], + vec![Event::Down(at(160.0, 150.0))], + vec![Event::Up(at(160.0, 150.0))], + vec![Event::Leave], + vec![Event::Down(at(150.0, 150.0))], + vec![Event::Move(at(400.0, 300.0)), Event::Move(at(150.0, 150.0)), Event::Up(at(150.0, 150.0))], + ]; + let mut heard = Vec::new(); + for (i, events) in batches.iter().enumerate() { + // Between frames and with a frame, alike. + let (rs, page) = if i % 2 == 0 { (anicraft_doc::player::input(&d, &r.state, events, &mut NoScripts), js.eval(&format!("P.input({}).sounds", js_events(events)))) } else { (step(&d, &r.state, events, &mut NoScripts), js.eval(&format!("P.step({}).sounds", js_events(events)))) }; + let theirs: Vec = rs.sounds.iter().map(|s| json!([d.sound(s.sound.sound).unwrap().name, s.sound.sync.key(), f64::from(s.gain)])).collect(); + let ours: Vec = page.as_array().unwrap().iter().map(|s| json!([names[s[0].as_u64().unwrap() as usize], s[1], s[5].as_f64()])).collect(); + assert_eq!(ours, theirs, "batch {i}"); + heard.extend(theirs); + r = rs; + } + let order: Vec<&str> = heard.iter().map(|h| h[0].as_str().unwrap()).collect(); + assert_eq!(order, ["over", "down", "hit", "up", "over", "down", "hit"]); + assert!(heard.iter().all(|h| h[1] == "event" && h[2] == 0.25), "{heard:?}"); +} + #[test] fn hostile_documents_export_without_panicking() { let mut doc = Document::default(); From 255cf5e2690111056259a593c5e872e2d7b5dab0 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:06:29 -0700 Subject: [PATCH 031/192] feat(xfl): sounds in the package come across, on frames and button states (M5) --- crates/xfl/src/import.rs | 83 +++++++++++++++++++++++++++++++++++++--- crates/xfl/src/tests.rs | 62 ++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 5 deletions(-) diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index e37b711c..499073c4 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -11,9 +11,10 @@ //! JPEG in the package; text fields, laid out with this computer's fonts (`text`, ADR 0014); //! frame scripts, symbol linkage classes and the document class, kept verbatim (ADR 0013 tier //! 1); frame scripts in the ActionScript 3.0 subset run in Test Movie (tier 2), and the report -//! lists which run and which are only kept. -//! Everything else (sound, motion tweens with property curves, unknown filters, -//! bitmaps kept only in Animate's own storage) is counted in the report instead of guessed at, +//! lists which run and which are only kept; sounds whose file is in the package as WAV, Ogg +//! Vorbis or MP3, and the sounds on frames that use them, buttons' states included (ADR 0057). +//! Everything else (sounds and bitmaps kept only in Animate's own storage, sound effects, +//! motion tweens with property curves, unknown filters) is counted in the report instead of guessed at, //! and so is whatever is drawn the nearest way AniCraft can (ragged, stipple and hatched //! strokes, reflecting gradients, advanced colour effects, …). The self-authored corpus in `tests/corpus/` covers //! every feature listed here, with golden renders (ADR 0035). @@ -22,7 +23,7 @@ use crate::edges::{self, Edge}; use crate::xml::{self, Element as X}; use anicraft_doc::{ Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, - Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, Language, Linkage, ScaleGrid, SourceScript, + Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, FrameSound, Language, Linkage, ScaleGrid, SoundSync, SourceScript, }; use anicraft_geom::{Affine, FillRule, Path, Vec2}; use anicraft_text::{FaceMatch, Fonts}; @@ -114,6 +115,7 @@ const MAX_SYMBOLS: usize = 20_000; const MAX_LAYERS: usize = 5_000; const MAX_FRAME: u32 = 100_000; const MAX_BITMAPS: usize = 10_000; +const MAX_SOUNDS: usize = 10_000; /// Bitmap fill matrices scale image pixels by twips (1/20 px): `a = 20` is one pixel per pixel. const TWIPS: f32 = 20.0; @@ -130,6 +132,8 @@ struct Builder<'a> { language: Language, /// Library item name → bitmap id, for the bitmaps that could be read. bitmaps: HashMap, + /// Library item name → sound id, for the sounds whose file is in the package (ADR 0057). + sounds: HashMap, report: Report, /// The fonts text is laid out with; the computer's, found on the first text field. fonts: Option<&'a Fonts>, @@ -551,6 +555,9 @@ impl<'a> Builder<'a> { if let Some(a) = f.child("Actionscript") { k.script = self.frame_script(a); } + if let Some(name) = f.attr("soundName").filter(|n| !n.trim().is_empty()) { + k.sound = self.frame_sound(f, name); + } let mut els = Vec::new(); self.elements(f.list("elements"), &Affine::IDENTITY, &mut els, 0); k.elements = els; @@ -720,6 +727,71 @@ impl<'a> Builder<'a> { Ok(()) } + /// Reads the document's sound library items (ADR 0057). Like a bitmap, each one's sound is + /// looked for as the original file in `LIBRARY/` and then as its data file in `bin/`, and is + /// used when it is a WAV, Ogg Vorbis or MP3 file. Animate's own encoding of the data file is + /// not public, so those sounds are reported instead (ADR 0039). + fn register_sounds(&mut self, root: &X) -> Result<(), XflError> { + for item in root.list("media").iter().filter(|i| i.name == "DOMSoundItem").take(MAX_SOUNDS) { + let Some(name) = item.attr("name").filter(|n| !self.sounds.contains_key(*n)) else { continue }; + let mut candidates = Vec::new(); + if let Some(href) = item.attr("href") { + candidates.push(format!("LIBRARY/{href}")); + } + if let Some(data) = item.attr("soundDataHRef") { + candidates.push(format!("bin/{data}")); + } + let short: String = name.rsplit('/').next().unwrap_or(name).chars().take(256).collect(); + let mut found_data = false; + let mut sound = None; + for path in candidates { + let Some(bytes) = (self.read)(&path)? else { continue }; + found_data = true; + if let Ok(s) = anicraft_doc::Sound::from_data(anicraft_doc::SoundId(0), short.clone(), bytes) { + sound = Some(s); + break; + } + } + match sound { + Some(mut s) => { + s.id = anicraft_doc::SoundId(self.doc.alloc_id()); + self.place_in_folder(name, anicraft_doc::LibraryItem::Sound(s.id)); + self.sounds.insert(name.to_string(), s.id); + self.doc.sounds.push(Arc::new(s)); + } + None if found_data => self.report.skip("sounds stored in Animate's own format"), + None => self.report.skip("missing sound files"), + } + } + Ok(()) + } + + /// The sound on a frame (`soundName`, the library item), with its sync (`soundSync`: event, + /// start, stop or stream) and repeats (`soundLoopMode` loop or repeat, `soundLoop` times). + /// Buttons' frames included: they play as the pointer changes the button's state. + fn frame_sound(&mut self, f: &X, name: &str) -> Option { + let Some(id) = self.sounds.get(name).copied() else { + self.report.skip("frame sounds whose sound isn't in the package"); + return None; + }; + let mut fs = FrameSound::new(id); + fs.sync = match f.attr("soundSync").map(str::trim) { + Some("start") => SoundSync::Start, + Some("stop") => SoundSync::Stop, + Some("stream") => SoundSync::Stream, + _ => SoundSync::Event, + }; + fs.looping = f.attr("soundLoopMode").map(str::trim) == Some("loop"); + fs.repeat = f.u32("soundLoop").unwrap_or(1).clamp(1, anicraft_doc::sound::MAX_REPEAT); + if f.attr("soundEffect").is_some_and(|e| !matches!(e.trim(), "" | "none")) || f.child("SoundEnvelope").is_some() { + self.report.skip("sound effects and envelopes (played without)"); + } + if f.attr("inPoint44").is_some() || f.attr("outPoint44").is_some() { + self.report.skip("sound in and out points (played whole)"); + } + Some(fs) + } + /// Allocates ids for every symbol the document lists, parsing their files. fn register_symbols(&mut self, root: &X) -> Result<(), XflError> { let mut seen = HashSet::new(); @@ -868,7 +940,7 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do if root.name != "DOMDocument" { return Err(XflError::NotXfl(format!("the root element is <{}>", root.name))); } - let mut b = Builder { doc: Document::default(), read, ids: HashMap::new(), pending: Vec::new(), language: Language::ActionScript3, bitmaps: HashMap::new(), report: Report::default(), fonts, faces: HashMap::new() }; + let mut b = Builder { doc: Document::default(), read, ids: HashMap::new(), pending: Vec::new(), language: Language::ActionScript3, bitmaps: HashMap::new(), sounds: HashMap::new(), report: Report::default(), fonts, faces: HashMap::new() }; b.publish_settings()?; // Only symbols keep a script class yet. for _ in root.list("media").iter().filter(|m| m.attr("linkageClassName").is_some_and(|c| !c.trim().is_empty())) { @@ -884,6 +956,7 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do }; b.register_folders(&root); b.register_bitmaps(&root)?; + b.register_sounds(&root)?; b.register_symbols(&root)?; b.build_symbols(); // Every DOMTimeline is a scene, in order. diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index b521f172..eb5e310e 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -502,3 +502,65 @@ fn stroke_caps_joints_dashes_and_dots_come_across() { assert_eq!(report.skipped.get("ragged, stipple and hatched strokes (drawn solid)"), Some(&1)); } } + +/// A button whose Over and Down frames hold sounds (ADR 0057), a sound on the main timeline, and +/// sounds the package doesn't hold in a form anyone can read. +const SOUND_DOC: &str = r##" + + + + + + + + + + +"##; + +const PUSH: &str = r##" + + + + + + + +"##; + +#[test] +fn sounds_in_the_package_come_across_on_frames_and_buttons_states() { + let wav = anicraft_doc::audio::wav::encode(8000, 1, &[0.25; 800], anicraft_doc::audio::wav::Bits::Int16); + let files: HashMap> = HashMap::from([ + ("DOMDocument.xml".to_string(), SOUND_DOC.as_bytes().to_vec()), + ("LIBRARY/Push.xml".to_string(), PUSH.as_bytes().to_vec()), + // An XFL folder keeps the original file in LIBRARY/. + ("LIBRARY/Sounds/click.wav".to_string(), wav), + // Animate's own encoding is not public: reported, not guessed. + ("bin/M 2 2.dat".to_string(), vec![1, 2, 3, 4, 5, 6, 7, 8]), + ]); + let read = |p: &str| -> Result>, XflError> { Ok(files.get(p).cloned()) }; + let (doc, report) = import_with(&read).unwrap(); + assert_eq!(doc.sounds.iter().map(|s| (s.name.as_str(), s.rate, s.frames)).collect::>(), [("click.wav", 8000, 800)]); + let click = doc.sounds[0].id; + let path = doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Sound(click))); + assert_eq!(path, "Sounds/click.wav", "in its Library folder"); + // The main timeline's: Start, three times. + let music = doc.timeline(0).layers[0].keyframes[0].sound.clone().unwrap(); + assert_eq!((music.sound, music.sync, music.repeat, music.looping), (click, anicraft_doc::SoundSync::Start, 3, false)); + // The button's Over and Down frames keep theirs; the Hit frame's sound isn't readable. + let push = doc.library.iter().find(|s| s.name == "Push").unwrap(); + let on = |f: u32| push.timeline.layers[0].keyframes.iter().find(|k| k.start == f).and_then(|k| k.sound.clone()); + assert_eq!(on(1).map(|s| (s.sound, s.sync)), Some((click, anicraft_doc::SoundSync::Event))); + assert_eq!(on(2).map(|s| (s.sound, s.sync)), Some((click, anicraft_doc::SoundSync::Stream))); + assert_eq!(on(3), None); + assert_eq!(report.skipped.get("sounds stored in Animate's own format"), Some(&1)); + assert_eq!(report.skipped.get("missing sound files"), Some(&1)); + assert_eq!(report.skipped.get("frame sounds whose sound isn't in the package"), Some(&1)); + assert_eq!(report.skipped.get("sound effects and envelopes (played without)"), Some(&1)); + // In the player, going over the button starts its Over sound. + use anicraft_doc::player::{Event, NoScripts, input, start}; + let s = start(&doc, &mut NoScripts); + let s = input(&doc, &s.state, &[Event::Move(anicraft_geom::Vec2::new(10.0, 10.0))], &mut NoScripts); + assert_eq!(s.sounds.iter().map(|x| x.sound.sound).collect::>(), [click]); +} From 075eb47f231e766a9e33d776ac2471c72c38e751 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:09:05 -0700 Subject: [PATCH 032/192] feat(engine): find.search, find.replace, find.goto and explorer.tree (M8) Find and Replace over text (text fields, labels, layer and instance names, frame scripts), fonts, colours, symbols, sounds and bitmaps, scoped to the scene (with the symbols it uses) or the document; a bounded linear-time regex engine; Replace and Replace All as one undo step, asking above 100 places; going to a hit opens symbols in place through the instances that lead to them. The Movie Explorer tree is made only for open rows, paged, with show filters and a text filter. 24,000 elements: text search 8.8 ms, colour 3.5 ms, Replace All of 12,500 colours 25.5 ms; explorer fully open 144,112 rows in 45 ms. --- Cargo.lock | 39 + Cargo.toml | 3 + crates/engine/Cargo.toml | 1 + crates/engine/src/cmds_library.rs | 49 +- crates/engine/src/cmds_plugin.rs | 2 +- crates/engine/src/cmds_scene.rs | 2 +- crates/engine/src/cmds_text.rs | 2 +- crates/engine/src/confirm.rs | 10 + crates/engine/src/editing.rs | 2 +- crates/engine/src/explorer.rs | 526 +++++++++++++ crates/engine/src/explorer_tests.rs | 205 +++++ crates/engine/src/find.rs | 1117 +++++++++++++++++++++++++++ crates/engine/src/find_tests.rs | 456 +++++++++++ crates/engine/src/lib.rs | 4 + crates/engine/src/tests.rs | 19 + 15 files changed, 2414 insertions(+), 23 deletions(-) create mode 100644 crates/engine/src/explorer.rs create mode 100644 crates/engine/src/explorer_tests.rs create mode 100644 crates/engine/src/find.rs create mode 100644 crates/engine/src/find_tests.rs diff --git a/Cargo.lock b/Cargo.lock index dd0754e2..ee7175cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,6 +134,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "aligned-vec" version = "0.6.4" @@ -286,6 +295,7 @@ dependencies = [ "miniz_oxide 0.8.9", "png 0.17.16", "rayon", + "regex", "serde", "serde_json", "thiserror 2.0.21", @@ -3377,6 +3387,35 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "regress" version = "0.10.5" diff --git a/Cargo.toml b/Cargo.toml index 562023b3..bb1df09d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,6 +56,9 @@ egui = "0.36" # `Instant` and `SystemTime` that work in the browser too (std's panic on wasm32-unknown-unknown); # on other targets a re-export of std::time (MIT OR Apache-2.0; already in the tree via winit). web-time = "1" +# Find and Replace's pattern matching (ADR 0058): linear time, with size limits on what a +# pattern compiles to (MIT OR Apache-2.0). Unicode case folding and word boundaries only. +regex = { version = "1", default-features = false, features = ["std", "perf", "unicode-case", "unicode-perl"] } [workspace.lints.rust] unsafe_code = "forbid" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index d5329679..333dea00 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -21,6 +21,7 @@ thiserror.workspace = true rayon.workspace = true web-time.workspace = true gif.workspace = true +regex.workspace = true [dev-dependencies] # Decodes exported sheets in tests (already in the tree through the renderer). diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs index a607bec6..a542b32f 100644 --- a/crates/engine/src/cmds_library.rs +++ b/crates/engine/src/cmds_library.rs @@ -412,29 +412,14 @@ fn swap_symbol(s: &mut Session, p: &Value) -> Result { /// the old bitmap's. Any other shape filled with a bitmap keeps its outline and fill transform. fn swap_bitmap(s: &mut Session, p: &Value) -> Result { let to = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?); - let Some(new) = s.doc.bitmap(to).map(|b| (b.name.clone(), b.width as f32, b.height as f32)) else { + if s.doc.bitmap(to).is_none() { return Err(EngineError::State(format!("no bitmap with id {}", to.0))); - }; + } let sizes: std::collections::HashMap = s.doc.bitmaps.iter().map(|b| (b.id, (b.name.clone(), b.width as f32, b.height as f32))).collect(); let mut swapped = 0; for e in s.selected_elements_mut()? { - let ElementKind::Shape(sh) = &mut e.kind else { continue }; - let Some(Paint::Bitmap { bitmap, repeat, matrix }) = &mut sh.fill else { continue }; - let old = *bitmap; - *bitmap = to; - swapped += 1; - if old == to { - continue; - } - if let Some((name, w, h)) = sizes.get(&old) - && !*repeat - && *matrix == anicraft_geom::Affine::IDENTITY - && *sh.path == anicraft_geom::Path::rect(0.0, 0.0, *w, *h) - { - sh.path = Arc::new(anicraft_geom::Path::rect(0.0, 0.0, new.1, new.2)); - if e.name == *name { - e.name.clone_from(&new.0); - } + if swap_bitmap_of(e, to, &sizes) { + swapped += 1; } } if swapped == 0 { @@ -443,6 +428,32 @@ fn swap_bitmap(s: &mut Session, p: &Value) -> Result { Ok(json!({"swapped": swapped, "bitmap": to.0})) } +/// Makes a bitmap-filled shape show bitmap `to` (Swap Bitmap, and Find and Replace, ADR 0058): +/// a placed bitmap (a rectangle of the old bitmap's size, filled once at the origin) takes the +/// new one's size and, when it had the old one's name, its name; any other shape keeps its +/// outline and fill transform. `sizes` are every bitmap's name, width and height. False when `e` +/// isn't filled with a bitmap. +pub(crate) fn swap_bitmap_of(e: &mut anicraft_doc::Element, to: BitmapId, sizes: &std::collections::HashMap) -> bool { + let ElementKind::Shape(sh) = &mut e.kind else { return false }; + let Some(Paint::Bitmap { bitmap, repeat, matrix }) = &mut sh.fill else { return false }; + let old = *bitmap; + *bitmap = to; + if old == to { + return true; + } + if let (Some((name, w, h)), Some(new)) = (sizes.get(&old), sizes.get(&to)) + && !*repeat + && *matrix == anicraft_geom::Affine::IDENTITY + && *sh.path == anicraft_geom::Path::rect(0.0, 0.0, *w, *h) + { + sh.path = Arc::new(anicraft_geom::Path::rect(0.0, 0.0, new.1, new.2)); + if e.name == *name { + e.name.clone_from(&new.0); + } + } + true +} + #[cfg(test)] #[path = "library_tests.rs"] mod tests; diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 616bd168..c571ef75 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -31,7 +31,7 @@ const MAX_ELEMENTS: usize = 10_000; /// a namespace this list doesn't know is refused until someone decides (a test checks that /// every registered namespace is known). pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { - const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw", "frames"]; + const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw", "frames", "find", "explorer"]; match id { "edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"), "edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" | "frames.cut" | "frames.copy" | "frames.paste" => { diff --git a/crates/engine/src/cmds_scene.rs b/crates/engine/src/cmds_scene.rs index e5ff51fb..c4fa34cc 100644 --- a/crates/engine/src/cmds_scene.rs +++ b/crates/engine/src/cmds_scene.rs @@ -31,7 +31,7 @@ pub(crate) fn target_scene(s: &Session, p: &Value) -> Result { } /// Opens scene `i` at its first frame, on its top layer. -fn open_scene(s: &mut Session, i: usize) { +pub(crate) fn open_scene(s: &mut Session, i: usize) { // A scene is edited from its own timeline: open symbols close first (ADR 0045). s.exit_all(); s.scene = i.min(s.doc.scenes.len().saturating_sub(1)); diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index a69844b7..33c3a3f7 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -124,7 +124,7 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu Ok((block, note)) } -fn style_of(t: &TextBlock) -> TextStyle { +pub(crate) fn style_of(t: &TextBlock) -> TextStyle { TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing } } diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 57de4cc9..5dae7f2a 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -144,6 +144,16 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: false, }) } + "find.replace" => { + // Replace All over many places asks first (ADR 0058); one undo step takes it back. + let n = crate::find::replace_count(s, p)?; + (n > crate::find::REPLACE_ASK).then(|| Confirmation { + title: "Replace all?".into(), + message: format!("This replaces what was found in {}. You can undo this in one step.", plural(n, "place")), + action: "Replace All".into(), + irreversible: false, + }) + } "library.delete" => { // Routine when nothing deleted is in use and no folder holds anything (undo is there); // asks when instances go with it or a folder takes its contents (ADR 0050). diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index a5078824..1124f7e4 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -274,7 +274,7 @@ fn instance(s: &Session, id: ElementId) -> Option<(LayerId, Arc)> { s.timeline().layers.iter().map(|l| l.id).find_map(|l| s.elements_on(l).into_iter().find(|e| e.id == id).map(|e| (l, e))) } -fn edit(s: &mut Session, p: &Value) -> Result { +pub(crate) fn edit(s: &mut Session, p: &Value) -> Result { if s.editing.len() >= MAX_LEVELS { return Err(EngineError::State(format!("at most {MAX_LEVELS} symbols can be open inside each other"))); } diff --git a/crates/engine/src/explorer.rs b/crates/engine/src/explorer.rs new file mode 100644 index 00000000..8ad5abab --- /dev/null +++ b/crates/engine/src/explorer.rs @@ -0,0 +1,526 @@ +//! The Movie Explorer (ADR 0058), as Animate's: the movie as a tree of scenes › layers › +//! keyframes › what is on them (symbol instances, text, bitmaps, sounds, frame scripts and +//! instance actions), each instance opening into its symbol's own layers, and the Library's +//! symbol definitions. Show filters hide kinds of rows; a text filter keeps the rows whose names +//! hold it, with the rows above them. +//! +//! [`tree`] gives the rows that are showing, in order, each with its depth, so a list can draw +//! only the rows in view. Only open rows' children are made, so the work follows what is shown, +//! and it stops at [`MAX_ROWS`] and [`MAX_DEPTH`]. Every row says where it is as `find.goto` +//! params, which is how a double-click jumps there. + +use crate::find::{Scope, Step}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Document, ElementId, ElementKind, FrameScript, Keyframe, LayerId, LayerKind, Paint, Symbol, SymbolId, SymbolKind, Timeline}; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet}; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![c( + "explorer.tree", + "Movie Explorer", + "", + None, + "{scope?: document (default) | scene, show?: {text?, symbols?, scripts?, media?, frames? (layers and keyframes)} (each default true), definitions?: bool (the Library's symbols; default true), expanded?: [row keys] (default: the top rows), all?: bool (everything open), filter?: text (rows whose names hold it, and the rows above them), offset?, limit? (default 1000, at most 10000)} → {rows: [{key, depth, kind, type?, name, extra, frame?, children, open, go: find.goto params}], total, truncated}", + false, + tree_cmd as crate::RunFn, + )] +} + +/// Most rows one tree makes. +pub const MAX_ROWS: usize = 200_000; +/// Deepest row (instances inside instances). +pub const MAX_DEPTH: usize = 48; +const DEFAULT_LIMIT: usize = 1_000; +const MAX_LIMIT: usize = 10_000; + +/// What a row is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NodeKind { + Scene, + /// The Library's symbols, under one row. + Definitions, + /// A symbol in the Library. + Symbol(SymbolKind), + Layer(LayerKind), + /// A keyframe (its name is its label). + Frame, + /// A keyframe's script or actions. + Script, + /// A button or movie clip instance's actions for one event. + Handler, + Sound, + Instance(SymbolKind), + Text, + Bitmap, +} + +impl NodeKind { + pub fn key(self) -> &'static str { + match self { + NodeKind::Scene => "scene", + NodeKind::Definitions => "definitions", + NodeKind::Symbol(_) => "symbol", + NodeKind::Layer(_) => "layer", + NodeKind::Frame => "frame", + NodeKind::Script => "script", + NodeKind::Handler => "handler", + NodeKind::Sound => "sound", + NodeKind::Instance(_) => "instance", + NodeKind::Text => "text", + NodeKind::Bitmap => "bitmap", + } + } +} + +/// Which kinds of rows show (Animate's Show buttons). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Show { + /// Text fields. + pub text: bool, + /// Buttons, movie clips and graphics. + pub symbols: bool, + /// Frame scripts and instance actions. + pub scripts: bool, + /// Sounds and bitmaps. + pub media: bool, + /// Layers and keyframes; off, what is on them is listed straight under the scene or symbol. + pub frames: bool, +} + +impl Default for Show { + fn default() -> Self { + Show { text: true, symbols: true, scripts: true, media: true, frames: true } + } +} + +/// What the tree shows. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Options { + pub scope: Scope, + pub show: Show, + pub definitions: bool, + /// Open rows, by key. `None`: only the top rows. + pub expanded: Option>, + /// Every row open. + pub all: bool, + pub filter: String, +} + +impl Default for Options { + fn default() -> Self { + Options { scope: Scope::Document, show: Show::default(), definitions: true, expanded: None, all: false, filter: String::new() } + } +} + +/// Where a row is, as `find.goto` params. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Go { + pub scene: Option, + /// The symbol opened alone (from the Library), or to open. + pub symbol: Option, + /// Instances opened in place from the scene or the symbol. + pub path: Vec, + pub layer: Option, + pub frame: Option, + pub element: Option, +} + +impl Go { + pub fn to_json(&self) -> Value { + let mut v = json!({}); + if let Some(s) = self.scene { + v["scene"] = json!(s); + } + if let Some(s) = self.symbol { + v["symbol"] = json!(s.0); + } + if !self.path.is_empty() { + v["path"] = Value::Array(self.path.iter().map(Step::to_json).collect()); + } + if let Some(l) = self.layer { + v["layer"] = json!(l.0); + } + if let Some(f) = self.frame { + v["frame"] = json!(f); + } + if let Some(e) = self.element { + v["element"] = json!(e.0); + } + v + } +} + +/// One row of the tree. +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + /// Stable while the document keeps its ids: what `expanded` names. + pub key: String, + pub depth: usize, + pub kind: NodeKind, + /// Document text: a scene, layer, symbol or sound name, a frame label, a text field's first + /// line, an instance's symbol, a script's summary. + pub name: String, + /// More document text: an instance's name, a text field's font and size. + pub extra: String, + /// The keyframe's first frame (keyframes and what is on them). + pub frame: Option, + pub children: bool, + pub open: bool, + pub go: Go, +} + +impl Row { + pub fn to_json(&self) -> Value { + let mut v = json!({"key": self.key, "depth": self.depth, "kind": self.kind.key(), "name": self.name, "extra": self.extra, "frame": self.frame, "children": self.children, "open": self.open, "go": self.go.to_json()}); + match self.kind { + NodeKind::Symbol(k) | NodeKind::Instance(k) => v["type"] = json!(crate::cmds_library::kind_key(k)), + NodeKind::Layer(k) => v["type"] = json!(format!("{k:?}").to_lowercase()), + _ => {} + } + v + } +} + +/// The tree's rows and whether it stopped at [`MAX_ROWS`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Tree { + pub rows: Vec, + pub truncated: bool, +} + +struct Walk<'a> { + doc: &'a Document, + syms: HashMap, + o: &'a Options, + /// Everything is open (all, or a filter is looking through it all). + every: bool, + rows: Vec, + truncated: bool, +} + +/// The first line of `t`, at most 80 characters. +fn line(t: &str) -> String { + let first = t.lines().next().unwrap_or("").trim(); + let mut out: String = first.chars().take(80).collect(); + if out.len() < first.len() || t.trim().lines().nth(1).is_some() { + out.push('…'); + } + out +} + +impl<'a> Walk<'a> { + fn open(&self, key: &str, depth: usize) -> bool { + self.every || self.o.expanded.as_ref().map_or(depth == 0, |e| e.contains(key)) + } + + /// Adds a row; false once the tree is full. + fn push(&mut self, row: Row) -> bool { + if self.rows.len() >= MAX_ROWS { + self.truncated = true; + return false; + } + self.rows.push(row); + true + } + + fn full(&self) -> bool { + self.truncated + } + + /// Whether a keyframe shows anything (with the frames shown, a labelled keyframe does too). + fn frame_items(&self, k: &Keyframe) -> bool { + let s = self.o.show; + (s.scripts && k.script.is_some()) + || (s.media && k.sound.is_some()) + || k.elements.iter().any(|e| match &e.kind { + ElementKind::Symbol { .. } => s.symbols, + ElementKind::Text(_) => s.text, + ElementKind::Shape(sh) => s.media && matches!(sh.fill, Some(Paint::Bitmap { .. })), + ElementKind::Camera => false, + }) + || (s.frames && !k.label.is_empty()) + } + + fn has_items(&self, tl: &Timeline) -> bool { + tl.layers.iter().any(|l| self.o.show.frames || l.keyframes.iter().any(|k| self.frame_items(k))) + } + + /// The rows of timeline `tl` under `key`, at `depth`. `go` is where the timeline is (scene or + /// symbol, and the instances opened to reach it); `stack` the symbols it is inside. + fn timeline(&mut self, tl: &Timeline, key: &str, depth: usize, go: &Go, stack: &[SymbolId]) { + if depth > MAX_DEPTH { + return; + } + let mut skip_to = 0usize; + for (i, l) in tl.layers.iter().enumerate() { + if self.full() { + return; + } + if i < skip_to { + continue; + } + let lkey = format!("{key}/l{}", l.id.0); + let lgo = Go { layer: Some(l.id), ..go.clone() }; + if self.o.show.frames { + let d = depth + tl.depth(i).min(MAX_DEPTH); + let folder = l.kind == LayerKind::Folder; + let children = if folder { tl.group_range(i).len() > 1 } else { l.keyframes.iter().any(|k| self.frame_items(k)) }; + let open = children && self.open(&lkey, d); + if !self.push(Row { key: lkey.clone(), depth: d, kind: NodeKind::Layer(l.kind), name: l.name.clone(), extra: String::new(), frame: None, children, open, go: lgo.clone() }) { + return; + } + if folder { + if !open { + skip_to = tl.group_range(i).end; + } + continue; + } + if !open { + continue; + } + for k in &l.keyframes { + if !self.frame_items(k) { + continue; + } + let kkey = format!("{lkey}/k{}", k.start); + let kgo = Go { frame: Some(k.start), ..lgo.clone() }; + let children = self.keyframe_has(k); + let open = children && self.open(&kkey, d + 1); + if !self.push(Row { key: kkey.clone(), depth: d + 1, kind: NodeKind::Frame, name: k.label.clone(), extra: String::new(), frame: Some(k.start), children, open, go: kgo.clone() }) { + return; + } + if open { + self.keyframe(k, &kkey, d + 2, &kgo, stack); + } + } + } else { + for k in &l.keyframes { + let kkey = format!("{lkey}/k{}", k.start); + let kgo = Go { frame: Some(k.start), ..lgo.clone() }; + self.keyframe(k, &kkey, depth, &kgo, stack); + } + } + } + } + + /// Whether a keyframe row has children (its label alone makes the row, not children). + fn keyframe_has(&self, k: &Keyframe) -> bool { + let s = self.o.show; + (s.scripts && k.script.is_some()) || (s.media && k.sound.is_some()) || k.elements.iter().any(|e| self.element_shows(e)) + } + + fn element_shows(&self, e: &anicraft_doc::Element) -> bool { + let s = self.o.show; + match &e.kind { + ElementKind::Symbol { .. } => s.symbols, + ElementKind::Text(_) => s.text, + ElementKind::Shape(sh) => s.media && matches!(sh.fill, Some(Paint::Bitmap { .. })), + ElementKind::Camera => false, + } + } + + /// What is on keyframe `k`: its script, its sound, then its elements. + fn keyframe(&mut self, k: &Keyframe, key: &str, depth: usize, go: &Go, stack: &[SymbolId]) { + let s = self.o.show; + let leaf = |key: String, kind: NodeKind, name: String, extra: String, go: Go| Row { key, depth, kind, name, extra, frame: Some(k.start), children: false, open: false, go }; + if s.scripts + && let Some(script) = &k.script + { + let name = match script { + FrameScript::Source(src) => line(&src.text), + other => line(&other.describe()), + }; + if !self.push(leaf(format!("{key}/x"), NodeKind::Script, name, String::new(), go.clone())) { + return; + } + } + if s.media + && let Some(fs) = &k.sound + { + let name = self.doc.sound(fs.sound).map(|x| x.name.clone()).unwrap_or_default(); + if !self.push(leaf(format!("{key}/a"), NodeKind::Sound, name, fs.sync.key().to_string(), go.clone())) { + return; + } + } + for e in &k.elements { + if self.full() || !self.element_shows(e) { + continue; + } + let ekey = format!("{key}/e{}", e.id.0); + let ego = Go { element: Some(e.id), ..go.clone() }; + match &e.kind { + ElementKind::Symbol { symbol, events, .. } => { + let sym = self.syms.get(symbol).copied(); + let nested = sym.filter(|_| !stack.contains(symbol) && stack.len() < MAX_DEPTH); + let children = (s.scripts && !events.is_empty()) || nested.is_some_and(|sym| self.has_items(&sym.timeline)); + let open = children && self.open(&ekey, depth); + let row = Row { + key: ekey.clone(), + depth, + kind: NodeKind::Instance(sym.map_or(SymbolKind::Graphic, |x| x.kind)), + name: sym.map_or_else(String::new, |x| x.name.clone()), + extra: e.name.clone(), + frame: Some(k.start), + children, + open, + go: ego.clone(), + }; + if !self.push(row) || !open { + continue; + } + if s.scripts { + for (n, h) in events.iter().enumerate() { + let desc = h.actions.iter().map(anicraft_doc::Action::describe).collect::>().join("; "); + if !self.push(Row { key: format!("{ekey}/h{n}"), depth: depth + 1, kind: NodeKind::Handler, name: h.event.key().to_string(), extra: line(&desc), frame: Some(k.start), children: false, open: false, go: ego.clone() }) { + return; + } + } + } + if let Some(sym) = nested { + // Inside: the symbol's own timeline, reached by opening this instance. + let (Some(layer), Some(frame)) = (go.layer, go.frame) else { continue }; + let mut inner = Go { scene: go.scene, symbol: go.symbol, path: go.path.clone(), layer: None, frame: None, element: None }; + inner.path.push(Step { layer, frame, element: e.id }); + let mut st = stack.to_vec(); + st.push(*symbol); + self.timeline(&sym.timeline, &ekey, depth + 1, &inner, &st); + } + } + ElementKind::Text(t) => { + if !self.push(leaf(ekey, NodeKind::Text, line(&t.text), format!("{} {}", t.font, t.size), ego)) { + return; + } + } + ElementKind::Shape(sh) => { + let name = match &sh.fill { + Some(Paint::Bitmap { bitmap, .. }) => self.doc.bitmap(*bitmap).map(|b| b.name.clone()).unwrap_or_default(), + _ => String::new(), + }; + if !self.push(leaf(ekey, NodeKind::Bitmap, name, e.name.clone(), ego)) { + return; + } + } + ElementKind::Camera => {} + } + } + } +} + +/// The rows showing for `o`, from scene `scene` (the scope's scene). +pub fn tree(doc: &Document, scene: usize, o: &Options) -> Tree { + let filter = o.filter.trim().to_lowercase(); + let mut w = Walk { doc, syms: doc.library.iter().map(|s| (s.id, &**s)).collect(), o, every: o.all || !filter.is_empty(), rows: Vec::new(), truncated: false }; + let scenes: Vec = match o.scope { + Scope::Document => (0..doc.scenes.len()).collect(), + Scope::Scene => vec![scene.min(doc.scenes.len().saturating_sub(1))], + }; + for i in scenes { + let Some(sc) = doc.scenes.get(i) else { continue }; + let key = format!("s{i}"); + let children = w.has_items(&sc.timeline); + let open = children && w.open(&key, 0); + let go = Go { scene: Some(i), ..Go::default() }; + if !w.push(Row { key: key.clone(), depth: 0, kind: NodeKind::Scene, name: sc.name.clone(), extra: String::new(), frame: None, children, open, go: go.clone() }) { + break; + } + if open { + w.timeline(&sc.timeline, &key, 1, &go, &[]); + } + } + if o.definitions && !doc.library.is_empty() && !w.full() { + let open = w.open("d", 0); + w.push(Row { key: "d".into(), depth: 0, kind: NodeKind::Definitions, name: String::new(), extra: String::new(), frame: None, children: true, open, go: Go::default() }); + if open { + for sym in &doc.library { + let key = format!("d/y{}", sym.id.0); + let children = w.has_items(&sym.timeline); + let open = children && w.open(&key, 1); + let go = Go { symbol: Some(sym.id), ..Go::default() }; + if !w.push(Row { key: key.clone(), depth: 1, kind: NodeKind::Symbol(sym.kind), name: sym.name.clone(), extra: String::new(), frame: None, children, open, go: go.clone() }) { + break; + } + if open { + w.timeline(&sym.timeline, &key, 2, &go, &[sym.id]); + } + } + } + } + let Walk { mut rows, truncated, .. } = w; + if !filter.is_empty() { + rows = filtered(rows, &filter); + } + Tree { rows, truncated } +} + +/// The rows whose name or extra text holds `needle` (lower case), with every row above them. +fn filtered(rows: Vec, needle: &str) -> Vec { + let hit = |r: &Row| r.name.to_lowercase().contains(needle) || r.extra.to_lowercase().contains(needle); + let mut keep = vec![false; rows.len()]; + // The nearest row above at each depth. + let mut above: Vec = Vec::new(); + for (i, r) in rows.iter().enumerate() { + above.truncate(r.depth); + if hit(r) { + if let Some(k) = keep.get_mut(i) { + *k = true; + } + for &a in &above { + if let Some(k) = keep.get_mut(a) { + *k = true; + } + } + } + // (Depths can skip, inside folders: keep the stack's indices in order.) + while above.len() < r.depth { + above.push(above.last().copied().unwrap_or(i)); + } + above.push(i); + } + rows.into_iter().zip(keep).filter_map(|(r, k)| k.then_some(r)).collect() +} + +fn opt_flag(v: &Value, key: &str) -> Result { + Ok(opt_bool(v, key)?.unwrap_or(true)) +} + +/// The options in `p` (`explorer.tree`'s params). +pub fn options_of(p: &Value) -> Result { + let scope = match opt_str(p, "scope")? { + None | Some("document") => Scope::Document, + Some("scene") => Scope::Scene, + Some(o) => return Err(EngineError::Param(format!("'scope' is document or scene, not '{o}'"))), + }; + let show = match p.get("show") { + None | Some(Value::Null) => Show::default(), + Some(v) if v.is_object() => Show { text: opt_flag(v, "text")?, symbols: opt_flag(v, "symbols")?, scripts: opt_flag(v, "scripts")?, media: opt_flag(v, "media")?, frames: opt_flag(v, "frames")? }, + Some(_) => return Err(EngineError::Param("'show' must be {text?, symbols?, scripts?, media?, frames?}".into())), + }; + let expanded = match p.get("expanded") { + None | Some(Value::Null) => None, + Some(Value::Array(list)) => { + if list.len() > MAX_ROWS { + return Err(EngineError::Param(format!("'expanded' names at most {MAX_ROWS} rows"))); + } + Some(list.iter().map(|v| v.as_str().map(str::to_string).ok_or_else(|| EngineError::Param("'expanded' must be a list of row keys".into()))).collect::>>()?) + } + Some(_) => return Err(EngineError::Param("'expanded' must be a list of row keys".into())), + }; + let filter: String = opt_str(p, "filter")?.unwrap_or("").chars().take(256).collect(); + Ok(Options { scope, show, definitions: opt_bool(p, "definitions")?.unwrap_or(true), expanded, all: opt_bool(p, "all")?.unwrap_or(false), filter }) +} + +fn tree_cmd(s: &mut Session, p: &Value) -> Result { + let o = options_of(p)?; + let offset = opt_u64(p, "offset")?.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)); + let limit = opt_u64(p, "limit")?.map_or(DEFAULT_LIMIT, |n| usize::try_from(n).unwrap_or(MAX_LIMIT)).min(MAX_LIMIT); + let t = tree(&s.doc, s.scene, &o); + let rows: Vec = t.rows.iter().skip(offset).take(limit).map(Row::to_json).collect(); + Ok(json!({"rows": rows, "total": t.rows.len(), "offset": offset, "truncated": t.truncated})) +} + +#[cfg(test)] +#[path = "explorer_tests.rs"] +mod tests; diff --git a/crates/engine/src/explorer_tests.rs b/crates/engine/src/explorer_tests.rs new file mode 100644 index 00000000..5eef3319 --- /dev/null +++ b/crates/engine/src/explorer_tests.rs @@ -0,0 +1,205 @@ +//! The Movie Explorer's tree (ADR 0058): its shape for scenes and nested symbols, open rows, +//! the show filters and the text filter, folders, symbols that hold themselves, paging, jumping +//! to a row, and a large document. + +use super::*; +use crate::find::tests::{Build, movie}; +use anicraft_doc::{LayerKind, Paint, Rgba, SymbolKind}; +use serde_json::json; + +fn keys_of(t: &Tree) -> Vec<(usize, NodeKind, String)> { + t.rows.iter().map(|r| (r.depth, r.kind, r.name.clone())).collect() +} + +fn all() -> Options { + Options { all: true, ..Options::default() } +} + +#[test] +fn the_top_rows_show_scenes_their_layers_and_the_library() { + let (s, ..) = movie(); + let t = tree(&s.doc, 0, &Options::default()); + let names: Vec<(usize, &str)> = t.rows.iter().map(|r| (r.depth, r.name.as_str())).collect(); + assert_eq!(names, [(0, "Scene 1"), (1, "Actions"), (1, "Art"), (0, "Scene 2"), (1, "Back"), (0, ""), (1, "Outer"), (1, "Inner"), (1, "Unused")]); + assert!(t.rows[1].children && !t.rows[1].open); + // Scene 2's only layer holds a plain shape: nothing to list under it. + assert!(!t.rows[4].children); + assert_eq!(t.rows[5].kind, NodeKind::Definitions); + assert_eq!(t.rows[6].kind, NodeKind::Symbol(SymbolKind::MovieClip)); + // Scope: one scene. + let one = tree(&s.doc, 1, &Options { scope: Scope::Scene, definitions: false, ..Options::default() }); + assert_eq!(one.rows.iter().map(|r| r.name.as_str()).collect::>(), ["Scene 2", "Back"]); +} + +#[test] +fn instances_open_into_their_symbols_layers_however_deep() { + let (s, outer, inner, _) = movie(); + let t = tree(&s.doc, 0, &all()); + let scene1: Vec<(usize, NodeKind, String)> = keys_of(&t).into_iter().take_while(|r| r.2 != "Scene 2").collect(); + let want = [ + (0, NodeKind::Scene, "Scene 1"), + (1, NodeKind::Layer(LayerKind::Normal), "Actions"), + (2, NodeKind::Frame, ""), + (3, NodeKind::Script, "stop(); // say hello"), + (1, NodeKind::Layer(LayerKind::Normal), "Art"), + (2, NodeKind::Frame, ""), + (3, NodeKind::Text, "Hello world"), + (3, NodeKind::Instance(SymbolKind::MovieClip), "Outer"), + (4, NodeKind::Layer(LayerKind::Normal), "Outer art"), + (5, NodeKind::Frame, ""), + (6, NodeKind::Instance(SymbolKind::Graphic), "Inner"), + (7, NodeKind::Layer(LayerKind::Normal), "Inner art"), + (8, NodeKind::Frame, ""), + (9, NodeKind::Text, "Hello inside"), + (2, NodeKind::Frame, "intro hello"), + (3, NodeKind::Text, "hello hello again"), + ]; + let want: Vec<(usize, NodeKind, String)> = want.iter().map(|(d, k, n)| (*d, *k, n.to_string())).collect(); + assert_eq!(scene1, want); + // The instance row names the instance too, and its frame. + let hero = t.rows.iter().find(|r| r.extra == "hero").unwrap(); + assert_eq!((hero.frame, hero.children, hero.open), (Some(0), true, true)); + // The deepest text: reached by opening hero, then wheel, in place. + let deep = t.rows.iter().find(|r| r.depth == 9).unwrap(); + assert_eq!(deep.go.path.len(), 2); + assert_eq!(deep.go.scene, Some(0)); + let mut s = s; + let v = s.execute("find.goto", &deep.go.to_json()).unwrap(); + assert_eq!(s.editing.iter().map(|l| l.symbol).collect::>(), [outer, inner], "{v}"); + assert_eq!(s.selection.id_list(), [deep.go.element.unwrap().0]); + // Under the Library's Outer: its own layers, then Inner inside it. + let defs: Vec<(usize, String)> = t.rows.iter().skip_while(|r| r.kind != NodeKind::Definitions).map(|r| (r.depth, r.name.clone())).take(8).collect(); + assert_eq!(defs, [(0, String::new()), (1, "Outer".into()), (2, "Outer art".into()), (3, String::new()), (4, "Inner".into()), (5, "Inner art".into()), (6, String::new()), (7, "Hello inside".into())]); + // Keys are unique, so open rows can be remembered. + let mut keys: Vec<&str> = t.rows.iter().map(|r| r.key.as_str()).collect(); + keys.sort_unstable(); + keys.dedup(); + assert_eq!(keys.len(), t.rows.len()); +} + +#[test] +fn only_open_rows_show_their_children() { + let (s, ..) = movie(); + let art = s.doc.timeline(0).layers[1].id.0; + let t = tree(&s.doc, 0, &Options { expanded: Some(["s0".to_string(), format!("s0/l{art}")].into()), definitions: false, ..Options::default() }); + let names: Vec<&str> = t.rows.iter().map(|r| r.name.as_str()).collect(); + assert_eq!(names, ["Scene 1", "Actions", "Art", "", "intro hello", "Scene 2"]); + assert!(t.rows[3].children && !t.rows[3].open); +} + +#[test] +fn show_filters_hide_kinds_and_frames_off_lists_items_straight_under_the_scene() { + let (s, ..) = movie(); + let no_symbols = tree(&s.doc, 0, &Options { show: Show { symbols: false, ..Show::default() }, definitions: false, ..all() }); + assert!(no_symbols.rows.iter().all(|r| !matches!(r.kind, NodeKind::Instance(_)))); + assert!(!no_symbols.rows.iter().any(|r| r.name == "Hello inside")); + let flat = tree(&s.doc, 0, &Options { show: Show { frames: false, ..Show::default() }, definitions: false, scope: Scope::Scene, ..all() }); + let names: Vec<(usize, &str)> = flat.rows.iter().map(|r| (r.depth, r.name.as_str())).collect(); + assert_eq!(names, [(0, "Scene 1"), (1, "stop(); // say hello"), (1, "Hello world"), (1, "Outer"), (2, "Inner"), (3, "Hello inside"), (1, "hello hello again")]); + let no_scripts = tree(&s.doc, 0, &Options { show: Show { scripts: false, ..Show::default() }, ..all() }); + assert!(no_scripts.rows.iter().all(|r| r.kind != NodeKind::Script && r.name != "Actions" || !r.children)); +} + +#[test] +fn the_text_filter_keeps_matches_and_the_rows_above_them() { + let (s, ..) = movie(); + let t = tree(&s.doc, 0, &Options { filter: "INSIDE".into(), ..Options::default() }); + let texts = t.rows.iter().filter(|r| r.kind == NodeKind::Text).count(); + assert_eq!(texts, 3, "{:?}", keys_of(&t)); + // Each row is a match or above one: its next row is deeper, or it matches. + for (i, r) in t.rows.iter().enumerate() { + let matches = r.name.to_lowercase().contains("inside"); + let parent = t.rows.get(i + 1).is_some_and(|n| n.depth > r.depth); + assert!(matches || parent, "{r:?}"); + } + assert!(tree(&s.doc, 0, &Options { filter: "zebra".into(), ..Options::default() }).rows.is_empty()); + // The instance name counts too. + assert!(tree(&s.doc, 0, &Options { filter: "wheel".into(), ..Options::default() }).rows.iter().any(|r| r.extra == "wheel")); +} + +#[test] +fn closed_folders_hide_the_layers_in_them() { + let mut b = Build::new(); + let t1 = b.text("one", Rgba::BLACK); + let t2 = b.text("two", Rgba::BLACK); + let mut folder = b.layer("Folder", vec![(0, 1, "", vec![])]); + folder.kind = LayerKind::Folder; + let mut a = b.layer("A", vec![(0, 1, "", vec![t1])]); + a.parent = Some(folder.id); + let c = b.layer("C", vec![(0, 1, "", vec![t2])]); + let fid = folder.id.0; + b.scene("S", vec![folder, a, c]); + let doc = crate::Session::new(b.doc).doc; + let closed = tree(&doc, 0, &Options { expanded: Some(["s0".to_string()].into()), ..Options::default() }); + assert_eq!(closed.rows.iter().map(|r| (r.depth, r.name.as_str())).collect::>(), [(0, "S"), (1, "Folder"), (1, "C")]); + let open = tree(&doc, 0, &Options { expanded: Some(["s0".to_string(), format!("s0/l{fid}")].into()), ..Options::default() }); + assert_eq!(open.rows.iter().map(|r| (r.depth, r.name.as_str())).collect::>(), [(0, "S"), (1, "Folder"), (2, "A"), (1, "C")]); +} + +#[test] +fn symbols_that_hold_themselves_stop() { + let mut b = Build::new(); + let a = b.symbol("A", SymbolKind::Graphic); + let c = b.symbol("B", SymbolKind::Graphic); + let (ia, ib, self_a) = (b.instance(c, ""), b.instance(a, ""), b.instance(a, "me")); + let l = b.layer("in A", vec![(0, 1, "", vec![ia, self_a])]); + b.fill(a, vec![l]); + let l = b.layer("in B", vec![(0, 1, "", vec![ib])]); + b.fill(c, vec![l]); + let top = b.instance(a, ""); + let l = b.layer("L", vec![(0, 1, "", vec![top])]); + b.scene("S", vec![l]); + let t = tree(&b.doc, 0, &all()); + assert!(t.rows.len() < 40 && !t.truncated, "{}", t.rows.len()); + assert!(t.rows.iter().all(|r| r.depth <= MAX_DEPTH)); +} + +#[test] +fn the_command_pages_rows_with_where_each_goes() { + let (mut s, ..) = movie(); + let v = s.execute("explorer.tree", &json!({"all": true, "offset": 2, "limit": 3})).unwrap(); + assert_eq!(v["rows"].as_array().map(Vec::len), Some(3)); + assert!(v["total"].as_u64().unwrap() > 20); + let r = &v["rows"][1]; + assert_eq!((r["kind"].as_str(), r["depth"].as_u64(), r["name"].as_str()), (Some("script"), Some(3), Some("stop(); // say hello"))); + assert_eq!(r["go"]["frame"], 0); + let v = s.execute("explorer.tree", &json!({"all": true, "show": {"text": false, "scripts": false, "media": false, "frames": false}, "definitions": false})).unwrap(); + let kinds: Vec<&str> = v["rows"].as_array().unwrap().iter().map(|r| r["kind"].as_str().unwrap()).collect(); + assert_eq!(kinds, ["scene", "instance", "instance", "scene"]); + assert_eq!(v["rows"][1]["type"], "movie_clip"); + assert!(s.execute("explorer.tree", &json!({"scope": "galaxy"})).is_err()); + assert!(s.execute("explorer.tree", &json!({"expanded": [1]})).is_err()); +} + +#[test] +fn a_large_movie_makes_its_tree_quickly() { + // 100 layers × 120 keyframes, each with a text and an instance of a symbol of 3 layers. + let mut b = Build::new(); + let sym = b.symbol("Prop", SymbolKind::MovieClip); + let inner: Vec<_> = (0..3).map(|i| { + let r = b.rect(Paint::Solid(Rgba::BLACK), None); + let t = b.text("label", Rgba::BLACK); + b.layer(&format!("p{i}"), vec![(0, 1, "", vec![r, t])]) + }).collect(); + b.fill(sym, inner); + let mut layers = Vec::new(); + for li in 0..100 { + let keys: Vec<_> = (0..120).map(|k| (k, 1, "", vec![b.text(&format!("t {li} {k}"), Rgba::BLACK), b.instance(sym, "")])).collect(); + layers.push(b.layer(&format!("Layer {li}"), keys)); + } + b.scene("Big", layers); + let doc = b.doc; + let t0 = std::time::Instant::now(); + let open = tree(&doc, 0, &all()); + let every = t0.elapsed(); + let t0 = std::time::Instant::now(); + let top = tree(&doc, 0, &Options::default()); + let closed = t0.elapsed(); + let t0 = std::time::Instant::now(); + let found = tree(&doc, 0, &Options { filter: "t 99 119".into(), ..Options::default() }); + let filtered = t0.elapsed(); + println!("Movie Explorer on 24,000 elements: everything open {every:?} ({} rows), top rows {closed:?} ({} rows), filtered {filtered:?} ({} rows)", open.rows.len(), top.rows.len(), found.rows.len()); + assert!(open.rows.len() > 100_000 && !open.truncated); + assert_eq!(found.rows.iter().filter(|r| r.kind == NodeKind::Text).count(), 1); + assert!(every.as_secs_f64() < 3.0 && closed.as_secs_f64() < 0.5); +} diff --git a/crates/engine/src/find.rs b/crates/engine/src/find.rs new file mode 100644 index 00000000..03b6cdd5 --- /dev/null +++ b/crates/engine/src/find.rs @@ -0,0 +1,1117 @@ +//! Find and Replace (ADR 0058), as Animate's Edit › Find and Replace: text (in text fields, +//! frame labels, layer names, instance names and frame scripts), fonts, colours, symbols, sounds +//! and bitmaps, in the current scene (and the symbols it uses) or the whole document. +//! +//! `find.search` lists located hits; `find.replace` replaces one hit or all of them as one undo +//! step (asking first above [`REPLACE_ASK`] places, ADR 0004); `find.goto` jumps to a place: the +//! scene or symbol (opened in place through the instances that lead to it, ADR 0045), the layer, +//! the keyframe and the element, selected. The Movie Explorer (`explorer.tree`) navigates through +//! `find.goto` too. +//! +//! Text is matched with the `regex` crate, whose engine runs in time linear in the text and +//! refuses patterns that would compile too large, so no pattern can hang the editor. Plain text, +//! whole words and case are the same engine with an escaped pattern. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Selection, Session}; +use anicraft_doc::{BitmapId, Document, ElementId, ElementKind, FrameScript, LayerId, Paint, Rgba, SoundId, SourceScript, Symbol, SymbolId, Timeline}; +use regex::{Regex, RegexBuilder}; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "find.search", + "Find and Replace", + "Edit", + Some("Ctrl+F"), + "{kind: text | font | color | symbol | sound | bitmap, text? (kind text: what to find), match_case?, whole_word?, regex? (a pattern; linear-time engine, size-limited), font? (family), color? (#rrggbb; alpha is ignored), symbol? | sound? | bitmap?: library id, in?: [text, labels, layers, instances, scripts] (kind text) | [fills, strokes, text] (kind color) (default: all), scope?: scene (the current scene and the symbols it uses; default) | document, offset?, limit? (default 500, at most 10000)} → {hits: [{kind, field, scene | symbol, layer, layer_name, frame (keyframe start; null on a layer name), element?, start, end (characters, text only), found, context}], total, truncated}", + false, + search_cmd as crate::RunFn, + ), + c( + "find.replace", + "Replace", + "", + None, + "{the find.search query, with: text (kind text; $1 and ${name} insert groups when regex) | family (font) | #rrggbb (color; each place keeps its alpha) | library id (symbol, sound, bitmap), at?: one hit as find.search returned it (Replace); without `at`, every hit (Replace All, one undo step; asks first above 100 places)} → {replaced, skipped, notes}", + true, + replace_cmd, + ), + c( + "find.goto", + "Go to Found Item", + "", + None, + "{layer?: id (its scene or symbol is found), scene?: index, symbol?: id, path?: [{layer, frame, element}] (instances to open in place from `scene`, or from `symbol` opened alone), frame?, element?} goes there: closes open symbols, switches scene or opens the symbol (in place through an instance that uses it when there is one), picks the layer and frame and selects the element", + false, + goto_cmd, + ), + ] +} + +/// Longest text to find (characters). +pub const MAX_QUERY_CHARS: usize = 1_000; +/// Most hits one search keeps. +pub const MAX_HITS: usize = 100_000; +/// Replace All asks first when it would change more places than this (ADR 0004). +pub const REPLACE_ASK: usize = 100; +/// Most a compiled pattern may take (bytes), and its lazy DFA. +const REGEX_LIMIT: usize = 1 << 20; +const DEFAULT_LIMIT: usize = 500; +const MAX_LIMIT: usize = 10_000; +/// Characters of context shown on each side of a text match. +const CONTEXT: usize = 32; +/// Most instances opened in place to reach a symbol (`editing`'s limit). +const MAX_ROUTE: usize = 32; + +/// What is searched for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Text, + Font, + Color, + Symbol, + Sound, + Bitmap, +} + +impl Kind { + pub const ALL: [Kind; 6] = [Kind::Text, Kind::Font, Kind::Color, Kind::Symbol, Kind::Sound, Kind::Bitmap]; + + pub fn key(self) -> &'static str { + match self { + Kind::Text => "text", + Kind::Font => "font", + Kind::Color => "color", + Kind::Symbol => "symbol", + Kind::Sound => "sound", + Kind::Bitmap => "bitmap", + } + } + + pub fn from_key(s: &str) -> Option { + Kind::ALL.into_iter().find(|k| k.key() == s || (s == "colour" && *k == Kind::Color)) + } +} + +/// Where a search looks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Scope { + /// The current scene, and every symbol it uses (however deep). + #[default] + Scene, + /// Every scene and every symbol in the Library, used or not. + Document, +} + +/// A timeline of the document: a scene's, or a Library symbol's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Where { + Scene(usize), + Symbol(SymbolId), +} + +/// The part of the document a hit is in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Field { + /// A text field's text. + Text, + /// A keyframe's label. + Label, + LayerName, + /// An element's instance name. + InstanceName, + /// A keyframe's script source. + Script, + /// A text field's font. + Font, + /// A shape's fill (solid or a gradient stop), stroke, or a text field's colour. + Fill, + Stroke, + TextColor, + /// A symbol instance. + Instance, + /// A keyframe's sound. + Sound, + /// A shape filled with a bitmap (a placed bitmap is one). + Bitmap, +} + +impl Field { + pub const ALL: [Field; 12] = [Field::Text, Field::Label, Field::LayerName, Field::InstanceName, Field::Script, Field::Font, Field::Fill, Field::Stroke, Field::TextColor, Field::Instance, Field::Sound, Field::Bitmap]; + + pub fn key(self) -> &'static str { + match self { + Field::Text => "text", + Field::Label => "label", + Field::LayerName => "layer_name", + Field::InstanceName => "instance_name", + Field::Script => "script", + Field::Font => "font", + Field::Fill => "fill", + Field::Stroke => "stroke", + Field::TextColor => "text_color", + Field::Instance => "instance", + Field::Sound => "sound", + Field::Bitmap => "bitmap", + } + } + + pub fn from_key(s: &str) -> Option { + Field::ALL.into_iter().find(|f| f.key() == s) + } +} + +/// Which places a text or colour search looks in (the others ignore it). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Within { + pub text: bool, + pub labels: bool, + pub layers: bool, + pub instances: bool, + pub scripts: bool, + pub fills: bool, + pub strokes: bool, + pub text_color: bool, +} + +impl Default for Within { + fn default() -> Self { + Within { text: true, labels: true, layers: true, instances: true, scripts: true, fills: true, strokes: true, text_color: true } + } +} + +/// What a query matches. +#[derive(Clone, Debug)] +pub enum Needle { + Text { re: Regex, expand: bool }, + /// A family name, lower-cased and trimmed. + Font(String), + Color([u8; 3]), + Symbol(SymbolId), + Sound(SoundId), + Bitmap(BitmapId), +} + +/// A checked search. +#[derive(Clone, Debug)] +pub struct Query { + pub needle: Needle, + pub within: Within, + pub scope: Scope, +} + +/// The text options of a text search, as the Find and Replace window holds them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct TextOptions { + pub match_case: bool, + pub whole_word: bool, + pub regex: bool, +} + +/// Compiles `text` as a bounded pattern. +pub fn text_needle(text: &str, o: TextOptions) -> Result { + if text.is_empty() { + return Err(EngineError::Param("type something to find".into())); + } + if text.chars().count() > MAX_QUERY_CHARS { + return Err(EngineError::Param(format!("what to find is at most {MAX_QUERY_CHARS} characters"))); + } + let body = if o.regex { text.to_string() } else { regex::escape(text) }; + let pattern = if o.whole_word { format!(r"\b(?:{body})\b") } else { body }; + let re = RegexBuilder::new(&pattern) + .case_insensitive(!o.match_case) + .size_limit(REGEX_LIMIT) + .dfa_size_limit(REGEX_LIMIT) + .nest_limit(64) + .build() + .map_err(|e| EngineError::Param(match e { + regex::Error::CompiledTooBig(_) => "that pattern is too large; make it simpler".to_string(), + regex::Error::Syntax(s) => format!("that isn't a pattern: {}", s.lines().last().unwrap_or("").trim()), + _ => "that isn't a pattern".to_string(), + }))?; + Ok(Needle::Text { re, expand: o.regex }) +} + +fn rgb8(c: Rgba) -> [u8; 3] { + let c = c.sanitized(); + let b = |v: f32| (v * 255.0).round() as u8; + [b(c.r), b(c.g), b(c.b)] +} + +fn font_key(f: &str) -> String { + f.trim().to_lowercase() +} + +fn opt_id(p: &Value, key: &str) -> Result { + opt_u64(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required: a Library id"))) +} + +impl Query { + /// The query in `p` (`find.search`'s params), checked against the document. + pub fn from_params(s: &Session, p: &Value) -> Result { + let kind = str_req(p, "kind")?; + let kind = Kind::from_key(kind).ok_or_else(|| EngineError::Param(format!("unknown kind '{kind}' (text, font, color, symbol, sound or bitmap)")))?; + let needle = match kind { + Kind::Text => { + let o = TextOptions { match_case: opt_bool(p, "match_case")?.unwrap_or(false), whole_word: opt_bool(p, "whole_word")?.unwrap_or(false), regex: opt_bool(p, "regex")?.unwrap_or(false) }; + text_needle(str_req(p, "text")?, o)? + } + Kind::Font => { + let f = font_key(str_req(p, "font")?); + if f.is_empty() || f.chars().count() > 256 { + return Err(EngineError::Param("'font' must be a family name".into())); + } + Needle::Font(f) + } + Kind::Color => Needle::Color(rgb8(opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' is required: #rrggbb".into()))?)), + Kind::Symbol => { + let id = SymbolId(opt_id(p, "symbol")?); + s.doc.symbol(id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + Needle::Symbol(id) + } + Kind::Sound => { + let id = SoundId(opt_id(p, "sound")?); + s.doc.sound(id).ok_or_else(|| EngineError::State(format!("no sound with id {}", id.0)))?; + Needle::Sound(id) + } + Kind::Bitmap => { + let id = BitmapId(opt_id(p, "bitmap")?); + s.doc.bitmap(id).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", id.0)))?; + Needle::Bitmap(id) + } + }; + let within = match p.get("in") { + None | Some(Value::Null) => Within::default(), + Some(Value::Array(list)) => { + let mut w = Within { text: false, labels: false, layers: false, instances: false, scripts: false, fills: false, strokes: false, text_color: false }; + for v in list.iter().take(16) { + match (kind, v.as_str()) { + (Kind::Text, Some("text")) => w.text = true, + (Kind::Text, Some("labels")) => w.labels = true, + (Kind::Text, Some("layers")) => w.layers = true, + (Kind::Text, Some("instances")) => w.instances = true, + (Kind::Text, Some("scripts")) => w.scripts = true, + (Kind::Color, Some("fills")) => w.fills = true, + (Kind::Color, Some("strokes")) => w.strokes = true, + (Kind::Color, Some("text")) => w.text_color = true, + (_, other) => return Err(EngineError::Param(format!("'in' can't hold {}", other.map_or_else(|| v.to_string(), |o| format!("'{o}'"))))), + } + } + w + } + Some(_) => return Err(EngineError::Param("'in' must be a list".into())), + }; + let scope = match opt_str(p, "scope")? { + None | Some("scene") => Scope::Scene, + Some("document") => Scope::Document, + Some(o) => return Err(EngineError::Param(format!("'scope' is scene or document, not '{o}'"))), + }; + Ok(Query { needle, within, scope }) + } + + pub fn kind(&self) -> Kind { + match self.needle { + Needle::Text { .. } => Kind::Text, + Needle::Font(_) => Kind::Font, + Needle::Color(_) => Kind::Color, + Needle::Symbol(_) => Kind::Symbol, + Needle::Sound(_) => Kind::Sound, + Needle::Bitmap(_) => Kind::Bitmap, + } + } +} + +/// One place a search found. +#[derive(Clone, Debug, PartialEq)] +pub struct Hit { + pub at: Where, + pub layer: LayerId, + /// The keyframe's first frame; `None` for a layer's name. + pub frame: Option, + pub element: Option, + pub field: Field, + /// A text match's characters in the field (`start..end`); `0..0` otherwise. + pub start: usize, + pub end: usize, + /// What was found: the matched text, the font, the colour (#rrggbb), or the item's name. + pub found: String, + /// The text around a match, on one line, for lists (empty for other kinds). + pub context: String, +} + +impl Hit { + pub fn to_json(&self, doc: &Document, kind: Kind) -> Value { + let mut v = json!({ + "kind": kind.key(), "field": self.field.key(), "layer": self.layer.0, "frame": self.frame, + "element": self.element.map(|e| e.0), "start": self.start, "end": self.end, "found": self.found, "context": self.context, + }); + match self.at { + Where::Scene(i) => { + v["scene"] = json!(i); + v["scene_name"] = json!(doc.scenes.get(i).map(|s| s.name.as_str())); + } + Where::Symbol(id) => { + v["symbol"] = json!(id.0); + v["symbol_name"] = json!(doc.symbol(id).map(|s| s.name.as_str())); + } + } + v["layer_name"] = json!(timeline_of(doc, self.at).and_then(|t| t.layer(self.layer)).map(|l| l.name.as_str())); + v + } + + /// The hit `v` names (as [`Hit::to_json`] wrote it), without what was found. + fn target(v: &Value) -> Result { + let bad = || EngineError::Param("'at' must be a hit as find.search returns it".into()); + if !v.is_object() { + return Err(bad()); + } + let at = match (opt_u64(v, "scene")?, opt_u64(v, "symbol")?) { + (Some(i), None) => Where::Scene(usize::try_from(i).map_err(|_| bad())?), + (None, Some(id)) => Where::Symbol(SymbolId(id)), + _ => return Err(bad()), + }; + let field = opt_str(v, "field")?.and_then(Field::from_key).ok_or_else(bad)?; + let layer = LayerId(opt_u64(v, "layer")?.ok_or_else(bad)?); + Ok(Target { at, layer, frame: opt_u32(v, "frame")?, element: opt_u64(v, "element")?.map(ElementId), field, start: opt_u64(v, "start")?.and_then(|n| usize::try_from(n).ok()).unwrap_or(0) }) + } +} + +/// A hit's place (what `find.replace`'s `at` names). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Target { + at: Where, + layer: LayerId, + frame: Option, + element: Option, + field: Field, + start: usize, +} + +impl Target { + fn is(&self, h: &Hit) -> bool { + self.at == h.at && self.layer == h.layer && self.frame == h.frame && self.element == h.element && self.field == h.field && (!matches!(h.field, Field::Text | Field::Label | Field::LayerName | Field::InstanceName | Field::Script) || self.start == h.start) + } +} + +/// The timeline `at` names. +pub fn timeline_of(doc: &Document, at: Where) -> Option<&Timeline> { + match at { + Where::Scene(i) => doc.scenes.get(i).map(|s| &s.timeline), + Where::Symbol(id) => doc.symbol(id).map(|s| &s.timeline), + } +} + +fn timeline_of_mut(doc: &mut Document, at: Where) -> Option<&mut Timeline> { + match at { + Where::Scene(i) => doc.scenes.get_mut(i).map(|s| &mut Arc::make_mut(s).timeline), + Where::Symbol(id) => doc.library.iter_mut().find(|s| s.id == id).map(|s| &mut Arc::make_mut(s).timeline), + } +} + +/// The symbols an instance on `tl` shows (directly). +fn used_symbols(tl: &Timeline, mut f: impl FnMut(SymbolId)) { + for k in tl.layers.iter().flat_map(|l| l.keyframes.iter()) { + for e in &k.elements { + if let ElementKind::Symbol { symbol, .. } = e.kind { + f(symbol); + } + } + } +} + +/// Every symbol reachable from `roots` through instances (the roots included), however deep. +pub fn reachable(doc: &Document, roots: impl IntoIterator) -> HashSet { + let by_id: HashMap = doc.library.iter().map(|s| (s.id, &**s)).collect(); + let mut seen = HashSet::new(); + let mut todo: Vec = roots.into_iter().collect(); + while let Some(id) = todo.pop() { + if !seen.insert(id) { + continue; + } + if let Some(sym) = by_id.get(&id) { + used_symbols(&sym.timeline, |u| { + if !seen.contains(&u) { + todo.push(u); + } + }); + } + } + seen +} + +/// The timelines a scope covers, in order: scenes first, then symbols in Library order. +pub fn timelines(doc: &Document, scene: usize, scope: Scope) -> Vec { + match scope { + Scope::Document => (0..doc.scenes.len()).map(Where::Scene).chain(doc.library.iter().map(|s| Where::Symbol(s.id))).collect(), + Scope::Scene => { + let mut used = Vec::new(); + used_symbols(doc.timeline(scene), |s| used.push(s)); + let inside = reachable(doc, used); + std::iter::once(Where::Scene(scene.min(doc.scenes.len().saturating_sub(1)))).chain(doc.library.iter().filter(|s| inside.contains(&s.id)).map(|s| Where::Symbol(s.id))).collect() + } + } +} + +/// Non-empty matches of `re` in `text`: byte range and character start/end. +fn text_matches<'a>(re: &'a Regex, text: &'a str) -> impl Iterator + 'a { + let (mut byte, mut ch) = (0usize, 0usize); + re.find_iter(text).filter(|m| !m.is_empty()).map(move |m| { + ch += text.get(byte..m.start()).map_or(0, |t| t.chars().count()); + let len = m.as_str().chars().count(); + byte = m.end(); + let out = (m.start(), m.end(), ch, ch + len); + ch += len; + out + }) +} + +/// At most `n` characters of `t`, with "…" when there were more. +fn clip(t: &str, n: usize) -> String { + let mut out: String = t.chars().take(n).collect(); + if out.len() < t.len() { + out.push('…'); + } + out +} + +/// `text` around bytes `a..b`, on one line (the match itself clipped too). +fn context(text: &str, a: usize, b: usize) -> String { + let mut before: Vec = text.get(..a).unwrap_or("").chars().rev().take(CONTEXT + 1).collect(); + let cut = before.len() > CONTEXT; + before.truncate(CONTEXT); + let mut out: String = if cut { "…".into() } else { String::new() }; + out.extend(before.into_iter().rev()); + out.push_str(&clip(text.get(a..b).unwrap_or(""), 4 * CONTEXT)); + out.push_str(&clip(text.get(b..).unwrap_or(""), CONTEXT)); + out.replace(['\n', '\r', '\t'], " ") +} + +/// Collects hits as they are found, up to [`MAX_HITS`]. +struct Found<'a> { + q: &'a Query, + doc: &'a Document, + hits: Vec, + truncated: bool, +} + +impl Found<'_> { + fn full(&mut self) -> bool { + if self.hits.len() >= MAX_HITS { + self.truncated = true; + } + self.truncated + } + + fn push(&mut self, h: Hit) { + if !self.full() { + self.hits.push(h); + } + } + + fn text(&mut self, place: (Where, LayerId, Option, Option), field: Field, text: &str) { + let q = self.q; + let Needle::Text { re, .. } = &q.needle else { return }; + for (a, b, ca, cb) in text_matches(re, text) { + if self.full() { + return; + } + self.hits.push(Hit { at: place.0, layer: place.1, frame: place.2, element: place.3, field, start: ca, end: cb, found: clip(text.get(a..b).unwrap_or(""), 4 * CONTEXT), context: context(text, a, b) }); + } + } + + fn timeline(&mut self, at: Where, tl: &Timeline) { + let q = self.q; + let w = q.within; + for l in &tl.layers { + if self.full() { + return; + } + if w.layers && matches!(q.needle, Needle::Text { .. }) { + self.text((at, l.id, None, None), Field::LayerName, &l.name); + } + for k in &l.keyframes { + let f = Some(k.start); + let place = |e: Option| Hit { at, layer: l.id, frame: f, element: e, field: Field::Text, start: 0, end: 0, found: String::new(), context: String::new() }; + match &q.needle { + Needle::Text { .. } => { + if w.labels { + self.text((at, l.id, f, None), Field::Label, &k.label); + } + if w.scripts + && let Some(FrameScript::Source(src)) = &k.script + { + self.text((at, l.id, f, None), Field::Script, &src.text); + } + } + Needle::Sound(id) if k.sound.as_ref().is_some_and(|fs| fs.sound == *id) => { + let found = self.doc.sound(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Sound, found, ..place(None) }); + } + _ => {} + } + for e in &k.elements { + if self.full() { + return; + } + let place = (at, l.id, f, Some(e.id)); + match (&q.needle, &e.kind) { + (Needle::Text { .. }, kind) => { + if w.instances { + self.text(place, Field::InstanceName, &e.name); + } + if w.text + && let ElementKind::Text(t) = kind + { + self.text(place, Field::Text, &t.text); + } + } + (Needle::Font(f), ElementKind::Text(t)) if font_key(&t.font) == *f => self.push(Hit { field: Field::Font, found: t.font.clone(), ..hit_at(place) }), + (Needle::Color(c), ElementKind::Shape(sh)) => { + if w.fills && sh.fill.as_ref().is_some_and(|p| paint_has(p, *c)) { + self.push(Hit { field: Field::Fill, found: hex(*c), ..hit_at(place) }); + } + if w.strokes && sh.stroke.as_ref().is_some_and(|s| rgb8(s.color) == *c) { + self.push(Hit { field: Field::Stroke, found: hex(*c), ..hit_at(place) }); + } + } + (Needle::Color(c), ElementKind::Text(t)) if w.text_color && rgb8(t.color) == *c => self.push(Hit { field: Field::TextColor, found: hex(*c), ..hit_at(place) }), + (Needle::Symbol(id), ElementKind::Symbol { symbol, .. }) if symbol == id => { + let found = self.doc.symbol(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Instance, found, ..hit_at(place) }); + } + (Needle::Bitmap(id), ElementKind::Shape(sh)) if matches!(&sh.fill, Some(Paint::Bitmap { bitmap, .. }) if bitmap == id) => { + let found = self.doc.bitmap(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Bitmap, found, ..hit_at(place) }); + } + _ => {} + } + } + } + } + } +} + +fn hit_at(place: (Where, LayerId, Option, Option)) -> Hit { + Hit { at: place.0, layer: place.1, frame: place.2, element: place.3, field: Field::Text, start: 0, end: 0, found: String::new(), context: String::new() } +} + +fn hex(c: [u8; 3]) -> String { + format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) +} + +fn paint_has(p: &Paint, c: [u8; 3]) -> bool { + match p { + Paint::Solid(x) => rgb8(*x) == c, + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => stops.iter().any(|s| rgb8(s.color) == c), + Paint::Bitmap { .. } => false, + } +} + +/// Every hit of `q` in its scope (from scene `scene`), in order, and whether the list stopped at +/// [`MAX_HITS`]. +pub fn search(doc: &Document, scene: usize, q: &Query) -> (Vec, bool) { + let mut f = Found { q, doc, hits: Vec::new(), truncated: false }; + for at in timelines(doc, scene, q.scope) { + if let Some(tl) = timeline_of(doc, at) { + f.timeline(at, tl); + } + if f.truncated { + break; + } + } + (f.hits, f.truncated) +} + +fn search_cmd(s: &mut Session, p: &Value) -> Result { + let q = Query::from_params(s, p)?; + let offset = opt_u64(p, "offset")?.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)); + let limit = opt_u64(p, "limit")?.map_or(DEFAULT_LIMIT, |n| usize::try_from(n).unwrap_or(MAX_LIMIT)).min(MAX_LIMIT); + let (hits, truncated) = search(&s.doc, s.scene, &q); + let kind = q.kind(); + let page: Vec = hits.iter().skip(offset).take(limit).map(|h| h.to_json(&s.doc, kind)).collect(); + Ok(json!({"hits": page, "total": hits.len(), "offset": offset, "truncated": truncated})) +} + +// ----- replace ----------------------------------------------------------------------------- + +/// What hits are replaced with. +#[derive(Clone, Debug)] +pub enum With { + Text(String), + Font(String), + Color(Rgba), + Symbol(SymbolId), + Sound(SoundId), + Bitmap(BitmapId), +} + +impl With { + fn from_params(s: &Session, kind: Kind, p: &Value) -> Result { + let v = p.get("with").ok_or_else(|| EngineError::Param("param 'with' is required: what to replace with".into()))?; + let id = || v.as_u64().ok_or_else(|| EngineError::Param("'with' must be a Library id".into())); + Ok(match kind { + Kind::Text => { + let t = v.as_str().ok_or_else(|| EngineError::Param("'with' must be text".into()))?; + if t.chars().count() > MAX_QUERY_CHARS { + return Err(EngineError::Param(format!("what to replace with is at most {MAX_QUERY_CHARS} characters"))); + } + With::Text(t.to_string()) + } + Kind::Font => { + let f = v.as_str().map(str::trim).filter(|f| !f.is_empty() && f.chars().count() <= 256).ok_or_else(|| EngineError::Param("'with' must be a font family".into()))?; + With::Font(f.to_string()) + } + Kind::Color => With::Color(opt_color(p, "with")?.ok_or_else(|| EngineError::Param("'with' must be a colour: #rrggbb".into()))?), + Kind::Symbol => { + let to = SymbolId(id()?); + s.doc.symbol(to).ok_or_else(|| EngineError::State(format!("no symbol with id {}", to.0)))?; + With::Symbol(to) + } + Kind::Sound => { + let to = SoundId(id()?); + s.doc.sound(to).ok_or_else(|| EngineError::State(format!("no sound with id {}", to.0)))?; + With::Sound(to) + } + Kind::Bitmap => { + let to = BitmapId(id()?); + s.doc.bitmap(to).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", to.0)))?; + With::Bitmap(to) + } + }) + } +} + +/// `text` with the matches of `re` replaced by `with` (only the one starting at character `only` +/// when given); `None` when nothing matched. +fn replace_text(re: &Regex, expand: bool, text: &str, with: &str, only: Option) -> Option { + let mut out = String::with_capacity(text.len()); + // `last`: copied up to here; `seen`, `ch`: characters counted up to byte `seen`. + let (mut last, mut seen, mut ch, mut any) = (0usize, 0usize, 0usize, false); + for caps in re.captures_iter(text) { + let Some(m) = caps.get(0) else { continue }; + if m.is_empty() { + continue; + } + ch += text.get(seen..m.start()).map_or(0, |t| t.chars().count()); + let this = ch; + ch += m.as_str().chars().count(); + seen = m.end(); + if only.is_some_and(|o| o != this) { + continue; + } + out.push_str(text.get(last..m.start()).unwrap_or("")); + if expand { + caps.expand(with, &mut out); + } else { + out.push_str(with); + } + last = m.end(); + any = true; + if only.is_some() { + break; + } + } + if !any { + return None; + } + out.push_str(text.get(last..).unwrap_or("")); + Some(out) +} + +/// The places Replace All would change (each field once). +pub fn places(hits: &[Hit]) -> usize { + let mut seen = HashSet::new(); + hits.iter().filter(|h| seen.insert((h.at, h.layer, h.frame, h.element, h.field))).count() +} + +/// How many places `find.replace` with `p` would change (for its confirmation); `None` when +/// the params don't make a query or name one hit. +pub(crate) fn replace_count(s: &Session, p: &Value) -> Option { + if p.get("at").is_some_and(|v| !v.is_null()) { + return None; + } + let q = Query::from_params(s, p).ok()?; + Some(places(&search(&s.doc, s.scene, &q).0)) +} + +/// What a replacement did. +#[derive(Default)] +struct Tally { + replaced: usize, + skipped: usize, + notes: Vec, +} + +impl Tally { + fn note(&mut self, n: String) { + if !self.notes.contains(&n) && self.notes.len() < 16 { + self.notes.push(n); + } + } +} + +fn replace_cmd(s: &mut Session, p: &Value) -> Result { + let q = Query::from_params(s, p)?; + let with = With::from_params(s, q.kind(), p)?; + let only = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some(Hit::target(v)?), + }; + let (mut hits, truncated) = search(&s.doc, s.scene, &q); + if let Some(t) = &only { + hits.retain(|h| t.is(h)); + if hits.is_empty() { + return Err(EngineError::State("that match isn't there any more; search again".into())); + } + } + if hits.is_empty() { + return Err(EngineError::State("nothing matches".into())); + } + // A symbol can't end up inside itself: no instance of `to` in `to`, or in a symbol it uses. + let blocked: HashSet = match with { + With::Symbol(to) => reachable(&s.doc, [to]), + _ => HashSet::new(), + }; + let sizes: HashMap = s.doc.bitmaps.iter().map(|b| (b.id, (b.name.clone(), b.width as f32, b.height as f32))).collect(); + let mut tally = Tally::default(); + let mut by_tl: Vec<(Where, Vec)> = Vec::new(); + for h in hits { + match by_tl.last_mut() { + Some((at, list)) if *at == h.at => list.push(h), + _ => by_tl.push((h.at, vec![h])), + } + } + for (at, list) in by_tl { + if let Where::Symbol(id) = at + && blocked.contains(&id) + { + tally.skipped += places(&list); + tally.note("an instance inside the symbol it would show (or one it uses) was left as it is: a symbol can't contain itself".into()); + continue; + } + let Some(tl) = timeline_of_mut(&mut s.doc, at) else { continue }; + apply(tl, &list, &q, &with, only.as_ref().map(|t| t.start), &sizes, &mut tally)?; + } + if tally.replaced == 0 { + return Err(EngineError::State(tally.notes.first().cloned().unwrap_or_else(|| "nothing could be replaced".into()))); + } + // The fill swatch and the text style keep what they were: replacing edits the document only. + Ok(json!({"replaced": tally.replaced, "skipped": tally.skipped, "notes": tally.notes, "truncated": truncated})) +} + +/// Replaces `hits` (all on `tl`) in place, un-sharing only the layers, keyframes and elements +/// they are on. `only`: the one text match to replace (Replace), by its first character. +fn apply(tl: &mut Timeline, hits: &[Hit], q: &Query, with: &With, only: Option, sizes: &HashMap, t: &mut Tally) -> Result<()> { + let layers: HashSet = hits.iter().map(|h| h.layer).collect(); + let (re, expand) = match &q.needle { + Needle::Text { re, expand } => (Some(re), *expand), + _ => (None, false), + }; + let new_text = |text: &str| -> Option { + match (re, with) { + (Some(re), With::Text(w)) => replace_text(re, expand, text, w, only), + _ => None, + } + }; + for l in tl.layers.iter_mut().filter(|l| layers.contains(&l.id)) { + let lh: Vec<&Hit> = hits.iter().filter(|h| h.layer == l.id).collect(); + let l = Arc::make_mut(l); + if lh.iter().any(|h| h.field == Field::LayerName) { + match new_text(&l.name).map(|n| n.chars().take(128).collect::()) { + Some(n) if !n.trim().is_empty() => { + l.name = n; + t.replaced += 1; + } + _ => { + t.skipped += 1; + t.note("a layer name can't be empty".into()); + } + } + } + let frames: HashSet = lh.iter().filter_map(|h| h.frame).collect(); + for k in l.keyframes.iter_mut().filter(|k| frames.contains(&k.start)) { + let kh: Vec<&&Hit> = lh.iter().filter(|h| h.frame == Some(k.start)).collect(); + let k = Arc::make_mut(k); + let has = |f: Field| kh.iter().any(|h| h.field == f && h.element.is_none()); + if has(Field::Label) + && let Some(n) = new_text(&k.label) + { + k.label = n.chars().take(256).collect(); + t.replaced += 1; + } + if has(Field::Script) + && let Some(FrameScript::Source(src)) = &k.script + && let Some(n) = new_text(&src.text) + { + if n.len() > anicraft_doc::actions::MAX_SOURCE_BYTES { + t.skipped += 1; + t.note("a script would be too long".into()); + } else { + k.script = Some(FrameScript::Source(Arc::new(SourceScript::new(src.language, n)))); + t.replaced += 1; + } + } + if has(Field::Sound) + && let (Some(fs), With::Sound(to)) = (k.sound.as_mut(), with) + { + fs.sound = *to; + t.replaced += 1; + } + let ids: HashSet = kh.iter().filter_map(|h| h.element).collect(); + for e in k.elements.iter_mut().filter(|e| ids.contains(&e.id)) { + let fields: Vec = kh.iter().filter(|h| h.element == Some(e.id)).map(|h| h.field).collect(); + let e = Arc::make_mut(e); + for f in Field::ALL.into_iter().filter(|f| fields.contains(f)) { + apply_element(e, f, q, with, &new_text, sizes, t)?; + } + } + } + } + Ok(()) +} + +/// Replaces field `f` of element `e`. +fn apply_element(e: &mut anicraft_doc::Element, f: Field, q: &Query, with: &With, new_text: &dyn Fn(&str) -> Option, sizes: &HashMap, t: &mut Tally) -> Result<()> { + match (f, &mut e.kind, with) { + (Field::InstanceName, _, _) => { + if let Some(n) = new_text(&e.name) { + e.name = n.chars().take(128).collect(); + t.replaced += 1; + } + } + (Field::Text, ElementKind::Text(tb), _) => { + if let Some(n) = new_text(&tb.text) { + if n.trim().is_empty() { + t.skipped += 1; + t.note("a text field can't be left empty (delete it instead)".into()); + } else { + let (block, note) = crate::cmds_text::lay_out(&n, &crate::cmds_text::style_of(tb), tb.width)?; + t.note_opt(note); + *tb = Arc::new(block); + t.replaced += 1; + } + } + } + (Field::Font, ElementKind::Text(tb), With::Font(family)) => { + let style = crate::cmds_text::TextStyle { font: family.clone(), ..crate::cmds_text::style_of(tb) }; + let (block, note) = crate::cmds_text::lay_out(&tb.text, &style, tb.width)?; + t.note_opt(note); + *tb = Arc::new(block); + t.replaced += 1; + } + (Field::TextColor, ElementKind::Text(tb), With::Color(c)) => { + let tb = Arc::make_mut(tb); + tb.color = Rgba { a: tb.color.a, ..*c }; + t.replaced += 1; + } + (Field::Fill | Field::Stroke, ElementKind::Shape(sh), With::Color(c)) => { + let Needle::Color(from) = q.needle else { return Ok(()) }; + let recolour = |x: &mut Rgba| { + if rgb8(*x) == from { + *x = Rgba { a: x.a, ..*c }; + } + }; + if f == Field::Fill { + match &mut sh.fill { + Some(Paint::Solid(x)) => recolour(x), + Some(Paint::Linear { stops, .. } | Paint::Radial { stops, .. }) => stops.iter_mut().for_each(|s| recolour(&mut s.color)), + _ => {} + } + } else if let Some(st) = &mut sh.stroke { + recolour(&mut st.color); + } + t.replaced += 1; + } + (Field::Instance, ElementKind::Symbol { symbol, .. }, With::Symbol(to)) => { + *symbol = *to; + t.replaced += 1; + } + (Field::Bitmap, ElementKind::Shape(_), With::Bitmap(to)) => { + t.replaced += usize::from(crate::cmds_library::swap_bitmap_of(e, *to, sizes)); + } + _ => {} + } + Ok(()) +} + +impl Tally { + fn note_opt(&mut self, n: Option) { + if let Some(n) = n { + self.note(n); + } + } +} + +// ----- go to ------------------------------------------------------------------------------- + +/// One instance opened in place on the way to a symbol: on `layer`, at the keyframe starting at +/// `frame`, the instance `element`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Step { + pub layer: LayerId, + pub frame: u32, + pub element: ElementId, +} + +impl Step { + pub fn to_json(&self) -> Value { + json!({"layer": self.layer.0, "frame": self.frame, "element": self.element.0}) + } +} + +/// Where a scene or symbol timeline holding layer `id` is. +pub fn locate_layer(doc: &Document, id: LayerId) -> Option { + doc.scenes.iter().position(|s| s.timeline.layer(id).is_some()).map(Where::Scene).or_else(|| doc.library.iter().find(|s| s.timeline.layer(id).is_some()).map(|s| Where::Symbol(s.id))) +} + +/// The shortest chain of instances from scene `scene`'s timeline to symbol `target` (each opened +/// in place in turn), when an instance in that scene leads to it. +pub fn route(doc: &Document, scene: usize, target: SymbolId) -> Option> { + let by_id: HashMap = doc.library.iter().map(|s| (s.id, &**s)).collect(); + let mut seen: HashSet = HashSet::new(); + let mut todo: VecDeque<(&Timeline, Vec)> = VecDeque::from([(doc.timeline(scene), Vec::new())]); + while let Some((tl, path)) = todo.pop_front() { + if path.len() >= MAX_ROUTE { + continue; + } + for l in &tl.layers { + for k in &l.keyframes { + for e in &k.elements { + let ElementKind::Symbol { symbol, .. } = e.kind else { continue }; + let mut next = path.clone(); + next.push(Step { layer: l.id, frame: k.start, element: e.id }); + if symbol == target { + return Some(next); + } + if seen.insert(symbol) + && let Some(sym) = by_id.get(&symbol) + { + todo.push_back((&sym.timeline, next)); + } + } + } + } + } + None +} + +fn steps_of(p: &Value) -> Result>> { + let Some(list) = p.get("path").filter(|v| !v.is_null()) else { return Ok(None) }; + let list = list.as_array().ok_or_else(|| EngineError::Param("'path' must be a list of {layer, frame, element}".into()))?; + if list.len() > MAX_ROUTE { + return Err(EngineError::Param(format!("'path' opens at most {MAX_ROUTE} instances"))); + } + let bad = || EngineError::Param("each step of 'path' is {layer, frame, element}".into()); + list.iter() + .map(|v| Ok(Step { layer: LayerId(opt_u64(v, "layer")?.ok_or_else(bad)?), frame: opt_u32(v, "frame")?.ok_or_else(bad)?, element: ElementId(opt_u64(v, "element")?.ok_or_else(bad)?) })) + .collect::>>() + .map(Some) +} + +/// Opens each instance of `steps` in place, from the timeline being edited. False when one +/// can't be opened (a hidden or locked layer, an instance that isn't there). +fn walk(s: &mut Session, steps: &[Step]) -> bool { + for st in steps { + if s.timeline().layer(st.layer).is_none() { + return false; + } + s.layer = st.layer; + s.frame = st.frame.min(crate::MAX_FRAME); + s.selection.clear(); + if crate::editing::edit(s, &json!({"id": st.element.0})).is_err() { + return false; + } + } + true +} + +fn goto_cmd(s: &mut Session, p: &Value) -> Result { + let layer = opt_u64(p, "layer")?.map(LayerId); + let frame = opt_u32(p, "frame")?; + let element = opt_u64(p, "element")?.map(ElementId); + let scene = match opt_u64(p, "scene")? { + Some(i) => Some(usize::try_from(i).ok().filter(|i| *i < s.doc.scenes.len()).ok_or_else(|| EngineError::State(format!("there is no scene {i}")))?), + None => None, + }; + let symbol = opt_u64(p, "symbol")?.map(SymbolId); + if let Some(id) = symbol + && s.doc.symbol(id).is_none() + { + return Err(EngineError::State(format!("no symbol with id {}", id.0))); + } + let steps = steps_of(p)?; + if steps.is_some() && layer.is_none() { + return Err(EngineError::Param("a 'path' goes to a 'layer': name it".into())); + } + // Where to end up: the layer's timeline, else what the params name. + let target = match layer { + Some(l) => locate_layer(&s.doc, l).ok_or_else(|| EngineError::State(format!("no layer with id {}", l.0)))?, + None => match (symbol, scene) { + (Some(id), _) => Where::Symbol(id), + (None, Some(i)) => Where::Scene(i), + (None, None) => return Err(EngineError::Param("name where to go: {layer}, {scene} or {symbol}".into())), + }, + }; + let here = s.scene; + // Open symbols close first (ADR 0045). + s.exit_all(); + match target { + Where::Scene(i) => crate::cmds_scene::open_scene(s, i), + Where::Symbol(t) => { + let opened = match &steps { + // Through the instances named, from the scene (or from `symbol`, opened alone). + Some(steps) => { + match symbol { + Some(b) => { + crate::editing::edit(s, &json!({"symbol": b.0}))?; + } + None => crate::cmds_scene::open_scene(s, scene.unwrap_or(here)), + } + walk(s, steps) && s.editing_symbol() == Some(t) + } + // In place through the first instance that leads there: in this scene, else another. + None => { + let order = std::iter::once(scene.unwrap_or(here)).chain(0..s.doc.scenes.len()); + let found = order.into_iter().find_map(|i| route(&s.doc, i, t).map(|r| (i, r))); + match found { + Some((i, r)) => { + crate::cmds_scene::open_scene(s, i); + walk(s, &r) && s.editing_symbol() == Some(t) + } + None => false, + } + } + }; + if !opened { + // Alone, from the Library (no instance leads there, or one can't be opened). + s.exit_all(); + crate::editing::edit(s, &json!({"symbol": t.0}))?; + } + } + } + if let Some(l) = layer.filter(|l| s.timeline().layer(*l).is_some()) { + s.layer = l; + } + if let Some(f) = frame { + s.frame = f.min(crate::MAX_FRAME); + } + s.selection = match element { + Some(e) => Selection::only(s.layer, [e]), + None => Selection::default(), + }; + s.revision += 1; + s.dl_cache.replace(None); + s.fix_selection(); + let mut v = crate::editing::editing_json(s); + v["scene"] = json!(s.scene); + Ok(v) +} + +#[cfg(test)] +#[path = "find_tests.rs"] +pub(crate) mod tests; diff --git a/crates/engine/src/find_tests.rs b/crates/engine/src/find_tests.rs new file mode 100644 index 00000000..c603f6c4 --- /dev/null +++ b/crates/engine/src/find_tests.rs @@ -0,0 +1,456 @@ +//! Find and Replace end to end (ADR 0058): each kind, scopes, text options and bounded patterns, +//! Replace and Replace All as one undo step, the confirmation, and going to what was found +//! (symbols opened in place through the instances that lead to them). + +use super::*; +use anicraft_doc::{ColorEffect, Document, Element, ElementKind, FrameSound, GradientStop, Keyframe, Layer, LayerId, LoopMode, Paint, Rgba, Scene, Shape, SourceScript, Symbol, SymbolKind, TextAlign, TextBlock}; +use anicraft_geom::{Affine, Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +/// Builds documents by hand, ids from the document. +pub(crate) struct Build { + pub doc: Document, +} + +impl Build { + pub fn new() -> Build { + let mut doc = Document::default(); + doc.scenes.clear(); + doc.next_id = 1; + Build { doc } + } + pub fn id(&mut self) -> u64 { + self.doc.alloc_id() + } + pub fn text(&mut self, t: &str, color: Rgba) -> Element { + let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0 }; + Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) } + } + pub fn rect(&mut self, fill: Paint, stroke: Option) -> Element { + let mut sh = Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), fill); + if let Some(c) = stroke { + sh = sh.with_stroke(c, 2.0); + } + Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(sh) } + } + pub fn instance(&mut self, symbol: SymbolId, name: &str) -> Element { + Element { + id: ElementId(self.id()), + name: name.into(), + transform: Affine::translate(100.0, 50.0), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + } + } + /// A layer with keyframes `(start, duration, label, elements)`. + pub fn layer(&mut self, name: &str, keys: Vec<(u32, u32, &str, Vec)>) -> Layer { + let mut l = Layer::new(LayerId(self.id()), name); + l.keyframes = keys + .into_iter() + .map(|(start, dur, label, els)| { + let mut k = Keyframe::new(start, dur); + k.label = label.into(); + k.elements = els.into_iter().map(Arc::new).collect(); + Arc::new(k) + }) + .collect(); + l + } + pub fn scene(&mut self, name: &str, layers: Vec) { + let mut sc = Scene::new(name); + sc.timeline.layers = layers.into_iter().map(Arc::new).collect(); + self.doc.scenes.push(Arc::new(sc)); + } + pub fn symbol(&mut self, name: &str, kind: SymbolKind) -> SymbolId { + let id = SymbolId(self.id()); + self.doc.library.push(Arc::new(Symbol { id, name: name.into(), kind, linkage: None, scale_grid: None, timeline: Timeline::default() })); + id + } + pub fn fill(&mut self, id: SymbolId, layers: Vec) { + if let Some(s) = self.doc.library.iter_mut().find(|s| s.id == id) { + Arc::make_mut(s).timeline.layers = layers.into_iter().map(Arc::new).collect(); + } + } +} + +const RED: u32 = 0xff0000; + +/// Scene 1: an Art layer (a text field, a red rect with a blue stroke, an instance of Outer +/// named "hero"; a second keyframe labelled "intro hello" with more text), an Actions layer with a +/// script. Outer holds an instance of Inner and a red rect; Inner holds text. Unused holds text +/// and is in no scene. Scene 2 has a red rect. +pub(crate) fn movie() -> (Session, SymbolId, SymbolId, SymbolId) { + let mut b = Build::new(); + let outer = b.symbol("Outer", SymbolKind::MovieClip); + let inner = b.symbol("Inner", SymbolKind::Graphic); + let unused = b.symbol("Unused", SymbolKind::Graphic); + let t = b.text("Hello inside", Rgba::hex(RED)); + let l = b.layer("Inner art", vec![(0, 5, "", vec![t])]); + b.fill(inner, vec![l]); + let i = b.instance(inner, "wheel"); + let r = b.rect(Paint::Solid(Rgba::hex(RED)), None); + let l = b.layer("Outer art", vec![(0, 1, "", vec![r]), (3, 2, "", vec![i])]); + b.fill(outer, vec![l]); + let t = b.text("hello unused", Rgba::BLACK); + let l = b.layer("U", vec![(0, 1, "", vec![t])]); + b.fill(unused, vec![l]); + let t1 = b.text("Hello world", Rgba::BLACK); + let r = b.rect(Paint::Solid(Rgba::hex(RED).with_alpha(0.5)), Some(Rgba::hex(0x0000ff))); + let hero = b.instance(outer, "hero"); + let t2 = b.text("hello hello again", Rgba::hex(RED)); + let art = b.layer("Art", vec![(0, 10, "", vec![t1, r, hero]), (10, 5, "intro hello", vec![t2])]); + let mut actions = b.layer("Actions", vec![(0, 15, "", vec![])]); + if let Some(k) = actions.keyframe_mut(0) { + k.script = Some(FrameScript::Source(Arc::new(SourceScript::new(Default::default(), "stop(); // say hello")))); + } + b.scene("Scene 1", vec![actions, art]); + let r = b.rect(Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(10.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(RED) }, GradientStop { offset: 1.0, color: Rgba::WHITE }] }, None); + let l = b.layer("Back", vec![(0, 1, "", vec![r])]); + b.scene("Scene 2", vec![l]); + (Session::new(b.doc), outer, inner, unused) +} + +fn hits(s: &mut Session, p: Value) -> Vec { + run(s, "find.search", p)["hits"].as_array().cloned().unwrap_or_default() +} + +fn fields(h: &[Value]) -> Vec { + h.iter().map(|h| h["field"].as_str().unwrap_or("").to_string()).collect() +} + +#[test] +fn text_is_found_in_every_place_and_scope() { + let (mut s, ..) = movie(); + // The scene and the symbols it uses: the script, text fields (Inner's too), the label. + let h = hits(&mut s, json!({"kind": "text", "text": "hello"})); + let found: Vec<&str> = h.iter().map(|h| h["found"].as_str().unwrap()).collect(); + assert_eq!(fields(&h), ["script", "text", "label", "text", "text", "text"], "{h:?}"); + assert_eq!(found, ["hello", "Hello", "hello", "hello", "hello", "Hello"]); + assert_eq!(h[1]["scene"], 0); + assert_eq!(h[1]["layer_name"], "Art"); + assert_eq!(h[3]["start"], 0); + assert_eq!(h[4]["start"], 6); + assert_eq!(h[4]["context"], "hello hello again"); + assert_eq!(h[5]["symbol_name"], "Inner"); + // The whole document adds the unused symbol (and Scene 2 has none). + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "hello", "scope": "document"})).len(), 7); + // Case, whole words and where to look. + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "Hello", "match_case": true})).len(), 2); + assert!(hits(&mut s, json!({"kind": "text", "text": "hell", "whole_word": true})).is_empty()); + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "hell"})).len(), 6); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "hello", "in": ["labels"]}))), ["label"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "her", "in": ["instances"]}))), ["instance_name"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "art", "in": ["layers"]}))), ["layer_name", "layer_name", "layer_name"]); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "x", "in": ["fills"]})).contains("'in'")); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": ""})).contains("find")); + // Paging. + let v = run(&mut s, "find.search", json!({"kind": "text", "text": "hello", "offset": 4, "limit": 1})); + assert_eq!((v["total"].as_u64(), v["hits"].as_array().map(Vec::len)), (Some(6), Some(1))); +} + +#[test] +fn patterns_are_bounded() { + let (mut s, ..) = movie(); + let h = hits(&mut s, json!({"kind": "text", "text": r"h\w+o", "regex": true, "in": ["text"]})); + assert_eq!(h.len(), 4); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "(", "regex": true})).contains("pattern")); + // Too large to compile is refused, not run. + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "a{1000}{1000}", "regex": true})).contains("too large")); + // What backtracking engines take exponential time over runs in linear time. + let mut b = Build::new(); + let t = b.text(&format!("{}b", "a".repeat(50_000)), Rgba::BLACK); + let l = b.layer("L", vec![(0, 1, "", vec![t])]); + b.scene("S", vec![l]); + let mut big = Session::new(b.doc); + let t0 = std::time::Instant::now(); + assert_eq!(hits(&mut big, json!({"kind": "text", "text": "(a+)+$", "regex": true})).len(), 0); + assert!(t0.elapsed().as_secs_f64() < 2.0, "{:?}", t0.elapsed()); + // An empty match finds nothing, rather than every gap. + assert!(hits(&mut s, json!({"kind": "text", "text": "x*", "regex": true})).is_empty()); +} + +#[test] +fn colours_fonts_and_library_items_are_found() { + let (mut s, outer, inner, _) = movie(); + // Red: a text colour (Scene 1's second text), a fill with alpha, Outer's fill, Inner's text. + let h = hits(&mut s, json!({"kind": "color", "color": "#FF0000"})); + assert_eq!(fields(&h), ["fill", "text_color", "fill", "text_color"], "{h:?}"); + assert_eq!(fields(&hits(&mut s, json!({"kind": "color", "color": "#0000ff"}))), ["stroke"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["strokes"]}))).len(), 0); + // Gradient stops count (Scene 2). + assert_eq!(hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["fills"], "scope": "document"})).len(), 3); + assert_eq!(hits(&mut s, json!({"kind": "font", "font": " test sans "})).len(), 3); + let h = hits(&mut s, json!({"kind": "symbol", "symbol": inner.0})); + assert_eq!((h.len(), h[0]["symbol"].as_u64(), h[0]["found"].as_str()), (1, Some(outer.0), Some("Inner"))); + assert!(err(&mut s, "find.search", json!({"kind": "symbol", "symbol": 999_999})).contains("no symbol")); + assert!(err(&mut s, "find.search", json!({"kind": "sparkle"})).contains("unknown kind")); +} + +#[test] +fn sounds_and_bitmaps_are_found_and_replaced() { + let (mut s, ..) = movie(); + let wav = crate::cmds_sound::test_wav(8000, &[0.25; 800]); + let (a, b) = (anicraft_doc::SoundId(s.doc.alloc_id()), anicraft_doc::SoundId(s.doc.alloc_id())); + for (id, n) in [(a, "a.wav"), (b, "b.wav")] { + s.doc.sounds.push(Arc::new(anicraft_doc::Sound::from_data(id, n, wav.clone()).unwrap())); + } + let k = Arc::make_mut(&mut s.doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap(); + k.sound = Some(FrameSound::new(a)); + let h = hits(&mut s, json!({"kind": "sound", "sound": a.0})); + assert_eq!((fields(&h), h[0]["found"].as_str()), (vec!["sound".to_string()], Some("a.wav"))); + run(&mut s, "find.replace", json!({"kind": "sound", "sound": a.0, "with": b.0})); + assert_eq!(s.doc.timeline(0).layers[0].keyframes[0].sound.as_ref().map(|f| f.sound), Some(b)); + // A placed bitmap takes the new one's size. + let png = |w, h| anicraft_render::encode_png(w, h, &[0, 0, 255, 255].repeat((w * h) as usize)).unwrap(); + let (p, q) = (anicraft_doc::BitmapId(s.doc.alloc_id()), anicraft_doc::BitmapId(s.doc.alloc_id())); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(p, "p.png", png(3, 2)).unwrap())); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(q, "q.png", png(5, 4)).unwrap())); + run(&mut s, "library.place", json!({"bitmap": p.0})); + assert_eq!(hits(&mut s, json!({"kind": "bitmap", "bitmap": p.0})).len(), 1); + run(&mut s, "find.replace", json!({"kind": "bitmap", "bitmap": p.0, "with": q.0})); + assert!(hits(&mut s, json!({"kind": "bitmap", "bitmap": p.0})).is_empty()); + let placed = s.doc.timeline(0).layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find_map(|e| match &e.kind { + ElementKind::Shape(sh) if matches!(sh.fill, Some(Paint::Bitmap { bitmap, .. }) if bitmap == q) => Some(sh.path.bounds()), + _ => None, + }); + assert_eq!(placed.map(|r| (r.width(), r.height())), Some((5.0, 4.0))); +} + +#[test] +fn replace_all_is_one_undo_step_and_undo_brings_everything_back() { + let (mut s, ..) = movie(); + let before = s.doc.clone(); + let steps = s.history_len(); + let v = run(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "with": "bye", "in": ["text", "labels", "scripts"]})); + assert_eq!(v["replaced"], 5, "{v}"); + assert_eq!(s.history_len(), steps + 1); + let texts: Vec = s.doc.timelines().flat_map(|t| &t.layers).flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).filter_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }).collect(); + // Case-insensitive, every match; the unused symbol is outside the scene's scope. + assert_eq!(texts, ["bye world", "bye bye again", "bye inside", "hello unused"]); + assert_eq!(s.doc.timeline(0).layers[1].keyframes[1].label, "intro bye"); + match &s.doc.timeline(0).layers[0].keyframes[0].script { + Some(FrameScript::Source(src)) => assert_eq!(src.text, "stop(); // say bye"), + other => panic!("{other:?}"), + } + // A replaced text is laid out again (its outline was empty). + assert!(s.doc.timeline(0).layers[1].keyframes[1].elements.iter().any(|e| matches!(&e.kind, ElementKind::Text(t) if t.text == "bye bye again" && t.box_width != 10.0))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before); + // Nothing to replace is an error, and records nothing. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "zebra", "with": "x"})).contains("nothing")); + assert_eq!(s.history_len(), steps); +} + +#[test] +fn replace_one_changes_only_that_match() { + let (mut s, ..) = movie(); + let h = hits(&mut s, json!({"kind": "text", "text": "hello", "in": ["text"]})); + let second = h.iter().find(|h| h["start"] == 6).cloned().unwrap(); + run(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "in": ["text"], "with": "HI", "at": second})); + let t = s.doc.timeline(0).layers[1].keyframes[1].elements.iter().find_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }); + assert_eq!(t.as_deref(), Some("hello HI again")); + // The same hit again is gone. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "in": ["text"], "with": "HI", "at": second})).contains("isn't there")); + // Groups expand with a pattern, not with plain text. + run(&mut s, "find.replace", json!({"kind": "text", "text": r"(\w+) world", "regex": true, "with": "$1, $1 world"})); + let first = s.doc.timeline(0).layers[1].keyframes[0].elements.iter().find_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }); + assert_eq!(first.as_deref(), Some("Hello, Hello world")); + run(&mut s, "find.replace", json!({"kind": "text", "text": "world", "with": "$0$1"})); + assert!(s.doc.timeline(0).layers[1].keyframes[0].elements.iter().any(|e| matches!(&e.kind, ElementKind::Text(t) if t.text == "Hello, Hello $0$1"))); + // A layer name can't become empty: skipped, and said why. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "Actions", "in": ["layers"], "with": ""})).contains("can't be empty")); +} + +#[test] +fn colours_keep_alpha_and_fonts_lay_out_again() { + let (mut s, ..) = movie(); + let v = run(&mut s, "find.replace", json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "scope": "document"})); + assert_eq!(v["replaced"], 5, "{v}"); + assert!(hits(&mut s, json!({"kind": "color", "color": "#ff0000", "scope": "document"})).is_empty()); + let r = &s.doc.timeline(0).layers[1].keyframes[0].elements[1]; + match &r.kind { + ElementKind::Shape(sh) => assert_eq!(sh.fill, Some(Paint::Solid(Rgba::hex(0x00ff00).with_alpha(0.5)))), + other => panic!("{other:?}"), + } + match &s.doc.timeline(1).layers[0].keyframes[0].elements[0].kind { + ElementKind::Shape(sh) => assert!(matches!(&sh.fill, Some(Paint::Linear { stops, .. }) if stops[0].color == Rgba::hex(0x00ff00) && stops[1].color == Rgba::WHITE)), + other => panic!("{other:?}"), + } + let v = run(&mut s, "find.replace", json!({"kind": "font", "font": "Test Sans", "with": "Inter"})); + assert_eq!(v["replaced"], 3); + assert!(hits(&mut s, json!({"kind": "font", "font": "test sans"})).is_empty()); +} + +#[test] +fn a_symbol_that_would_contain_itself_is_skipped() { + let (mut s, outer, inner, unused) = movie(); + // Inner's instance is inside Outer: swapping it for Outer would nest Outer in itself. + assert!(err(&mut s, "find.replace", json!({"kind": "symbol", "symbol": inner.0, "with": outer.0})).contains("contain itself")); + // Into a symbol that doesn't hold the place: fine (and the scene's Outer becomes Unused). + let v = run(&mut s, "find.replace", json!({"kind": "symbol", "symbol": outer.0, "with": unused.0})); + assert_eq!(v["replaced"], 1); + let v = run(&mut s, "find.replace", json!({"kind": "symbol", "symbol": inner.0, "with": unused.0, "scope": "document"})); + assert_eq!(v["replaced"], 1); +} + +#[test] +fn replace_all_over_many_places_asks_first() { + let mut b = Build::new(); + let els: Vec = (0..(REPLACE_ASK + 1)).map(|_| b.rect(Paint::Solid(Rgba::hex(RED)), None)).collect(); + let l = b.layer("L", vec![(0, 1, "", els)]); + b.scene("S", vec![l]); + let mut s = Session::new(b.doc); + let p = json!({"kind": "color", "color": "#ff0000", "with": "#000000"}); + let c = s.confirmation("find.replace", &p).expect("asks above the limit"); + assert!(!c.irreversible && c.message.contains("101 places"), "{c:?}"); + // One place (Replace) never asks. + let one = hits(&mut s, p.clone()).remove(0); + let mut p1 = p.clone(); + p1["at"] = one; + assert!(s.confirmation("find.replace", &p1).is_none()); + // Undoable, so a script runs it without "confirm". + assert_eq!(run(&mut s, "find.replace", p)["replaced"], 101); +} + +#[test] +fn going_to_a_hit_opens_the_symbols_in_place_and_selects_it() { + let (mut s, outer, inner, unused) = movie(); + // Inner's text: through hero (Outer) and wheel (Inner), in place. + let h = hits(&mut s, json!({"kind": "text", "text": "inside"})).remove(0); + let v = run(&mut s, "find.goto", h.clone()); + let open: Vec = s.editing.iter().map(|l| l.symbol).collect(); + assert_eq!(open, [outer, inner], "{v}"); + assert!(s.editing.iter().all(|l| l.instance.is_some())); + assert_eq!(s.selection.id_list(), [h["element"].as_u64().unwrap()]); + assert_eq!(s.edit_view().map(|v| v.in_place), Some(true)); + // A symbol no scene uses opens alone, from the Library. + let h = hits(&mut s, json!({"kind": "text", "text": "unused", "scope": "document"})).remove(0); + run(&mut s, "find.goto", h.clone()); + assert_eq!((s.editing.len(), s.editing_symbol(), s.editing[0].instance), (1, Some(unused), None)); + assert_eq!(s.selection.id_list(), [h["element"].as_u64().unwrap()]); + // Another scene: the scene switches, the frame is the keyframe's. + let h = hits(&mut s, json!({"kind": "color", "color": "#ff0000", "scope": "document"})); + let back = h.iter().find(|h| h["scene"] == 1).cloned().unwrap(); + run(&mut s, "find.goto", back); + assert_eq!((s.scene, s.editing.len(), s.selection.len()), (1, 0, 1)); + // A label: the keyframe, nothing selected. + let h = hits(&mut s, json!({"kind": "text", "text": "intro", "scope": "document"})).remove(0); + run(&mut s, "find.goto", h); + assert_eq!((s.scene, s.frame, s.selection.len()), (0, 10, 0)); + assert_eq!(s.active_layer().map(|l| l.name.as_str()), Some("Art")); + // Going somewhere records nothing to undo. + assert!(!s.can_undo()); + assert!(err(&mut s, "find.goto", json!({})).contains("where")); + assert!(err(&mut s, "find.goto", json!({"layer": 999_999})).contains("no layer")); +} + +#[test] +fn going_to_a_symbol_behind_a_locked_layer_opens_it_alone() { + let (mut s, outer, ..) = movie(); + let art = s.doc.timeline(0).layers[1].id.0; + run(&mut s, "layer.toggle_lock", json!({"layer": art})); + let h = hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["fills"]})); + let inside = h.iter().find(|h| h["symbol"] == outer.0).cloned().unwrap(); + run(&mut s, "find.goto", inside); + assert_eq!((s.editing_symbol(), s.editing[0].instance), (Some(outer), None)); +} + +#[test] +fn search_and_replace_are_fast_on_a_large_document() { + // 40 layers × 300 keyframes (12,000 text fields and 12,000 shapes), 500 symbols. + let mut b = Build::new(); + let mut layers = Vec::new(); + for li in 0..40 { + let keys: Vec<(u32, u32, &str, Vec)> = (0..300).map(|k| (k, 1, "", vec![b.text(&format!("caption {li} {k} needle"), Rgba::BLACK), b.rect(Paint::Solid(Rgba::hex(RED)), None)])).collect(); + layers.push(b.layer(&format!("Layer {li}"), keys)); + } + b.scene("Big", layers); + for i in 0..500 { + let id = b.symbol(&format!("S{i}"), SymbolKind::Graphic); + let r = b.rect(Paint::Solid(Rgba::hex(RED)), None); + let l = b.layer("x", vec![(0, 1, "", vec![r])]); + b.fill(id, vec![l]); + } + let mut s = Session::new(b.doc); + let t0 = std::time::Instant::now(); + let n = run(&mut s, "find.search", json!({"kind": "text", "text": "needle", "whole_word": true, "limit": 1}))["total"].as_u64(); + let text = t0.elapsed(); + let t0 = std::time::Instant::now(); + let c = run(&mut s, "find.search", json!({"kind": "color", "color": "#ff0000", "scope": "document", "limit": 1}))["total"].as_u64(); + let colour = t0.elapsed(); + let t0 = std::time::Instant::now(); + let r = run(&mut s, "find.replace", json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "scope": "document"}))["replaced"].as_u64(); + let replace = t0.elapsed(); + let t0 = std::time::Instant::now(); + run(&mut s, "edit.undo", json!({})); + let undo = t0.elapsed(); + println!("find on 24,000 elements: text {text:?}, colour {colour:?}; Replace All of 12,500 colours {replace:?}, its undo {undo:?}"); + assert_eq!((n, c, r), (Some(12_000), Some(12_500), Some(12_500))); + assert!(text.as_secs_f64() < 2.0 && colour.as_secs_f64() < 2.0 && replace.as_secs_f64() < 5.0); +} + +#[test] +fn random_queries_never_panic() { + let (s0, outer, inner, _) = movie(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let atoms = ["a", "(", ")", "*", "+", "?", "|", "\\b", "\\w", "[", "]", "{2,}", ".", "^", "$", "hello", "é", "\\", "$1", "${x}", "\n"]; + let kinds = ["text", "font", "color", "symbol", "sound", "bitmap", "x"]; + let mut s = s0; + for _ in 0..400 { + let pat: String = (0..(next() % 6)).map(|_| atoms[(next() % atoms.len() as u64) as usize]).collect(); + let with: String = (0..(next() % 4)).map(|_| atoms[(next() % atoms.len() as u64) as usize]).collect(); + let kind = kinds[(next() % kinds.len() as u64) as usize]; + let id = [outer.0, inner.0, next()][(next() % 3) as usize]; + let p = json!({"kind": kind, "text": pat, "regex": next() % 2 == 0, "whole_word": next() % 3 == 0, "match_case": next() % 2 == 0, "font": pat, "color": format!("#{:06x}", next() % 0xffffff), "symbol": id, "sound": id, "bitmap": id, "with": if next() % 2 == 0 { json!(with) } else { json!(id) }, "scope": if next() % 2 == 0 { "scene" } else { "document" }}); + if let Ok(v) = s.execute("find.search", &p) + && let Some(h) = v["hits"].as_array().and_then(|h| h.first()) + { + let _ = s.execute("find.goto", h); + let mut one = p.clone(); + one["at"] = h.clone(); + let _ = s.execute("find.replace", &one); + } + let _ = s.execute("find.replace", &p); + if next() % 7 == 0 { + let _ = s.execute("edit.undo", &json!({})); + } + } + let _ = anicraft_render::render_frame(&s.doc, 0, 0.1); +} + +#[test] +fn the_new_namespaces_are_open_to_plug_ins() { + for id in ["find.search", "find.replace", "find.goto", "explorer.tree"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 17e44ea9..a7fcaddd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -33,6 +33,8 @@ mod cmds_width; mod cmds_stroke; pub mod confirm; pub mod editing; +pub mod explorer; +pub mod find; pub mod format; pub mod history; mod merge; @@ -127,6 +129,8 @@ pub fn commands() -> Vec { v.extend(cmds_rawsub::specs()); v.extend(cmds_rawpoints::specs()); v.extend(editing::specs()); + v.extend(find::specs()); + v.extend(explorer::specs()); v.extend(cmds_brush::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0143d66c..3127fcb4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -747,6 +747,25 @@ fn panic_hunt_every_command() { json!({"items": [{"symbol": ball}, {"symbol": ball}, {"folder": inner}, null], "x": "a"}), json!({"items": (0..1500).map(|_| json!({"symbol": ball})).collect::>(), "x": 0, "y": 0}), json!({"sound": SOUND, "symbol": ball, "x": 10, "y": 10}), + // Find and Replace and the Movie Explorer (ADR 0058): patterns that are slow in + // backtracking engines or too large, replacements that would nest a symbol in itself, + // stale hits, junk paths, rows and pages. + json!({"kind": "text", "text": "(a+)+$", "regex": true, "with": "$1$1$1${x}", "in": ["text", "labels", "layers", "instances", "scripts"], "scope": "document"}), + json!({"kind": "text", "text": "a{1000}{1000}", "regex": true, "with": ""}), + json!({"kind": "text", "text": "", "with": "x"}), + json!({"kind": "text", "text": "[a-z]", "regex": true, "with": "", "whole_word": false, "match_case": true, "confirm": true}), + json!({"kind": "text", "text": "L", "with": "", "at": {"scene": 0, "layer": 1, "field": "layer_name", "start": u64::MAX}}), + json!({"kind": "text", "text": "e", "with": "x".repeat(1000), "at": {"symbol": ball, "layer": u64::MAX, "field": "text", "frame": -1}}), + json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "in": ["fills", "strokes", "text", "nope"]}), + json!({"kind": "color", "color": "#3d8bfd", "with": "#000000", "scope": "document"}), + json!({"kind": "font", "font": "Inter", "with": "No Such Font"}), + json!({"kind": "symbol", "symbol": ball, "with": ball, "scope": "document"}), + json!({"kind": "sound", "sound": SOUND, "with": SOUND}), + json!({"kind": "bitmap", "bitmap": bm.0, "with": bm.0, "scope": "document"}), + json!({"kind": "nope", "layer": u64::MAX, "path": [{"layer": 1, "frame": u32::MAX, "element": u64::MAX}], "symbol": ball, "scene": 0}), + json!({"path": (0..100).map(|i| json!({"layer": i, "frame": i, "element": i})).collect::>(), "layer": 1}), + json!({"all": true, "filter": "a", "show": {"frames": false, "symbols": "x"}, "expanded": ["s0", 5], "offset": u64::MAX, "limit": u64::MAX}), + json!({"all": true, "scope": "scene", "definitions": false, "show": {"frames": false}, "limit": 0}), ]); for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, keyed, library] { let mut s = start; From 9daf579bc4eb96fa99bddae0082ac362cef56719 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:09:44 -0700 Subject: [PATCH 033/192] feat(shell): button states named on the timeline, hit area while editing, Show hit areas in Test Movie (M5) --- src/app.rs | 33 +++++++++++++++++++++++++++++ src/main.rs | 2 +- src/test_movie.rs | 22 +++++++++++++------ src/theme.rs | 14 ++++++++++++ src/timeline.rs | 54 ++++++++++++++++++++++++++++++++++++++++++----- 5 files changed, 113 insertions(+), 12 deletions(-) diff --git a/src/app.rs b/src/app.rs index 4d504089..192dace4 100644 --- a/src/app.rs +++ b/src/app.rs @@ -307,6 +307,9 @@ pub struct App { pub tl_scroll: f32, /// Timeline frame width (zoom), in points. pub tl_cell_w: f32, + /// The zoom the timeline had before a button opened and widened its frames for their state + /// names, and the zoom it set (ADR 0057): it goes back on closing, unless zoomed meanwhile. + pub tl_button_zoom: Option<(f32, f32)>, /// Timeline vertical scroll, in rows. pub tl_vscroll: f32, pub tl_last_layer: Option, @@ -496,6 +499,7 @@ impl App { cursor_stage: None, tl_scroll: 0.0, tl_cell_w: timeline::CELL_DEFAULT, + tl_button_zoom: None, tl_vscroll: 0.0, tl_last_layer: None, tl_collapsed: HashSet::new(), @@ -941,6 +945,33 @@ impl App { crate::test_movie::demo_pointer(self); } } + Some(which @ ("button" | "testhits")) => { + // Buttons (ADR 0057): the sample's Play button open in place on its Over frame, + // a click sound on it (made here, a short decaying tone), its states named on + // the timeline and its Hit area over the artwork; or Test Movie with Show Hit + // Areas on. + self.perform("file.new_sample", json!({"which": "interactive"})); + self.run("layer.select", json!({"index": 1})); + if which == "testhits" { + crate::test_movie::open(self); + crate::test_movie::demo_pointer(self); + if let Some(tm) = self.test_movie.as_mut() { + tm.hit_areas = true; + } + } else if let Some(id) = self.s.visible_elements().iter().find(|e| e.name == "play_btn").map(|e| e.id.0) { + self.run("symbol.edit", json!({"id": id})); + let tone: Vec = (0..4410).map(|i| (i as f32 * 0.12).sin() * 0.6 * (-(i as f32) / 900.0).exp()).collect(); + let dir = std::env::temp_dir().join("anicraft-demo"); + let wav = dir.join("click.wav"); + let _ = std::fs::create_dir_all(&dir); + if std::fs::write(&wav, anicraft_engine::doc::audio::wav::encode(44_100, 1, &tone, anicraft_engine::doc::audio::wav::Bits::Int16)).is_ok() + && let Some(v) = self.run("file.import_to_library", json!({"path": wav.display().to_string()})) + { + self.run("sound.place", json!({"sound": v["sound"], "frame": 1})); + } + self.run("timeline.goto", json!({"frame": 1})); + } + } Some(which @ ("script" | "scriptproblems" | "testscript")) => { // The interactive sample as an imported Animate document might bring it: a // frame script kept on the Actions layer's first keyframe (in place of its @@ -2211,6 +2242,8 @@ impl App { crate::motion_path::upkeep(self); crate::widthtool::upkeep(self); crate::bone_tool::upkeep(self); + // An open button shows its hit area over its other states, in the theme's colour (ADR 0057). + self.s.hit_area = Some(theme::hit_area()); self.tick_playback(&ctx); self.scrub_sound(); self.update_title(&ctx); diff --git a/src/main.rs b/src/main.rs index f2746514..0118334a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -180,7 +180,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|button|testhits|exporthtml|sound|envelope|library|librarymenu]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/test_movie.rs b/src/test_movie.rs index 816096b3..e6b7d9e0 100644 --- a/src/test_movie.rs +++ b/src/test_movie.rs @@ -102,8 +102,8 @@ pub struct TestMovie { paused: bool, acc: f64, texture: Option, - /// The state and pixel size the texture shows. - shown: Option<(PlayerState, [u32; 2])>, + /// The state and pixel size the texture shows, and whether with the hit areas. + shown: Option<(PlayerState, [u32; 2], bool)>, /// Where the pointer was over the picture last frame, and whether it was down. pointer: Option, down: bool, @@ -118,6 +118,8 @@ pub struct TestMovie { skipped: usize, /// The movie takes the keyboard the next time it is drawn. focus: bool, + /// Show Hit Areas: every button's hit area drawn over the movie (ADR 0057). + pub hit_areas: bool, } impl TestMovie { @@ -158,7 +160,9 @@ pub fn open(app: &mut App) { let movie = Movie::start_seeded(&doc, if app.shot.is_some() { 0 } else { seed }, &mut runner); let name = app.s.path.as_ref().and_then(|p| p.file_stem()).map(|n| n.to_string_lossy().into_owned()); let skipped = anicraft_engine::player::kept_scripts(&doc).iter().filter(|k| !k.runs()).count(); - let mut tm = TestMovie { doc, movie, paused: false, acc: 0.0, texture: None, shown: None, pointer: None, down: false, name, ms: 0.0, voices: Vec::new(), audio: false, skipped, focus: true }; + // Show Hit Areas stays as it was across a restart. + let hit_areas = app.test_movie.as_ref().is_some_and(|t| t.hit_areas); + let mut tm = TestMovie { doc, movie, paused: false, acc: 0.0, texture: None, shown: None, pointer: None, down: false, name, ms: 0.0, voices: Vec::new(), audio: false, skipped, focus: true, hit_areas }; // Sound only when there is some, and never in screenshot runs or tests. if sound::has_sounds(&tm.doc) && app.shot.is_none() { tm.resume(&mut app.sound); @@ -220,6 +224,8 @@ pub fn show(app: &mut App, ctx: &egui::Context) { let keys = if has_keys(ctx) { tr!("Keys go to the movie") } else { tr!("Click the movie to give it the keyboard") }; ui.label(text(Type::Caption, keys).color(T.text_dim)); } + ui.add_space(8.0); + ui.checkbox(&mut tm.hit_areas, tr!("Show hit areas")).on_hover_text(tr!("Draw where each button answers the pointer (its Hit frame) over the movie")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // i18n-exempt: numbers and units (data) ui.label(text(Type::Data, format!("{:.0} fps · {:.1} ms", tm.doc.stage.fps, tm.ms)).color(T.text_faint)).on_hover_text(tr!("Frame rate, and the time the last picture took to draw")); @@ -316,10 +322,14 @@ pub fn show(app: &mut App, ctx: &egui::Context) { let ppp = ctx.pixels_per_point(); let scale = (k * ppp).min(MAX_EDGE / sw.max(sh).max(1.0)); let px = [((sw * scale).round() as u32).max(1), ((sh * scale).round() as u32).max(1)]; - let stale = tm.shown.as_ref().is_none_or(|(st, at)| *st != tm.movie.state || *at != px); + let stale = tm.shown.as_ref().is_none_or(|(st, at, hits)| *st != tm.movie.state || *at != px || *hits != tm.hit_areas); if stale { let t0 = web_time::Instant::now(); - let dl = evaluate_player(&tm.doc, &tm.movie.state); + let mut dl = evaluate_player(&tm.doc, &tm.movie.state); + if tm.hit_areas { + let (tint, alpha) = crate::theme::hit_area(); + dl.append(anicraft_engine::doc::player::hit_overlay(&tm.doc, &tm.movie.state, tint, alpha)); + } let view = View { transform: Affine::scale(scale, scale), width: px[0], height: px[1], background: Some(tm.doc.stage.background) }; if let Ok((pm, _)) = render(&dl, &view) { let image = egui::ColorImage::from_rgba_unmultiplied([px[0] as usize, px[1] as usize], &pm.to_rgba8()); @@ -329,7 +339,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) { } } tm.ms = t0.elapsed().as_secs_f32() * 1000.0; - tm.shown = Some((tm.movie.state.clone(), px)); + tm.shown = Some((tm.movie.state.clone(), px, tm.hit_areas)); } ui.painter().rect_filled(outer, crate::theme::SQUARE, T.pasteboard); if let Some(t) = &tm.texture { diff --git a/src/theme.rs b/src/theme.rs index 63e586b1..d85351b3 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -83,6 +83,9 @@ pub struct Tokens { /// A symbol's 9-slice guides while it is open for editing (ADR 0055), dashed over a light /// underlay so they read on any artwork. pub slice_guide: Color32, + /// A button's hit area (ADR 0057): laid over its other states while it is open for editing, + /// and over the movie in Test Movie's Show Hit Areas, at [`HIT_AREA_ALPHA`]. + pub hit_area: Color32, /// Library symbol kinds. pub kind_graphic: Color32, pub kind_movie_clip: Color32, @@ -152,6 +155,7 @@ pub const GRAPHITE: Tokens = Tokens { onion_past: Color32::from_rgb(0x4f, 0x8d, 0xff), onion_future: Color32::from_rgb(0x4c, 0xd0, 0x7d), slice_guide: Color32::from_rgb(0xd9, 0x3c, 0xc4), + hit_area: Color32::from_rgb(0x1f, 0xc8, 0x8c), kind_graphic: Color32::from_rgb(0x22, 0xc7, 0xa9), kind_movie_clip: Color32::from_rgb(0x5a, 0x8f, 0xff), kind_button: Color32::from_rgb(0xff, 0xb5, 0x3d), @@ -209,6 +213,7 @@ pub const HIGH_CONTRAST: Tokens = Tokens { onion_past: Color32::from_rgb(0x6f, 0xa8, 0xff), onion_future: Color32::from_rgb(0x5c, 0xf0, 0x9a), slice_guide: Color32::from_rgb(0xff, 0x6e, 0xe6), + hit_area: Color32::from_rgb(0x3d, 0xff, 0xb0), kind_graphic: Color32::from_rgb(0x3d, 0xf0, 0xcf), kind_movie_clip: Color32::from_rgb(0x85, 0xad, 0xff), kind_button: Color32::from_rgb(0xff, 0xc8, 0x5c), @@ -630,3 +635,12 @@ pub fn to_color32(c: anicraft_engine::doc::Rgba) -> Color32 { let c = c.sanitized(); Color32::from_rgba_unmultiplied((c.r * 255.0).round() as u8, (c.g * 255.0).round() as u8, (c.b * 255.0).round() as u8, (c.a * 255.0).round() as u8) } + +/// How strongly a button's hit area is laid over the artwork (ADR 0057): enough to see where the +/// pointer finds the button, light enough to see the state under it. +pub const HIT_AREA_ALPHA: f32 = 0.35; + +/// The tint and opacity a button's hit area is drawn in (ADR 0057). +pub fn hit_area() -> (anicraft_engine::doc::Rgba, f32) { + (to_rgba(T.hit_area), HIT_AREA_ALPHA) +} diff --git a/src/timeline.rs b/src/timeline.rs index fc6caa32..3ffc1087 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -229,6 +229,24 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.tl_scroll = (under - (h.x - grid.left() - pad_for(new)) / new).max(0.0); } } + // A button open (ADR 0057): its four frames are named Up, Over, Down and Hit, as in Animate, + // and drawn wide enough for their names; the zoom it had comes back when it closes. + let states = button_states(app); + match (states, app.tl_button_zoom) { + (Some(names), None) => { + let widest = names.iter().map(|n| painter.layout_no_wrap(n.to_string(), font(Type::Caption), T.text).rect.width()).fold(0.0f32, f32::max); + let set = app.tl_cell_w.max((widest + 8.0).min(*CELL_RANGE.end())); + app.tl_button_zoom = Some((app.tl_cell_w, set)); + app.tl_cell_w = set; + } + (None, Some((before, set))) => { + if (app.tl_cell_w - set).abs() < 1e-3 { + app.tl_cell_w = before; + } + app.tl_button_zoom = None; + } + _ => {} + } let cell_w = app.tl_cell_w; // Dead space before frame 1 (a preference): the playhead's flag never touches the edge. let pad = pad_for(cell_w); @@ -295,7 +313,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Ticks and numbers sit on the frame's centre, where the playhead line and the // keyframe dots are, so "1" is exactly under the playhead on frame 1 at any zoom. let cx = frame_center(x, cell_w); - if n % step == 0 || n == 1 { + if let Some(name) = states.and_then(|s| s.get(f as usize).copied()) { + // A button's state frame: its name in place of the number, the Hit frame underlined + // in the colour its area is drawn in on the stage. + let cell = Rect::from_min_max(pos2(x, ruler.top()), pos2(x + cell_w, ruler.bottom())); + gp.with_clip_rect(cell.intersect(grid)).text(pos2(cx, ruler.center().y - 1.0), Align2::CENTER_CENTER, name, font(Type::Caption), color(Type::Caption)); + if f == 3 { + gp.line_segment([pos2(x + 2.0, ruler.bottom() - 1.5), pos2(x + cell_w - 2.0, ruler.bottom() - 1.5)], Stroke::new(2.0, T.hit_area)); + } + } else if n % step == 0 || n == 1 { gp.line_segment([pos2(cx, ruler.bottom() - 6.0), pos2(cx, ruler.bottom())], Stroke::new(1.0, T.text_faint)); gp.text(pos2(cx, ruler.top() + 3.0), Align2::CENTER_TOP, n.to_string(), font(Type::DataSmall), color(Type::DataSmall)); } else if n % minor == 0 { @@ -313,6 +339,16 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } // The onion menu on a right-click, as the markers live here (ADR 0047). ruler_resp.context_menu(|ui| crate::onion::menu(app, ui)); + // What a button's state frame is for, under the pointer. + if let Some(f) = states.and(ruler_resp.hover_pos()).map(|p| frame_at(p.x)).filter(|f| *f < 4) { + let tip = match f { + 0 => tr!("Up: the button as it first shows"), + 1 => tr!("Over: the button with the pointer over it"), + 2 => tr!("Down: the button while it is pressed"), + _ => tr!("Hit: the area that answers the pointer, never shown (drawn over the other states while you edit them)"), + }; + ruler_resp.clone().on_hover_text(tip); + } // Onion markers over the ruler (they take the pointer before it). crate::onion::ruler(app, ui, ruler, cell_w, x_of, frame_at); @@ -878,9 +914,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if px + cell_w > grid.left() && px < grid.right() { // The same pixel as the ruler tick for this frame. let cx = frame_center(px, cell_w); - // The flag fits its number; it never grows with the zoom. - let label = (app.s.frame + 1).to_string(); - let tw = painter.layout_no_wrap(label.clone(), font(Type::DataSmall), T.ink).rect.width(); + // The flag fits its number (a button's state name on its state frames); it never grows + // with the zoom. + let state = states.and_then(|s| s.get(app.s.frame as usize).copied()); + let (label, role) = state.map_or_else(|| ((app.s.frame + 1).to_string(), Type::DataSmall), |n| (n.to_string(), Type::Caption)); + let tw = painter.layout_no_wrap(label.clone(), font(role), T.ink).rect.width(); let head = Rect::from_center_size(pos2(cx, ruler.center().y), vec2((tw + 8.0).max(HEAD_W), RULER_H - 4.0)); // The frame's band, centred on the same pixel column as the line and the flag: an odd // whole-pixel width around a half-pixel centre puts both edges on pixel boundaries, @@ -889,7 +927,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.with_clip_rect(grid).rect_filled(Rect::from_min_max(pos2(cx - band * 0.5, rows_top), pos2(cx + band * 0.5, body.bottom())), 0.0, T.playhead.gamma_multiply(0.12)); painter.with_clip_rect(grid).line_segment([pos2(cx, ruler.bottom()), pos2(cx, body.bottom())], Stroke::new(1.5, T.playhead)); painter.with_clip_rect(grid).rect_filled(head, T.rc(), T.playhead); - painter.with_clip_rect(grid).text(head.center(), Align2::CENTER_CENTER, label, font(Type::DataSmall), T.ink); + painter.with_clip_rect(grid).text(head.center(), Align2::CENTER_CENTER, label, font(role), T.ink); } // footer buttons for layers @@ -1010,6 +1048,12 @@ fn waveform(p: &egui::Painter, doc: &anicraft_engine::doc::Document, fs: &anicra /// An ease's name in the interface language: the presets and "Custom" are catalog strings, a /// classic ease's strength is filled in, a free Bézier's numbers are data. +/// The names of a button's four state frames, while a button is open for editing (ADR 0057). +pub fn button_states(app: &App) -> Option<[&'static str; 4]> { + let open = app.s.editing_symbol().and_then(|id| app.s.doc.symbol(id))?; + (open.kind == anicraft_engine::doc::SymbolKind::Button).then(|| [trc!("button state", "Up"), trc!("button state", "Over"), trc!("button state", "Down"), trc!("button state", "Hit")]) +} + pub fn easing_label(e: &Easing) -> String { match e { Easing::Classic(s) => tr!("Classic {strength}", strength = format!("{s:+.0}")), From bd770d69807c155cd9501927e20ebdf3635fb233 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:12:25 -0700 Subject: [PATCH 034/192] test: fuzz an open button and its hit area; shell test for state names and zoom (M5) --- crates/engine/src/tests.rs | 14 +++++++++++++- src/test_movie.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0143d66c..9c65ba75 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -748,7 +748,12 @@ fn panic_hunt_every_command() { json!({"items": (0..1500).map(|_| json!({"symbol": ball})).collect::>(), "x": 0, "y": 0}), json!({"sound": SOUND, "symbol": ball, "x": 10, "y": 10}), ]); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, keyed, library] { + // A button open for editing, its hit area drawn over its other states (ADR 0057). + let mut button = Session::new(sample::interactive()); + if let Some(id) = button.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id) { + button.execute("symbol.edit", &json!({"symbol": id.0})).unwrap(); + } + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, keyed, library, button] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { @@ -764,7 +769,14 @@ fn panic_hunt_every_command() { for f in [0, 1, 5, 47, 1000] { let _ = anicraft_render::render_frame(&s.doc, f, 0.1); } + s.hit_area = Some((anicraft_doc::Rgba::WHITE, 0.4)); let pic = s.stage_picture(); + // ...and every button's hit area draws, under a pointer that goes over and presses. + let mut ns = anicraft_doc::player::NoScripts; + let st = anicraft_doc::player::start(&s.doc, &mut ns).state; + let p = anicraft_geom::Vec2::new(640.0, 400.0); + let st = anicraft_doc::player::input(&s.doc, &st, &[anicraft_doc::player::Event::Move(p), anicraft_doc::player::Event::Down(p), anicraft_doc::player::Event::Up(p)], &mut ns).state; + let _ = anicraft_render::render(&anicraft_doc::player::hit_overlay(&s.doc, &st, anicraft_doc::Rgba::WHITE, 0.4), &anicraft_render::View { transform: anicraft_geom::Affine::scale(0.1, 0.1), width: 128, height: 72, background: None }); let _ = anicraft_render::render_frame(&pic.doc, pic.frame, 0.1); // ...and its sounds lay out and mix. let voices = anicraft_doc::sound::voices(&s.doc, 8000); diff --git a/src/test_movie.rs b/src/test_movie.rs index e6b7d9e0..467d3abc 100644 --- a/src/test_movie.rs +++ b/src/test_movie.rs @@ -452,6 +452,34 @@ mod tests { assert!(app.test_movie.is_none()); } + #[test] + fn an_open_button_names_its_states_widens_its_frames_and_shows_its_hit_area() { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::interactive()); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + frame(&ctx, &mut app, vec![]); + let zoom = app.tl_cell_w; + assert!(crate::timeline::button_states(&app).is_none(), "on the stage, frames are numbered"); + let button = app.s.doc.library.iter().find(|s| s.kind == anicraft_engine::doc::SymbolKind::Button).map(|s| s.id.0); + app.run("symbol.edit", json!({"symbol": button})); + app.run("timeline.goto", json!({"frame": 1})); + frame(&ctx, &mut app, vec![]); + assert_eq!(crate::timeline::button_states(&app).map(|s| s.len()), Some(4)); + assert!(app.tl_cell_w > zoom, "wide enough for “Over”: {} vs {zoom}", app.tl_cell_w); + assert!(app.s.hit_overlay().is_some(), "the Hit area over the Over state, in the theme's colour"); + app.run("symbol.exit", json!({})); + frame(&ctx, &mut app, vec![]); + assert_eq!(app.tl_cell_w, zoom, "the zoom it had comes back"); + // Test Movie keeps Show hit areas across a restart. + open(&mut app); + if let Some(tm) = app.test_movie.as_mut() { + tm.hit_areas = true; + } + open(&mut app); + assert!(app.test_movie.as_ref().is_some_and(|t| t.hit_areas)); + frame(&ctx, &mut app, vec![]); + } + #[test] fn key_codes_are_actionscript_s() { use egui::Key as K; From 9b2e783b3c0fa23764391e88215ce1236deca83c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:13:35 -0700 Subject: [PATCH 035/192] docs: ADR 0057 button sounds and hit areas; roadmap, changelog, ADR 0039 and 0055 notes (M5) --- ATTRIBUTION.md | 1 + CHANGELOG.md | 15 +++ ...-sound-effects-volume-and-symbol-sounds.md | 8 ++ docs/adr/0055-nine-slice-scaling.md | 5 + docs/adr/0057-button-sounds-and-hit-areas.md | 109 ++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 8 +- 7 files changed, 142 insertions(+), 5 deletions(-) create mode 100644 docs/adr/0057-button-sounds-and-hit-areas.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8b6fbe8b..a627b6de 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -100,6 +100,7 @@ OR Apache-2.0) is noted in the table. | ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs`, `crates/xfl/tests/support/fla.rs` | PKWARE APPNOTE.TXT 6.3 (published ZIP specification), the Info-ZIP Unicode path extra field (0x7075, Info-ZIP `proginfo/extrafld.txt`); CRC-32 by slicing by 8 (M. Kounavis and F. Berry, "A Systematic Approach to Building High Performance Software-based CRC Generators", IEEE ISCC 2005); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries, ZIP64, data descriptors, CP437 and UTF-8 names; no encryption (ADR 0054). | | JPEG decoding (imported images) | `crates/engine/src/cmds_file.rs` | `zune-jpeg` (MIT OR Apache-2.0 OR Zlib), already in the dependency tree | Decoded to RGBA, kept as PNG. | | XFL document structure and shape edges | `crates/xfl/src/` | The publicly documented XFL package structure (`DOMDocument.xml`, `LIBRARY/*.xml`, edge strings) | Clean room: no Animate or third-party converter code (ADR 0009). | +| Button sounds by state transition (Up→Over, Over→Up, Over→Down, Down→Over) | `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | Adobe, *SWF File Format Specification* (version 19), `DefineButtonSound` (published open specification) | Only the mapping of transitions to the four state frames is taken; no code or data (ADR 0057). | | Full SVG path data and elliptical-arc to Bézier conversion | `crates/geom/src/svg.rs` | W3C SVG 1.1 §8.3 and Appendix F.6 (implementation notes) | W3C Royalty-Free Patent Policy. | | SVG document import: shapes, styling and inheritance, transforms, viewBox and preserveAspectRatio, paint servers (gradients), `use` | `crates/svg` | W3C SVG 1.1 (§5, §6, §7, §9, §13) and SVG 2; CSS Color Module Level 3 (colour syntax and names) | W3C Royalty-Free Patent Policy. | | SVG clip paths, masks and text: `clipPath`, `mask`, `text`/`tspan` positioning and text chunks, white-space handling | `crates/svg/src/clip.rs`, `crates/svg/src/text.rs` | W3C SVG 1.1 (§10, §14) and SVG 2 (§11 Text); W3C CSS Masking Module Level 1; CSS Fonts Level 3 (`font-family`, `font-weight`, `font-size` keywords) | W3C Royalty-Free Patent Policy. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b7b22d2..75654804 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +* **Buttons, complete: sounds on button frames and hit-area editing** (ADR 0057, M5). + * A sound on a button's **Over** or **Down** frame plays when the pointer goes over or + presses the button, in Test Movie and in the HTML canvas page (Web Audio). As the SWF format + keeps them, the Up frame's plays on leaving and the Hit frame's on letting go over it. A + stream on a button frame plays as an event. Buttons stay out of the soundtrack: Export Audio + and video are unchanged. + * Editing a button in place, the timeline names its four frames **Up, Over, Down, Hit** (and + widens them to fit while the button is open), and the stage draws the **Hit area** + translucent over the other states. + * Test Movie has a **Show hit areas** checkbox. + * XFL and `.fla` import bring sounds whose file is in the package (WAV, Ogg Vorbis, MP3), with + the sounds on frames that use them, buttons' states included; sounds kept only in Animate's + own format are reported. + * Headless: `control.test_movie` lists the sounds it started. + * 9-slice guides switched off are now kept, and come back where they were when switched on. * **9-slice scaling for symbols** (ADR 0055, M2). * **Enable guides for 9-slice scaling** on a symbol, in the Library's item properties or in Properties. A scaled instance then keeps its corners unscaled, stretches its edges one way diff --git a/docs/adr/0039-sound-effects-volume-and-symbol-sounds.md b/docs/adr/0039-sound-effects-volume-and-symbol-sounds.md index 8810a606..54d791f6 100644 --- a/docs/adr/0039-sound-effects-volume-and-symbol-sounds.md +++ b/docs/adr/0039-sound-effects-volume-and-symbol-sounds.md @@ -129,3 +129,11 @@ editor playhead during preview. default); files without effects or volumes are byte-identical to before. * The fuzz over every command runs with fades, custom envelopes and streams inside every symbol, and lays out and mixes the result after each run. + +## Update (2026-11-11, ADR 0057) + +Sounds on button frames now play in Test Movie and the HTML page as the pointer changes a +button's state (Over's going over it, Down's pressing it, Up's leaving, Hit's letting go over +it), and the soundtrack still leaves buttons out. XFL import brings sounds whose file is in the +package (WAV, Ogg Vorbis, MP3), with the sounds on frames that use them; sounds kept only in +Animate's own data format are still reported, as this ADR decided. diff --git a/docs/adr/0055-nine-slice-scaling.md b/docs/adr/0055-nine-slice-scaling.md index b7d525a8..a6755a88 100644 --- a/docs/adr/0055-nine-slice-scaling.md +++ b/docs/adr/0055-nine-slice-scaling.md @@ -118,3 +118,8 @@ work stays bounded. HTML canvas export slicing (its player), 9-slice for bitmaps (Animate doesn't either), guides shown in Library previews, snapping guides to artwork, a symbol-wide "scale strokes" option, and Lottie's native 9-slice (it has none). + +## Update (2026-11-11, ADR 0057) + +Turning the guides off no longer forgets them: they are kept (`Symbol::scale_grid_kept`, only +hidden) and turning 9-slice on again, or moving a guide, brings them back where they were. diff --git a/docs/adr/0057-button-sounds-and-hit-areas.md b/docs/adr/0057-button-sounds-and-hit-areas.md new file mode 100644 index 00000000..860398ee --- /dev/null +++ b/docs/adr/0057-button-sounds-and-hit-areas.md @@ -0,0 +1,109 @@ +# ADR 0057: Sounds on button frames and hit-area editing + +* Status: accepted (2026-11-11) +* Relates to: ADR 0024 (the interactive player and Test Movie), ADR 0020 and ADR 0039 (sounds, + effects, volumes), ADR 0028 (HTML canvas export), ADR 0045 (editing a symbol in place), + ADR 0055 (9-slice scaling), ADR 0009 (XFL import), ADR 0040 (interface languages) + +## Context + +Buttons already show Up, Over and Down and answer the pointer through their Hit frame in Test +Movie and the HTML page (ADR 0024, 0028), but a sound on a button's frame never played: the +soundtrack layout skips buttons (they wait for the pointer) and the player only started sounds +of frames that timelines *enter*. Artists coming from Animate put a click on a button's Over or +Down frame and expect to hear it when they point at or press the button. They also expect the +four frames to say what they are, and they need to see the Hit area while drawing the other +states, which Animate leaves to guesswork (the Hit frame is never shown). + +Behaviour was learned from Adobe's public help ("add a sound to a button's Over or Down +frame") and from the **SWF File Format Specification** (published by Adobe as an open +specification), whose `DefineButtonSound` tag keeps four sounds by state transition: +`OverUpToIdle`, `IdleToOverUp`, `OverUpToOverDown`, `OverDownToOverUp`. No Adobe code, SDK or +asset was used. + +## Decision + +1. **When a button sounds (player, `doc::player`).** Each button's pointer state is one of + `ButtonState::{Up, Over, Down, OutDown}` (pressed and dragged off shows Up). Every change of + hover, press or release is diffed per button, before its handlers run, and a change plays + the sound on the frame the SWF transitions name: + + | Change | Frame whose sound plays | + |---|---| + | Up → Over (the pointer arrives) | Over (2nd) | + | Over → Up (it leaves) | Up (1st) | + | Over → Down (pressed) | Down (3rd) | + | Down → Over (released over it) | Hit (4th) | + | dragged off and back while pressed, released off | none | + + Arriving and pressing in one event plays Over's, then Down's. The sound is the keyframe + *starting* at that frame on every sound-carrying layer of the button (as entering a frame + does), at the volume of its layer times the layers holding the button (ADR 0039). Start and + Stop keep their meaning; **a stream plays as an event**, since a button frame has no span to + stream over. A button shorter than four frames has no sound for the frames it lacks. The + sounds go out in `Step::sounds` from `input` and `step` alike, so Test Movie (which already + triggers what each step reports) plays them with no change of its own, deterministically and + without a device in tests. +2. **The soundtrack is untouched.** `sound::voices` still leaves buttons out: buttons only + sound interactively. Export Audio, video and Lottie are unchanged (tested: a movie whose only + sounds are on a button exports silence). +3. **HTML canvas.** The page already carries every symbol's frame sounds (`snd`); `player.js` + gets the same state diff (`buttonState`, `buttonSoundFrame`, `buttonSounds`) and canvas.js + plays the result with Web Audio as it plays every other sound. The export no longer reports + "sounds on button frames". A Boa test plays the same pointer script through both players and + compares the sounds started, their sync and volume, batch by batch. +4. **One hit area.** `player::hit_frame` (the 4th frame, else Up) and `player::hit_area` (that + frame's artwork without guides and mask artwork, unclipped) are what the hit test uses, and + what is drawn: `player::tinted` lays any display list over the picture as **one** group at + an opacity, every item in one colour (so overlapping shapes don't darken each other), and + `player::hit_overlay` does it for every button on the stage. +5. **Editing a button in place (ADR 0045).** While a button is open and its playhead is on any + frame but its hit frame, `Session::stage_picture` adds its hit timeline (mask layers removed + and what they masked made whole, guide layers hidden) on top, as an instance tinted fully in + the theme's `hit_area` colour at 35 % (`theme::HIT_AREA_ALPHA`). The tint is view state + (`Session::hit_area`, set by the app from the theme every frame; `None` headless, so the + picture is unchanged there) and part of the picture's key, so every tile, GPU or CPU, draws + the same overlay. The timeline names the four frames **Up, Over, Down, Hit** in the ruler + and in the playhead's flag (prose, `Type::Caption`, translated with the context "button + state"), underlines the Hit frame in the overlay's colour, explains each on hover, and widens + its frames to fit the names while the button is open, restoring the zoom on closing unless + the artist zoomed meanwhile. +6. **Test Movie: Show hit areas**, a checkbox in the window's bar: every hittable button's + hit area over the picture (`hit_overlay`), kept across Restart. +7. **Headless.** `control.test_movie` returns `sounds: [{tick, sound, name, sync, gain}]` + (capped at 10,000, the rest counted in `more_sounds`), so button sounds can be checked from + the CLI and MCP. +8. **XFL (ADR 0039's rule, now applied).** `DOMSoundItem`s whose file is in the package + (`LIBRARY/`, or `bin/` when that is a plain WAV, Ogg Vorbis or MP3) come + across into the Library, in their folders; sounds kept only in Animate's own data format are + reported ("sounds stored in Animate's own format"), as are missing files. Keyframes keep + their sound (`soundName`, `soundSync`, `soundLoopMode`/`soundLoop`) on every timeline, + buttons' included; a frame whose sound didn't come across, sound effects and envelopes, and + in/out points are reported. The attribute names follow the publicly described XFL format; + our test package is self-made. +9. **9-slice guides are remembered** (from the ADR 0055 review). `Symbol::scale_grid_kept` + (`#[serde(default)]`, left out when empty) holds the guides while 9-slice is off; + `symbol.set_scale_grid {on: true}` (or moving a guide) brings them back where they were + instead of starting again from the artwork. Loading drops a kept grid that isn't usable, or + one kept beside guides that are on. Older files open unchanged. + +## Choices made without the project lead (defaults; easy to change later) + +* **Up and Hit frame sounds play too** (on leaving and on release), as the SWF format keeps + them, rather than only Over and Down. +* **The hit area is drawn over the artwork**, translucent, rather than under it: it stays + visible on busy states. +* **The timeline widens a button's frames** for their names rather than abbreviating them. + +## Not in this slice + +Editing the Hit frame's shape from another state (drawing straight into the overlay), a +separate outline style for the overlay, sounds on movie clips used as buttons (they have no +states), keyboard-driven button presses (Tab focus, Enter), sound envelopes and in/out points +from XFL, and button sounds in Lottie (Lottie has no interactivity). + +## Consequences + +* Older files open unchanged; files without kept guides are byte-identical. +* The fuzz over every command now also runs with a button open for editing and its overlay + on, and draws every button's hit area after a pointer goes over and presses. diff --git a/docs/adr/README.md b/docs/adr/README.md index 32101b85..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0057 | (M5 track, button sounds) | Sounds on button frames and hit-area editing | diff --git a/docs/roadmap.md b/docs/roadmap.md index 593b07f4..abbfbb6e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -13,11 +13,11 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | -| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | +| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | -| Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | +| Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | -| Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported. Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | +| Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | | Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. | @@ -36,7 +36,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. | From 10ec9a084d7d48b41db247ad38f0a60b37592b74 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:18:09 -0700 Subject: [PATCH 036/192] feat(shell): Find and Replace window and the Movie Explorer tab (M8) --- src/a11y.rs | 2 +- src/app.rs | 44 ++++ src/find_panel.rs | 506 ++++++++++++++++++++++++++++++++++++++++ src/guidelines_tests.rs | 4 +- src/i18n/tests.rs | 2 +- src/keymap.rs | 3 + src/main.rs | 2 + src/menus.rs | 9 +- src/movie_explorer.rs | 314 +++++++++++++++++++++++++ src/panels.rs | 20 +- 10 files changed, 897 insertions(+), 9 deletions(-) create mode 100644 src/find_panel.rs create mode 100644 src/movie_explorer.rs diff --git a/src/a11y.rs b/src/a11y.rs index f9bbdc0e..15724ac7 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -352,7 +352,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index 4d504089..9833d81c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -382,6 +382,10 @@ pub struct App { pub show_plugins: bool, /// Window › Actions (F9), and what it addresses. pub show_actions: bool, + /// Edit › Find and Replace (Ctrl+F) and its results (ADR 0058). + pub find: crate::find_panel::FindState, + /// Window › Movie Explorer, the Library dock's other tab (ADR 0058). + pub explorer: crate::movie_explorer::ExplorerView, pub actions: crate::actions_panel::State, /// Control › Test Movie: the movie playing in its own window. pub test_movie: Option, @@ -435,6 +439,10 @@ pub const VIEW_SHORTCUTS: &[(&str, &str)] = &[ ("Ctrl+F6", "view.next_panel"), ("Ctrl+Shift+F6", "view.prev_panel"), ("F9", "view.actions"), + // Find Next and Find Previous, and Window › Movie Explorer, as in Animate (ADR 0058). + ("F3", "view.find_next"), + ("Shift+F3", "view.find_prev"), + ("Alt+F3", "view.movie_explorer"), // Brush size, as in paint programs. ("[", "view.brush_smaller"), ("]", "view.brush_larger"), @@ -539,6 +547,8 @@ impl App { plugin_dialog: None, show_plugins: false, show_actions: false, + find: Default::default(), + explorer: Default::default(), actions: crate::actions_panel::State::default(), test_movie: None, envelope: None, @@ -773,6 +783,22 @@ impl App { self.recovery.show = true; } Some("licenses") => self.show_licenses = true, + Some("find") => { + // Find and Replace (ADR 0058): a caption on the stage and the sample's names hold + // "ball"; the results listed, the first one gone to. + self.run("text.create", json!({"text": "Ball bounces (ball 1)", "x": 60, "y": 40, "size": 28})); + self.run("edit.deselect", json!({})); + self.find.open = true; + self.find.text = "ball".into(); + self.find.with = "planet".into(); + crate::find_panel::step(self, true); + } + Some("explorer") => { + // The Movie Explorer tab (ADR 0058), its first rows open: scene, layers, keyframes + // and the instances on them, opening into their symbols. + crate::movie_explorer::open(self); + crate::movie_explorer::expand_to(self, 3); + } Some("about") => self.show_about = true, Some("zoom") => { // 300% on the ball: many tiles, edges cross shapes (seam check). @@ -1515,6 +1541,15 @@ impl App { self.status_ok(if n == 0 { tr!("Exported {path} ({secs} s). No sounds play in that range, so the file is silent.", path = path, secs = secs) } else { tr!("Exported {path} ({secs} s).", path = path, secs = secs) }); } "sound.delete" => self.status_ok(tr!("Deleted sound — {undo} to undo", undo = self.undo_key())), + "find.replace" => { + let n = v["replaced"].as_u64().unwrap_or(0); + let skipped = v["skipped"].as_u64().unwrap_or(0); + self.status_ok(if skipped > 0 { + trn!("Replaced {n} place, left {skipped} as it was — {undo} to undo", "Replaced {n} places, left {skipped} as they were — {undo} to undo", n, skipped = skipped, undo = self.undo_key()) + } else { + trn!("Replaced {n} place — {undo} to undo", "Replaced {n} places — {undo} to undo", n, undo = self.undo_key()) + }); + } "file.import" => { if let Some(b) = self.s.doc.bitmaps.last().filter(|b| v["bitmap"].as_u64() == Some(b.id.0)) { self.library_sel = Some(LibraryItem::Bitmap(b.id)); @@ -1636,6 +1671,11 @@ impl App { crate::shape_hints::add(self); return; } + if id == "find.search" { + // Edit › Find and Replace (Ctrl+F): its window (headless, the command searches). + crate::find_panel::open(self); + return; + } if id == "control.test_movie" { // Control › Test Movie: the player in its own window (headless, the command plays // the movie and reports). @@ -1961,6 +2001,9 @@ impl App { } } "view.actions" => self.show_actions = !self.show_actions, + "view.find_next" => crate::find_panel::step(self, true), + "view.find_prev" => crate::find_panel::step(self, false), + "view.movie_explorer" => crate::movie_explorer::open(self), "view.brush_smaller" => crate::brushtool::resize(self, false), "view.brush_larger" => crate::brushtool::resize(self, true), id if id.starts_with("tool.") => tool = keymap::tool_for(id).or(tool), @@ -2243,6 +2286,7 @@ impl App { autosave::window(self, &ctx); crate::plugins_ui::show(self, &ctx); crate::actions_panel::show(self, &ctx); + crate::find_panel::show(self, &ctx); crate::test_movie::show(self, &ctx); crate::envelope::show(self, &ctx); diff --git a/src/find_panel.rs b/src/find_panel.rs new file mode 100644 index 00000000..4392c5d0 --- /dev/null +++ b/src/find_panel.rs @@ -0,0 +1,506 @@ +//! Edit › Find and Replace (ADR 0058): a window that stays open while you work. What to find +//! (text, a font, a colour, a symbol, a sound or a bitmap), where (this scene and the symbols it +//! uses, or the whole document), and the results listed as you type; clicking one, Find Next +//! (F3) or Find Previous (Shift+F3) goes there (`find.goto`); Replace and Replace All are +//! `find.replace`, one undo step each. The list draws only the rows in view. + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::theme::{T, TARGET, Type, color, font, text}; +use anicraft_engine::StateId; +use anicraft_engine::find::{self, Field, Hit, Kind, Query, TextOptions, Where}; +use egui::{Align2, Rect, Sense, WidgetType, pos2, vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +/// The window's fields and results (view state). +pub struct FindState { + pub open: bool, + /// Put the keyboard in the Find field on the next frame. + pub focus: bool, + pub kind: Kind, + /// Search the whole document (off: this scene and the symbols it uses). + pub document: bool, + pub text: String, + pub with: String, + pub opts: TextOptions, + pub within: find::Within, + pub color: [u8; 3], + pub with_color: [u8; 3], + pub font: String, + pub with_font: String, + /// A Library id (symbol, sound or bitmap) to find, and to replace with. + pub item: Option, + pub with_item: Option, + /// The result the last Find Next or click went to. + pub current: Option, + results: Option, +} + +impl Default for FindState { + fn default() -> Self { + FindState { + open: false, + focus: false, + kind: Kind::Text, + document: false, + text: String::new(), + with: String::new(), + opts: TextOptions::default(), + within: find::Within::default(), + color: [0, 0, 0], + with_color: [255, 255, 255], + font: String::new(), + with_font: String::new(), + item: None, + with_item: None, + current: None, + results: None, + } + } +} + +/// The hits, and whether the list stopped at its limit; or why the query isn't one. +type Found = Result<(Arc>, bool), String>; + +/// A search's results and what they were found for. +struct Results { + key: (String, StateId, usize), + found: Found, +} + +impl FindState { + /// The query as `find.search` params (`with` added for `find.replace`). + pub fn params(&self) -> Value { + let hex = |c: [u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]); + let mut p = json!({"kind": self.kind.key(), "scope": if self.document { "document" } else { "scene" }}); + let w = self.within; + match self.kind { + Kind::Text => { + p["text"] = json!(self.text); + p["match_case"] = json!(self.opts.match_case); + p["whole_word"] = json!(self.opts.whole_word); + p["regex"] = json!(self.opts.regex); + let places: Vec<&str> = [(w.text, "text"), (w.labels, "labels"), (w.layers, "layers"), (w.instances, "instances"), (w.scripts, "scripts")].into_iter().filter(|(on, _)| *on).map(|(_, k)| k).collect(); + p["in"] = json!(places); + p["with"] = json!(self.with); + } + Kind::Color => { + p["color"] = json!(hex(self.color)); + let places: Vec<&str> = [(w.fills, "fills"), (w.strokes, "strokes"), (w.text_color, "text")].into_iter().filter(|(on, _)| *on).map(|(_, k)| k).collect(); + p["in"] = json!(places); + p["with"] = json!(hex(self.with_color)); + } + Kind::Font => { + p["font"] = json!(self.font); + p["with"] = json!(self.with_font); + } + Kind::Symbol | Kind::Sound | Kind::Bitmap => { + p[self.kind.key()] = json!(self.item); + p["with"] = json!(self.with_item); + } + } + p + } + + /// Whether there is something to look for yet (an empty field shows a hint, not an error). + fn ready(&self) -> bool { + match self.kind { + Kind::Text => !self.text.is_empty(), + Kind::Font => !self.font.trim().is_empty(), + Kind::Color => true, + Kind::Symbol | Kind::Sound | Kind::Bitmap => self.item.is_some(), + } + } +} + +/// The results for the window's query, searched again when the query or the document changes. +fn results(app: &mut App) -> Option<&Found> { + if !app.find.ready() { + app.find.results = None; + return None; + } + let mut p = app.find.params(); + if let Some(o) = p.as_object_mut() { + o.remove("with"); + } + let key = (p.to_string(), app.s.state, app.s.scene); + if app.find.results.as_ref().is_none_or(|r| r.key != key) { + let found = Query::from_params(&app.s, &p).map(|q| find::search(&app.s.doc, app.s.scene, &q)).map(|(h, t)| (Arc::new(h), t)).map_err(|e| crate::i18n::t_dyn(&e.to_string()).into_owned()); + app.find.results = Some(Results { key, found }); + } + app.find.results.as_ref().map(|r| &r.found) +} + +fn hits(app: &mut App) -> Arc> { + match results(app) { + Some(Ok((h, _))) => h.clone(), + _ => Arc::default(), + } +} + +/// Edit › Find and Replace (Ctrl+F): opens the window, the Find field ready for typing. +pub fn open(app: &mut App) { + app.find.open = true; + app.find.focus = true; +} + +/// Goes to result `i` and remembers it. +fn go(app: &mut App, i: usize, list: &[Hit]) { + let Some(h) = list.get(i) else { return }; + app.playing = false; + if app.run("find.goto", h.to_json(&app.s.doc, app.find.kind)).is_some() { + app.find.current = Some(i); + app.status_ok(tr!("Result {n} of {total}", n = i + 1, total = list.len())); + } +} + +/// Find Next (F3) or Find Previous (Shift+F3): the next result after the current one, round +/// to the first. +pub fn step(app: &mut App, forward: bool) { + let list = hits(app); + if list.is_empty() { + if !app.find.open { + open(app); + } + app.status_ok(if app.find.ready() { tr!("Nothing found") } else { tr!("Type what to find in Find and Replace") }); + return; + } + let n = list.len(); + let i = match app.find.current { + Some(c) if forward => (c + 1) % n, + Some(c) => (c + n - 1) % n, + None if forward => 0, + None => n - 1, + }; + go(app, i, &list); +} + +/// Replace: the current result (the first when none is), then on to the next. +fn replace_one(app: &mut App) { + let list = hits(app); + let i = app.find.current.filter(|i| *i < list.len()).unwrap_or(0); + let Some(h) = list.get(i) else { return }; + let mut p = app.find.params(); + p["at"] = h.to_json(&app.s.doc, app.find.kind); + if app.perform("find.replace", p).is_some() { + // The replaced one is gone (or no longer matches): the one now at its place is next. + let after = hits(app); + if after.is_empty() { + app.find.current = None; + } else { + go(app, i.min(after.len() - 1), &after); + } + } +} + +fn kind_label(k: Kind) -> &'static str { + match k { + Kind::Text => tr_noop!("Text"), + Kind::Font => tr_noop!("Font"), + Kind::Color => tr_noop!("Colour"), + Kind::Symbol => tr_noop!("Symbol"), + Kind::Sound => tr_noop!("Sound"), + Kind::Bitmap => tr_noop!("Bitmap"), + } +} + +fn field_label(f: Field) -> &'static str { + match f { + Field::Text => tr_noop!("Text field"), + Field::Label => tr_noop!("Frame label"), + Field::LayerName => tr_noop!("Layer name"), + Field::InstanceName => tr_noop!("Instance name"), + Field::Script => tr_noop!("Script"), + Field::Font => tr_noop!("Font"), + Field::Fill => tr_noop!("Fill"), + Field::Stroke => tr_noop!("Stroke"), + Field::TextColor => tr_noop!("Text colour"), + Field::Instance => tr_noop!("Instance"), + Field::Sound => tr_noop!("Sound"), + Field::Bitmap => tr_noop!("Bitmap"), + } +} + +/// Where a result is, for its row: the scene or symbol, the layer and the frame. +fn location(app: &App, h: &Hit) -> String { + let doc = &app.s.doc; + // Scene, symbol and layer names are document text, as written. + let place = match h.at { + Where::Scene(i) => doc.scenes.get(i).map_or_else(String::new, |s| s.name.clone()), + Where::Symbol(id) => doc.symbol(id).map_or_else(String::new, |s| s.name.clone()), + }; + let layer = find::timeline_of(doc, h.at).and_then(|t| t.layer(h.layer)).map_or_else(String::new, |l| l.name.clone()); + match h.frame { + Some(f) => tr!("{place} › {layer}, frame {frame}", place = place, layer = layer, frame = f + 1), + None => tr!("{place} › {layer}", place = place, layer = layer), + } +} + +pub fn show(app: &mut App, ctx: &egui::Context) { + if !app.find.open { + return; + } + let mut open = app.find.open; + let at = ctx.content_rect().right_top() + vec2(-720.0, 110.0); + let shown = egui::Window::new(tr!("Find and Replace")).id(egui::Id::new("find_replace")).open(&mut open).default_pos(at).default_width(400.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui)); + a11y::name_title_bar(&shown, tr!("Find and Replace")); + app.find.open = open; +} + +/// The query's "find" and "replace with" rows for the kind chosen. +fn query_rows(app: &mut App, ui: &mut egui::Ui) -> bool { + let mut enter = false; + let label_w = 92.0; + let row = |ui: &mut egui::Ui, label: &str, add: &mut dyn FnMut(&mut egui::Ui)| { + ui.horizontal(|ui| { + ui.add_sized(vec2(label_w, TARGET), egui::Label::new(text(Type::Label, label))); + add(ui); + }); + }; + let w = (ui.available_width() - label_w - 8.0).max(120.0); + match app.find.kind { + Kind::Text => { + row(ui, tr!("Find"), &mut |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut app.find.text).desired_width(w).hint_text(tr!("Text to find"))).named(tr!("Text to find")); + if app.find.focus { + r.request_focus(); + app.find.focus = false; + } + enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + }); + row(ui, tr!("Replace with"), &mut |ui| { + ui.add(egui::TextEdit::singleline(&mut app.find.with).desired_width(w).hint_text(if app.find.opts.regex { tr!("$1 puts back a group") } else { tr!("Replacement text") })).set_name(tr!("Replace with")); + }); + } + Kind::Font => { + let used = doc_fonts(&app.s.doc); + let families = app.font_families.get_or_insert_with(|| anicraft_engine::text::Fonts::get().families().to_vec()).clone(); + row(ui, tr!("Find"), &mut |ui| { + font_combo(ui, "find_font", &mut app.find.font, &used, tr!("Font to find"), w); + }); + row(ui, tr!("Replace with"), &mut |ui| { + font_combo(ui, "with_font", &mut app.find.with_font, &families, tr!("Font to replace with"), w); + }); + } + Kind::Color => { + row(ui, tr!("Find"), &mut |ui| { + ui.color_edit_button_srgb(&mut app.find.color).named(tr!("Colour to find")); + ui.label(text(Type::Data, format!("#{:02x}{:02x}{:02x}", app.find.color[0], app.find.color[1], app.find.color[2]))); + }); + row(ui, tr!("Replace with"), &mut |ui| { + ui.color_edit_button_srgb(&mut app.find.with_color).named(tr!("Colour to replace with")); + ui.label(text(Type::Data, format!("#{:02x}{:02x}{:02x}", app.find.with_color[0], app.find.with_color[1], app.find.with_color[2]))); + }); + } + Kind::Symbol | Kind::Sound | Kind::Bitmap => { + let items = library_items(app, app.find.kind); + row(ui, tr!("Find"), &mut |ui| item_combo(ui, "find_item", &mut app.find.item, &items, tr!("Item to find"), w)); + row(ui, tr!("Replace with"), &mut |ui| item_combo(ui, "with_item", &mut app.find.with_item, &items, tr!("Item to replace with"), w)); + } + } + enter +} + +/// The fonts text in the document uses, A to Z. +fn doc_fonts(doc: &anicraft_engine::doc::Document) -> Vec { + let mut v: Vec = doc.timelines().flat_map(|t| &t.layers).flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).filter_map(|e| match &e.kind { + anicraft_engine::doc::ElementKind::Text(t) => Some(t.font.clone()), + _ => None, + }).collect(); + v.sort_unstable(); + v.dedup(); + v +} + +fn font_combo(ui: &mut egui::Ui, id: &str, value: &mut String, options: &[String], name: &str, w: f32) { + let shown = if value.is_empty() { tr!("Choose a font").to_string() } else { value.clone() }; + egui::ComboBox::from_id_salt(id).width(w).selected_text(shown).show_ui(ui, |ui| { + if options.is_empty() { + ui.label(text(Type::Caption, tr!("No text uses a font yet"))); + } + for f in options.iter().take(2_000) { + if ui.selectable_label(f == value, f.as_str()).clicked() { + value.clone_from(f); + } + } + }) + .response + .set_name(name); +} + +/// The Library's items of `kind`: id and name (document text). +fn library_items(app: &App, kind: Kind) -> Vec<(u64, String)> { + let d = &app.s.doc; + match kind { + Kind::Symbol => d.library.iter().map(|s| (s.id.0, s.name.clone())).collect(), + Kind::Sound => d.sounds.iter().map(|s| (s.id.0, s.name.clone())).collect(), + Kind::Bitmap => d.bitmaps.iter().map(|b| (b.id.0, b.name.clone())).collect(), + _ => Vec::new(), + } +} + +fn item_combo(ui: &mut egui::Ui, id: &str, value: &mut Option, items: &[(u64, String)], name: &str, w: f32) { + let shown = value.and_then(|v| items.iter().find(|(i, _)| *i == v)).map_or_else(|| tr!("Choose from the Library").to_string(), |(_, n)| n.clone()); + egui::ComboBox::from_id_salt(id).width(w).selected_text(shown).show_ui(ui, |ui| { + if items.is_empty() { + ui.label(text(Type::Caption, tr!("The Library has none"))); + } + for (i, n) in items { + if ui.selectable_label(*value == Some(*i), n.as_str()).clicked() { + *value = Some(*i); + } + } + }) + .response + .set_name(name); +} + +fn panel(app: &mut App, ui: &mut egui::Ui) { + // What to find, and where. + ui.horizontal(|ui| { + ui.label(text(Type::Label, tr!("Search for"))); + let before = app.find.kind; + egui::ComboBox::from_id_salt("find_kind").width(110.0).selected_text(crate::i18n::t(kind_label(app.find.kind))).show_ui(ui, |ui| { + for k in Kind::ALL { + ui.selectable_value(&mut app.find.kind, k, crate::i18n::t(kind_label(k))); + } + }) + .response + .set_name(tr!("What to search for")); + if app.find.kind != before { + app.find.current = None; + } + ui.label(text(Type::Label, tr!("in"))); + let scope = if app.find.document { tr!("The whole document") } else { tr!("This scene") }; + egui::ComboBox::from_id_salt("find_scope").width(150.0).selected_text(scope).show_ui(ui, |ui| { + ui.selectable_value(&mut app.find.document, false, tr!("This scene")).on_hover_text(tr!("The current scene and every symbol in it")); + ui.selectable_value(&mut app.find.document, true, tr!("The whole document")).on_hover_text(tr!("Every scene, and every symbol in the Library")); + }) + .response + .set_name(tr!("Where to search")); + }); + ui.add_space(4.0); + let enter = query_rows(app, ui); + // Options and where to look. + match app.find.kind { + Kind::Text => { + ui.horizontal_wrapped(|ui| { + ui.checkbox(&mut app.find.opts.match_case, tr!("Match case")); + ui.checkbox(&mut app.find.opts.whole_word, tr!("Whole word")); + ui.checkbox(&mut app.find.opts.regex, tr!("Regular expression")).on_hover_text(tr!("A pattern such as h.llo or \\d+ (Rust regex syntax; runs in linear time)")); + }); + ui.horizontal_wrapped(|ui| { + ui.label(text(Type::Label, tr!("Look in"))); + let w = &mut app.find.within; + ui.checkbox(&mut w.text, tr!("Text fields")); + ui.checkbox(&mut w.labels, tr!("Frame labels")); + ui.checkbox(&mut w.layers, tr!("Layer names")); + ui.checkbox(&mut w.instances, tr!("Instance names")); + ui.checkbox(&mut w.scripts, tr!("Scripts")); + }); + } + Kind::Color => { + ui.horizontal_wrapped(|ui| { + ui.label(text(Type::Label, tr!("Look in"))); + let w = &mut app.find.within; + ui.checkbox(&mut w.fills, tr!("Fills")); + ui.checkbox(&mut w.strokes, tr!("Strokes")); + ui.checkbox(&mut w.text_color, tr!("Text")); + }); + } + _ => {} + } + ui.add_space(4.0); + let list = hits(app); + let (err, truncated) = match results(app) { + Some(Err(e)) => (Some(e.clone()), false), + Some(Ok((_, t))) => (None, *t), + None => (None, false), + }; + // The buttons: Find Next first (Enter in the Find field), then Replace and Replace All. + let any = !list.is_empty(); + let next = |k: &str| app.keymap.primary(k).map(crate::platform::shortcut_label).unwrap_or_default(); + let (next_key, prev_key) = (next("view.find_next"), next("view.find_prev")); + ui.horizontal(|ui| { + if ui.add_enabled(any, egui::Button::new(tr!("Find Next"))).on_hover_text(a11y::with_key(tr!("Go to the next result"), Some(&next_key))).clicked() || (enter && any) { + step(app, true); + } + if ui.add_enabled(any, egui::Button::new(tr!("Find Previous"))).on_hover_text(a11y::with_key(tr!("Go to the previous result"), Some(&prev_key))).clicked() { + step(app, false); + } + if ui.add_enabled(any, egui::Button::new(tr!("Replace"))).on_hover_text(tr!("Replace the current result, then go to the next")).clicked() { + replace_one(app); + } + if ui.add_enabled(any, egui::Button::new(tr!("Replace All"))).on_hover_text(tr!("Replace every result, as one step you can undo")).clicked() { + let p = app.find.params(); + app.request("find.replace", p); + } + }); + ui.add_space(4.0); + // What was found. + if let Some(e) = err { + ui.label(text(Type::Caption, e).color(T.error)); + return; + } + if !app.find.ready() { + ui.label(text(Type::Caption, match app.find.kind { + Kind::Text => tr!("Type what to find: results show as you type."), + Kind::Font => tr!("Choose a font the document's text uses."), + _ => tr!("Choose a Library item."), + })); + return; + } + let summary = if list.is_empty() { + tr!("Nothing found").to_string() + } else if truncated { + trn!("The first {n} result", "The first {n} results", list.len()) + } else { + trn!("{n} result", "{n} results", list.len()) + }; + ui.label(text(Type::Caption, summary)); + results_list(app, ui, &list); +} + +/// The results, only the rows in view drawn (a search can find 100,000 places). +fn results_list(app: &mut App, ui: &mut egui::Ui, list: &[Hit]) { + let mut clicked = None; + let current = app.find.current; + let kind = app.find.kind; + egui::ScrollArea::vertical().id_salt("find_results").max_height(260.0).min_scrolled_height(TARGET * 6.0).auto_shrink([false, true]).show_rows(ui, TARGET, list.len(), |ui, range| { + for i in range { + let Some(h) = list.get(i) else { continue }; + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click()); + let p = ui.painter(); + let on = current == Some(i); + if on || resp.hovered() { + p.rect_filled(r, T.rc(), if on { T.accent_dim } else { T.hover }); + } + if on { + p.rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent); + } + // What was found (the text around a match), then where. + let what = match kind { + Kind::Text => h.context.clone(), + _ => h.found.clone(), + }; + let field = crate::i18n::t(field_label(h.field)); + let place = location(app, h); + let half = r.width() * 0.5; + let left = Rect::from_min_max(pos2(r.left() + 8.0, r.top()), pos2(r.left() + half, r.bottom())); + let right = Rect::from_min_max(pos2(r.left() + half + 6.0, r.top()), pos2(r.right() - 6.0, r.bottom())); + let g = p.layout_no_wrap(what.clone(), font(Type::Body), color(Type::Body)); + p.with_clip_rect(left.intersect(ui.clip_rect())).galley(pos2(left.left(), r.center().y - g.rect.height() / 2.0), g, color(Type::Body)); + let label = format!("{field} · {place}"); + p.with_clip_rect(right.intersect(ui.clip_rect())).text(pos2(right.left(), r.center().y), Align2::LEFT_CENTER, &label, font(Type::Caption), color(Type::Caption)); + let name = tr!("{what}, {field}, {place}", what = what, field = field, place = place); + a11y::control(ui, &resp, WidgetType::SelectableLabel, &name, Some(on)); + if resp.on_hover_text(&name).clicked() { + clicked = Some(i); + } + } + }); + if let Some(i) = clicked { + go(app, i, list); + } +} diff --git a/src/guidelines_tests.rs b/src/guidelines_tests.rs index 02dc4682..29e418af 100644 --- a/src/guidelines_tests.rs +++ b/src/guidelines_tests.rs @@ -1,6 +1,6 @@ //! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values. -const SOURCES: [(&str, &str); 20] = [ +const SOURCES: [(&str, &str); 22] = [ ("actions_panel.rs", include_str!("actions_panel.rs")), ("test_movie.rs", include_str!("test_movie.rs")), ("autosave.rs", include_str!("autosave.rs")), @@ -20,6 +20,8 @@ const SOURCES: [(&str, &str); 20] = [ ("motion_editor.rs", include_str!("motion_editor.rs")), ("shape_hints.rs", include_str!("shape_hints.rs")), ("bone_tool.rs", include_str!("bone_tool.rs")), + ("find_panel.rs", include_str!("find_panel.rs")), + ("movie_explorer.rs", include_str!("movie_explorer.rs")), ("main.rs", ""), ]; diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 971a0377..7a10cfee 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -578,7 +578,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("symbol.set_kind", serde_json::json!({"symbol": symbol, "kind": "movie_clip"})); a.run("element.set_filters", serde_json::json!({"filters": [{"type": "drop_shadow"}, {"type": "gradient_glow"}]})); })); - for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol"] { + for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] { diff --git a/src/keymap.rs b/src/keymap.rs index 56184e70..960975f0 100644 --- a/src/keymap.rs +++ b/src/keymap.rs @@ -81,6 +81,9 @@ fn view_label(id: &str) -> &'static str { "view.next_panel" => tr_noop!("Next Panel"), "view.prev_panel" => tr_noop!("Previous Panel"), "view.actions" => tr_noop!("Actions Panel"), + "view.find_next" => tr_noop!("Find Next"), + "view.find_prev" => tr_noop!("Find Previous"), + "view.movie_explorer" => tr_noop!("Movie Explorer"), "view.brush_smaller" => tr_noop!("Brush Size Down"), "view.brush_larger" => tr_noop!("Brush Size Up"), _ => tr_noop!("View action"), diff --git a/src/main.rs b/src/main.rs index f2746514..08014ac3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,6 +27,7 @@ mod app; mod autosave; mod brushtool; mod envelope; +mod find_panel; mod erasertool; mod bone_tool; mod camera_tool; @@ -39,6 +40,7 @@ mod library; mod menus; mod mixed; mod motion_editor; +mod movie_explorer; mod panels; mod motion_path; mod onion; diff --git a/src/menus.rs b/src/menus.rs index 5eda634a..d4fb04d0 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -261,11 +261,18 @@ pub(crate) fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: & if ui_item(ui, tr!("Actions"), app.keymap.primary("view.actions").unwrap_or(""), Some(app.show_actions)) { app.show_actions = !app.show_actions; } + use crate::movie_explorer::DockTab; + if ui_item(ui, tr!("Library"), "", Some(app.explorer.tab == DockTab::Library)) { + app.explorer.tab = DockTab::Library; + } + if ui_item(ui, tr!("Movie Explorer"), app.keymap.primary("view.movie_explorer").unwrap_or(""), Some(app.explorer.tab == DockTab::Explorer)) { + crate::movie_explorer::open(app); + } ui.separator(); if ui_item(ui, tr!("Onion Skin"), "", Some(app.onion.ghosts)) { crate::onion::toggle_ghosts(app); } - ui.label(text(Type::Caption, tr!("Panels are docked: Tools, Stage, Timeline, Properties, Library"))); + ui.label(text(Type::Caption, tr!("Panels are docked: Tools, Stage, Timeline, Properties, Library and Movie Explorer"))); } "Help" => { if ui_item(ui, tr!("Command Palette…"), "Ctrl+K", None) { diff --git a/src/movie_explorer.rs b/src/movie_explorer.rs new file mode 100644 index 00000000..baf9501a --- /dev/null +++ b/src/movie_explorer.rs @@ -0,0 +1,314 @@ +//! Window › Movie Explorer (ADR 0058), a tab of the Library's dock: the movie as a tree of +//! scenes, layers, keyframes and what is on them, instances opening into their symbols, and the +//! Library's symbol definitions. The Show buttons hide kinds of rows; the search keeps matching +//! rows with the rows above them. A double-click (or Enter) goes there with `find.goto`, opening +//! symbols in place as a double-click on the stage does (ADR 0045). The tree comes from +//! `explorer::tree` (what `explorer.tree` pages for scripts), made again only when the document +//! or the view changes; the list draws only the rows in view. + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::icons::{self, Icon}; +use crate::theme::{T, TARGET, Type, color, font, text}; +use anicraft_engine::StateId; +use anicraft_engine::doc::{LayerKind, SymbolKind}; +use anicraft_engine::explorer::{self, NodeKind, Options, Row, Show, Tree}; +use anicraft_engine::find::Scope; +use egui::{Key, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; +use std::collections::HashSet; +use std::sync::Arc; + +/// The tab the Library's dock shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum DockTab { + #[default] + Library, + Explorer, +} + +/// What the Movie Explorer shows and holds between frames (view state). +#[derive(Default)] +pub struct ExplorerView { + pub tab: DockTab, + pub show: ShowState, + /// Every scene (off: only the current one). + pub this_scene: bool, + pub hide_definitions: bool, + pub filter: String, + /// Open rows; `None` until a row is opened or closed (then: the top rows are open). + pub expanded: Option>, + /// The selected row, by key. + pub selected: Option, + /// Bumped when anything above changes, so the tree is made again. + rev: u64, + cache: Option<((StateId, usize, u64), Arc)>, +} + +/// The Show menu's kinds, kept as the engine's [`Show`] (all on to start). +#[derive(Default)] +pub struct ShowState(pub Show); + +impl ExplorerView { + fn options(&self) -> Options { + Options { + scope: if self.this_scene { Scope::Scene } else { Scope::Document }, + show: self.show.0, + definitions: !self.hide_definitions, + expanded: self.expanded.clone(), + all: false, + filter: self.filter.clone(), + } + } + + fn changed(&mut self) { + self.rev += 1; + } + + /// Opens or closes `row`. + fn toggle(&mut self, rows: &[Row], key: &str) { + let set = self.expanded.get_or_insert_with(|| rows.iter().filter(|r| r.open).map(|r| r.key.clone()).collect()); + if !set.remove(key) { + set.insert(key.to_string()); + } + self.changed(); + } +} + +/// The tree for the current view, made again only when the document or the view changed. +fn tree(app: &mut App) -> Arc { + let key = (app.s.state, app.s.scene, app.explorer.rev); + if let Some((k, t)) = &app.explorer.cache + && *k == key + { + return t.clone(); + } + let t = Arc::new(explorer::tree(&app.s.doc, app.s.scene, &app.explorer.options())); + app.explorer.cache = Some((key, t.clone())); + t +} + +/// Window › Movie Explorer: the dock shows it (its band unfolded). +pub fn open(app: &mut App) { + app.explorer.tab = DockTab::Explorer; + app.explorer.changed(); +} + +/// Opens every row above `depth` (screenshots). +pub fn expand_to(app: &mut App, depth: usize) { + let all = explorer::tree(&app.s.doc, app.s.scene, &Options { all: true, ..app.explorer.options() }); + app.explorer.expanded = Some(all.rows.iter().filter(|r| r.depth < depth && r.children).map(|r| r.key.clone()).collect()); + app.explorer.changed(); +} + +/// The tab strip at the top of the dock band: Library, Movie Explorer. +pub fn tabs(app: &mut App, ui: &mut egui::Ui) { + ui.horizontal(|ui| { + for (tab, label) in [(DockTab::Library, tr!("Library")), (DockTab::Explorer, tr!("Movie Explorer"))] { + if ui.selectable_label(app.explorer.tab == tab, label).clicked() { + app.explorer.tab = tab; + } + } + }); + ui.add_space(4.0); +} + +fn kind_name(k: NodeKind) -> &'static str { + match k { + NodeKind::Scene => tr_noop!("Scene"), + NodeKind::Definitions => tr_noop!("Symbol definitions"), + NodeKind::Symbol(SymbolKind::Graphic) | NodeKind::Instance(SymbolKind::Graphic) => tr_noop!("Graphic"), + NodeKind::Symbol(SymbolKind::MovieClip) | NodeKind::Instance(SymbolKind::MovieClip) => tr_noop!("Movie clip"), + NodeKind::Symbol(SymbolKind::Button) | NodeKind::Instance(SymbolKind::Button) => tr_noop!("Button"), + NodeKind::Layer(LayerKind::Folder) => tr_noop!("Folder"), + NodeKind::Layer(LayerKind::Mask) => tr_noop!("Mask layer"), + NodeKind::Layer(LayerKind::Guide) => tr_noop!("Guide layer"), + NodeKind::Layer(LayerKind::Camera) => tr_noop!("Camera layer"), + NodeKind::Layer(LayerKind::Armature) => tr_noop!("Armature layer"), + NodeKind::Layer(LayerKind::Normal) => tr_noop!("Layer"), + NodeKind::Frame => tr_noop!("Keyframe"), + NodeKind::Script => tr_noop!("Frame script"), + NodeKind::Handler => tr_noop!("Actions"), + NodeKind::Sound => tr_noop!("Sound"), + NodeKind::Text => tr_noop!("Text"), + NodeKind::Bitmap => tr_noop!("Bitmap"), + } +} + +/// What a row says: its document text, or for rows without a name what they are. +fn row_text(r: &Row) -> String { + match r.kind { + NodeKind::Definitions => crate::i18n::t(kind_name(r.kind)).to_string(), + NodeKind::Frame => match (r.frame, r.name.is_empty()) { + // The label is document text, as written. + (Some(f), false) => tr!("Frame {frame}: {label}", frame = f + 1, label = r.name), + (Some(f), true) => tr!("Frame {frame}", frame = f + 1), + _ => crate::i18n::t(kind_name(r.kind)).to_string(), + }, + NodeKind::Handler => { + let event = anicraft_engine::doc::actions::ButtonEvent::ALL.iter().find(|e| e.key() == r.name).map_or(r.name.as_str(), |e| crate::i18n::t(e.label())); + tr!("On {event}: {actions}", event = event, actions = r.extra) + } + NodeKind::Instance(_) if !r.extra.is_empty() => tr!("{instance} ({symbol})", instance = r.extra, symbol = r.name), + NodeKind::Bitmap if !r.extra.is_empty() => tr!("{instance} ({bitmap})", instance = r.extra, bitmap = r.name), + _ if r.name.is_empty() => crate::i18n::t(kind_name(r.kind)).to_string(), + _ => r.name.clone(), + } +} + +/// The row's marker: the Library's symbol square, or the icon the timeline uses. +fn marker(p: &egui::Painter, at: Rect, k: NodeKind, c: egui::Color32) { + let symbol = |kind: SymbolKind| match kind { + SymbolKind::Graphic => T.kind_graphic, + SymbolKind::MovieClip => T.kind_movie_clip, + SymbolKind::Button => T.kind_button, + }; + match k { + NodeKind::Symbol(s) | NodeKind::Instance(s) => { + let r = at.shrink(1.0); + p.rect_stroke(r, 2.0, Stroke::new(1.5, symbol(s)), StrokeKind::Inside); + p.circle_filled(r.center(), 2.5, symbol(s)); + } + NodeKind::Scene => icons::paint(p, at, Icon::Play, c), + NodeKind::Definitions => icons::paint(p, at, Icon::Folder, c), + NodeKind::Layer(LayerKind::Folder) => icons::paint(p, at, Icon::Folder, c), + NodeKind::Layer(LayerKind::Mask) => icons::paint(p, at, Icon::Mask, c), + NodeKind::Layer(LayerKind::Guide) => icons::paint(p, at, Icon::Guide, c), + NodeKind::Layer(LayerKind::Camera) => icons::paint(p, at, Icon::Camera, c), + NodeKind::Layer(LayerKind::Armature) => icons::paint(p, at, Icon::Bone, c), + NodeKind::Layer(LayerKind::Normal) => { + p.rect_stroke(at.shrink(2.0), 1.0, Stroke::new(1.2, c), StrokeKind::Inside); + } + NodeKind::Frame => { + p.circle_filled(at.center(), 3.0, c); + } + NodeKind::Script | NodeKind::Handler => { + p.text(at.center(), egui::Align2::CENTER_CENTER, "{ }", font(Type::DataSmall), T.accent_text); + } + NodeKind::Sound => icons::paint(p, at, Icon::Sound, c), + NodeKind::Text => icons::paint(p, at, Icon::Type, c), + NodeKind::Bitmap => icons::paint(p, at, Icon::Image, c), + } +} + +pub fn panel(app: &mut App, ui: &mut egui::Ui) { + // The search, and the Show menu: kinds of rows, which scenes, the Library's symbols. + ui.horizontal(|ui| { + let menu_w = 72.0; + let search = ui.add(egui::TextEdit::singleline(&mut app.explorer.filter).hint_text(tr!("Search")).desired_width((ui.available_width() - menu_w).max(80.0))); + search.set_name(tr!("Search the Movie Explorer")); + if search.changed() { + app.explorer.changed(); + } + let menu = ui.menu_button(tr!("Show"), |ui| { + let mut changed = false; + let s = &mut app.explorer.show.0; + for (on, label, tip) in [ + (&mut s.text, tr!("Text"), tr!("Text fields")), + (&mut s.symbols, tr!("Symbols"), tr!("Buttons, movie clips and graphics")), + (&mut s.scripts, tr!("Scripts"), tr!("Frame scripts and instance actions")), + (&mut s.media, tr!("Sounds and bitmaps"), tr!("Sounds on keyframes, and bitmaps")), + (&mut s.frames, tr!("Layers and frames"), tr!("Off: what is on them, straight under the scene")), + ] { + changed |= ui.checkbox(on, label).on_hover_text(tip).changed(); + } + ui.separator(); + changed |= ui.radio_value(&mut app.explorer.this_scene, false, tr!("All scenes")).changed(); + changed |= ui.radio_value(&mut app.explorer.this_scene, true, tr!("This scene")).changed(); + ui.separator(); + let mut defs = !app.explorer.hide_definitions; + if ui.checkbox(&mut defs, tr!("Symbol definitions")).on_hover_text(tr!("Every symbol in the Library, with what is inside it")).changed() { + app.explorer.hide_definitions = !defs; + changed = true; + } + if changed { + app.explorer.changed(); + } + }); + menu.response.on_hover_text(tr!("What the Movie Explorer shows")).set_name(tr!("Show in the Movie Explorer")); + }); + ui.add_space(4.0); + let t = tree(app); + if t.rows.is_empty() { + ui.label(text(Type::Caption, if app.explorer.filter.trim().is_empty() { tr!("Nothing to show: turn on more Show buttons.") } else { tr!("Nothing matches the search.") })); + return; + } + let summary = if t.truncated { trn!("The first {n} row", "The first {n} rows", t.rows.len()) } else { trn!("{n} row", "{n} rows", t.rows.len()) }; + ui.label(text(Type::Caption, summary)); + list(app, ui, &t); +} + +/// The rows, only those in view drawn. +fn list(app: &mut App, ui: &mut egui::Ui, t: &Tree) { + let mut toggle: Option = None; + let mut select: Option = None; + let mut go: Option = None; + let room = (ui.available_height() - 8.0).clamp(140.0, 320.0); + let filtering = !app.explorer.filter.trim().is_empty(); + egui::ScrollArea::vertical().id_salt("explorer_rows").max_height(room).auto_shrink([false, true]).show_rows(ui, TARGET, t.rows.len(), |ui, range| { + for i in range { + let Some(r) = t.rows.get(i) else { continue }; + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click()); + let on = app.explorer.selected.as_deref() == Some(r.key.as_str()); + let p = ui.painter(); + if on || resp.hovered() { + p.rect_filled(rect, T.rc(), if on { T.accent_dim } else { T.hover }); + } + if on { + p.rect_filled(Rect::from_min_size(rect.left_top(), vec2(3.0, rect.height())), 0.0, T.accent); + } + let indent = 6.0 + r.depth.min(24) as f32 * 14.0; + let chevron = Rect::from_center_size(pos2(rect.left() + indent + 6.0, rect.center().y), vec2(12.0, 12.0)); + let icon = Rect::from_center_size(pos2(rect.left() + indent + 22.0, rect.center().y), vec2(14.0, 14.0)); + if r.children && !filtering { + icons::paint(p, chevron, if r.open { Icon::ChevronDown } else { Icon::ChevronRight }, T.icon); + } + marker(p, icon, r.kind, color(Type::Body)); + let label = row_text(r); + let name_rect = Rect::from_min_max(pos2(icon.right() + 8.0, rect.top()), rect.max); + let g = p.layout_no_wrap(label.clone(), font(Type::Body), color(Type::Body)); + p.with_clip_rect(name_rect.intersect(ui.clip_rect())).galley(pos2(name_rect.left(), rect.center().y - g.rect.height() / 2.0), g, color(Type::Body)); + let kind = crate::i18n::t(kind_name(r.kind)); + let name = match (r.children && !filtering, r.open) { + (true, true) => tr!("{kind}: {row}, open", kind = kind, row = label), + (true, false) => tr!("{kind}: {row}, closed", kind = kind, row = label), + _ => tr!("{kind}: {row}", kind = kind, row = label), + }; + a11y::control(ui, &resp, WidgetType::SelectableLabel, &name, Some(on)); + let resp = resp.on_hover_text(tr!("{row}\nDouble-click to go there", row = name)); + if resp.clicked() { + let on_chevron = ui.input(|inp| inp.pointer.interact_pos()).is_some_and(|q| q.x < icon.left()); + if on_chevron && r.children && !filtering { + toggle = Some(r.key.clone()); + } + select = Some(r.key.clone()); + } + if resp.double_clicked() { + go = Some(i); + } + if resp.has_focus() && ui.input(|inp| inp.key_pressed(Key::Enter)) { + go = Some(i); + } + } + }); + if let Some(k) = select { + app.explorer.selected = Some(k); + } + if let Some(k) = toggle { + app.explorer.toggle(&t.rows, &k); + } + if let Some(r) = go.and_then(|i| t.rows.get(i)) { + goto(app, r); + } +} + +/// Goes where row `r` is. +fn goto(app: &mut App, r: &Row) { + app.explorer.selected = Some(r.key.clone()); + if r.kind == NodeKind::Definitions { + return; + } + app.playing = false; + if app.run("find.goto", r.go.to_json()).is_some() { + app.status_ok(tr!("Went to {row}", row = row_text(r))); + } +} diff --git a/src/panels.rs b/src/panels.rs index 82b3e487..53037eae 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -326,7 +326,9 @@ pub fn right(app: &mut App, ui: &mut egui::Ui) { let h = ui.available_height(); let dock = ui.max_rect(); // Dock sections are layout bands; each folds away to give the others room. - let props = egui::ScrollArea::vertical().id_salt("props").max_height(h * 0.56).auto_shrink([false, true]).show(ui, |ui| { + // The Movie Explorer's tree needs room: Properties gives some up while it shows. + let props_share = if app.explorer.tab == crate::movie_explorer::DockTab::Explorer { 0.4 } else { 0.56 }; + let props = egui::ScrollArea::vertical().id_salt("props").max_height(h * props_share).auto_shrink([false, true]).show(ui, |ui| { crate::theme::section_with_header(ui, "dock_properties", Section::Band, tr!("Properties"), None, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| properties(app, ui)); }) @@ -338,13 +340,21 @@ pub fn right(app: &mut App, ui: &mut egui::Ui) { // Ctrl+F6 lands on the Properties and Library headers; each panel owns the dock down to the // next one (Align goes with Properties, History with the Library). let split = ui.cursor().top(); - let (library_header, _) = crate::theme::section_with_header(ui, "dock_library", Section::Band, tr!("Library"), None, |ui| { + // The Library and the Movie Explorer share the band, as tabs (ADR 0058). + let explorer = app.explorer.tab == crate::movie_explorer::DockTab::Explorer; + let title = if explorer { tr!("Movie Explorer") } else { tr!("Library") }; + let (library_header, _) = crate::theme::section_with_header(ui, "dock_library", Section::Band, title, None, |ui| { // The Library scrolls on its own, so a short window still reaches every row (History's // header stays below it). let room = (ui.available_height() - 48.0).max(120.0); - egui::ScrollArea::vertical().id_salt("library_dock").max_height(room).auto_shrink([false, true]).show(ui, |ui| { - egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, ui)); - }); + egui::Frame::NONE.inner_margin(egui::Margin { left: 12, right: 12, top: 8, bottom: 0 }).show(ui, |ui| crate::movie_explorer::tabs(app, ui)); + if explorer { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 4)).show(ui, |ui| crate::movie_explorer::panel(app, ui)); + } else { + egui::ScrollArea::vertical().id_salt("library_dock").max_height(room).auto_shrink([false, true]).show(ui, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, ui)); + }); + } }); section(ui, "dock_history", Section::Band, tr!("History"), None, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| history(app, ui)); From e81770b4038780d0f49ad822a25598be6a293eb3 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:19:10 -0700 Subject: [PATCH 037/192] docs: ADR 0058, roadmap, changelog and compliance for Find and Replace and the Movie Explorer (M8) --- CHANGELOG.md | 19 +++ ...058-find-and-replace-and-movie-explorer.md | 142 ++++++++++++++++++ docs/adr/README.md | 1 - docs/legal/compliance.md | 7 + docs/roadmap.md | 5 +- 5 files changed, 171 insertions(+), 3 deletions(-) create mode 100644 docs/adr/0058-find-and-replace-and-movie-explorer.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b7b22d2..0f39d475 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ ## Unreleased +* **Find and Replace, and the Movie Explorer** (ADR 0058, M8). + * **Edit › Find and Replace** (Ctrl+F) is a window that stays open while you work. It finds + text in text fields, frame labels, layer names, instance names and frame scripts, with + match case, whole word and regular expressions. It also finds fonts, colours (fills, + gradient stops, strokes, text), symbols, sounds and bitmaps. It searches this scene and + the symbols in it, or the whole document. Results show as you type. + * Click a result, or press **Find Next** (F3) or Find Previous (Shift+F3), to go there: the + scene, the frame and the item selected. A symbol opens in place through the instances + that lead to it. + * **Replace** replaces the current result and goes on to the next. **Replace All** is one + undo step and asks first above 100 places. Replaced text is laid out again, colours keep + their transparency, and a symbol is never put inside itself. + * **Window › Movie Explorer** (Alt+F3) is a tab next to the Library. It shows scenes › + layers › keyframes › instances, text, sounds, bitmaps and scripts, each instance opening + into its symbol, plus the Library's symbol definitions. A Show menu filters it by kind + and a search keeps matching rows. Double-click a row to go there. + * Both lists draw only the rows in view, so movies with 100,000 rows stay smooth. + * Headless: `find.search`, `find.replace`, `find.goto` and `explorer.tree` (paged). + Patterns use a linear-time engine with size limits. * **9-slice scaling for symbols** (ADR 0055, M2). * **Enable guides for 9-slice scaling** on a symbol, in the Library's item properties or in Properties. A scaled instance then keeps its corners unscaled, stretches its edges one way diff --git a/docs/adr/0058-find-and-replace-and-movie-explorer.md b/docs/adr/0058-find-and-replace-and-movie-explorer.md new file mode 100644 index 00000000..dcb6259a --- /dev/null +++ b/docs/adr/0058-find-and-replace-and-movie-explorer.md @@ -0,0 +1,142 @@ +# ADR 0058: Find and Replace, and the Movie Explorer + +* Status: accepted (2026-11-11) +* Relates to: ADR 0004 (destructive actions), ADR 0017 (plug-in policy), ADR 0022 + (accessibility), ADR 0040 (interface languages), ADR 0045 (editing a symbol in place) + +## Context + +Animate users who work on big files rely on two tools to get around them. **Edit › Find and +Replace** finds text (in text fields, frame labels, layer names, instance names and scripts), +fonts, colours, symbols, sounds and bitmaps, in the current scene or the whole document. It +can replace one result or all of them, and Find Next goes to the frame and selects the item. +The **Movie Explorer** shows the movie as a tree of scenes, layers, frames and what is on +them, and of symbols inside instances. Show buttons filter it by kind. A double-click goes +there. + +Behaviour was learned from Adobe's public help pages and from using the tools. No Adobe code, +SDK or asset was used. + +## Decision + +1. **Three commands and a query, in the engine** (`crates/engine/src/find.rs`). Everything + works headless, over the CLI and MCP. The shell uses the same functions. + * `find.search {kind, text | font | color | symbol | sound | bitmap, match_case?, + whole_word?, regex?, in?, scope?, offset?, limit?}` lists **located hits**. Each hit + has the timeline (`scene` index or `symbol` id), `layer`, `frame` (the keyframe's + start; none for a layer name), `element`, `field` (`text`, `label`, `layer_name`, + `instance_name`, `script`, `font`, `fill`, `stroke`, `text_color`, `instance`, `sound`, + `bitmap`), the match's characters (`start..end`), what was found and the text around + it. Pages hold up to 10,000 hits, and one search keeps at most 100,000 (`truncated`). + * **Scope.** `scene` (the default, as in Animate) is the current scene plus every symbol + it uses, however deep. `document` is every scene and every Library symbol, used or not. + * **Colours** match on 8-bit RGB; alpha is ignored. They cover solid fills, gradient + stops, strokes and text colour. A replacement keeps each place's alpha, so a + half-transparent red becomes a half-transparent green. + * **Fonts** match the family name, ignoring case and surrounding spaces. + * `find.replace {query, with, at?}`. With `at` (a hit as `find.search` returned it), + it replaces that one match (Replace). Without it, it replaces every hit (Replace All). + Either way it is **one undo step**, because it is one mutating command. Text in a text + field, or a new font, is laid out again with this computer's fonts. A font that isn't + installed falls back to another, and the result says so in `notes`. Some places are + skipped, and the result says why: a text field or layer name left empty, a script over + 1 MiB, or an instance that would put a symbol inside itself. An instance of `to` can't go + into `to` or into any symbol `to` uses. When nothing could be replaced, the command + fails and records nothing. + * **Confirmation (ADR 0004).** Replace All over more than 100 places (`REPLACE_ASK`) asks + first in the editor. The confirmation is undoable-tier (`irreversible: false`), so a + script runs it directly, and "don't ask again" works. + * `find.goto {layer?, scene?, symbol?, path?, frame?, element?}` goes to a place. It + closes any open symbols and finds the layer's timeline (layer ids are unique in a + document). A scene is switched to. A symbol is **opened in place through the instances + that lead to it**: the `path` given (the Movie Explorer knows it), or else the shortest + chain from the current scene, then from any scene, found breadth-first, each symbol + visited once. It falls back to opening the symbol alone from the Library, as a + double-click in the Library does. That happens when no instance leads there, or when + one is on a hidden or locked layer. It then picks the layer and frame and selects the + element. Going somewhere records nothing to undo. + +2. **A bounded pattern engine.** Text matching uses the `regex` crate (MIT OR Apache-2.0, + crates.io). Its engines run in time linear in the text. Patterns that would compile past + 1 MiB (`size_limit`, `dfa_size_limit`), or nest deeper than 64, are refused with a + message. So `(a+)+$` over 50,000 characters returns at once, and `a{1000}{1000}` is + refused. Plain text, whole words (`\b(?:…)\b`) and match case are the same engine, with + the text escaped. Empty matches are never hits, so `x*` doesn't match every gap. Only the + `std`, `perf`, `unicode-case` and `unicode-perl` features are built: case folding and + word boundaries work for any language, without the other Unicode tables. In + regular-expression mode `$1` and `${name}` in the replacement put back groups. In plain + mode the replacement is used exactly as typed. + +3. **The Movie Explorer tree** (`crates/engine/src/explorer.rs`, `explorer.tree`). The rows + that are showing come in order, each with a depth, a kind, document text (a name, a + label, a text field's first line, a script's first line), whether it has children and + whether it is open, and a stable **key** (`s0/l12/k0/e40/…`, a path of ids) that open + rows are remembered by. + * Scenes › layers (folder nesting as indentation; a closed folder hides its layers) › + keyframes that hold something (named by their label) › the frame script, the sound, + symbol instances, text fields and bitmaps. Plain shapes aren't listed, as in Animate. + An instance opens into its symbol's own layers. Under a separate row, the **symbol + definitions** list every Library symbol, each opening into its timeline. + * **Only open rows' children are made.** So the work follows what is shown, and a + closed tree of a huge movie costs almost nothing. Limits: 200,000 rows (`truncated`) + and 48 levels. A symbol already on the way down isn't entered again, so a symbol that + holds itself, or two that hold each other, stops. + * **Show filters**, as Animate's Show buttons: text, symbols, scripts, media (sounds and + bitmaps), and frames. With frames off, layers and keyframes are left out, and what is + on them is listed straight under the scene or the instance. The **text filter** looks + through every row, as if all were open, and keeps the rows whose name holds it, with + every row above them. + * Every row carries its `find.goto` params (`go`). Rows inside instances carry the + instance path, so a double-click opens the symbols in place. Rows under a definition + open that symbol alone first, then follow the path. + +4. **The shell** (`src/find_panel.rs`, `src/movie_explorer.rs`). + * **Find and Replace** is a non-modal window: Edit › Find and Replace, Ctrl+F (⌘F), + from the registry. It has a kind, a scope, a Find and a Replace with field (or a font + list, colour wells or Library lists), the text options, and where to look. Results are + listed **as you type**. The search runs again only when the query or the document + changes; on 24,000 elements it takes under 10 ms. Clicking a result, Find Next (F3, or + Enter in the Find field) and Find Previous (Shift+F3) go there. Replace replaces the + current result and goes on to the next. Replace All goes through `App::request`, so the + confirmation shows when it applies. Bad patterns are reported in the window, not in a + dialog. + * **Movie Explorer** is the other tab of the Library's dock band (Window › Movie + Explorer, Alt+F3). The band's title follows the tab, and Properties gives up some + height while the explorer shows. It has a search field and a Show menu (the kinds, all + scenes or this scene, symbol definitions). A click on the chevron opens or closes a + row, and a double-click or Enter goes there. The tree is made again only when the + document or the view changes. + * Both lists draw **only the rows in view** (`ScrollArea::show_rows`), so 100,000 rows + scroll as smoothly as ten. Every row is named for screen readers: what it is, its + text, and whether it is open or closed (ADR 0022). Every string goes through `tr!` + (ADR 0040). Document text (names, labels, found text) is shown as written. + +5. **Plug-ins** may call `find.*` and `explorer.*` (`plugin_may_call`). These commands read + the document or edit it through the same undo path as every document command. + +## Consequences + +* An artist can rename a character across 60 scenes, swap a font, recolour a palette or swap + a symbol, sound or bitmap everywhere in one step. Undo takes it all back. +* An agent over MCP can locate things (`find.search`), walk the tree page by page + (`explorer.tree`) and go to any place (`find.goto`) without knowing the timeline's layout. +* Measured (dev profile, `cargo test -- --nocapture`). On 40 layers × 300 keyframes + (12,000 text fields and 12,000 shapes) plus 500 symbols: a whole-word text search takes + 8.8 ms, a colour search 3.5 ms, and Replace All of 12,500 colours 25.5 ms, with its undo + 7.4 ms. The Movie Explorer on 100 layers × 120 keyframes, each with a text and an instance + of a 3-layer symbol: everything open (144,112 rows) in 45 ms, the top rows (103) in + 0.08 ms, and a filtered tree in 67 ms. +* `regex` and its `regex-syntax`, `regex-automata` and `aho-corasick` crates are new in the + tree. They are MIT OR Apache-2.0 (aho-corasick Unlicense OR MIT), so no new licence. + +## Not in this slice + +* Searching inside ActionScript string literals separately from code, and in action + parameters (instance actions are listed in the Movie Explorer, not searched). +* Find by font size or style, and colour tolerance. Replacing a font keeps size and style. +* Video items (there are none yet), and editing names in place in the Movie Explorer. + Animate's Movie Explorer can rename; here the Library and the timeline do that. +* The Movie Explorer's "Show movie elements" options for the stage selection, and copying + the tree as text. +* Highlighting the match inside each result's text, and keeping the Find window's last + query between sessions. diff --git a/docs/adr/README.md b/docs/adr/README.md index ed3d9110..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0058 | M8 track: find and replace, Movie Explorer | Find and Replace, Movie Explorer | diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index 438cdc64..78020825 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -50,6 +50,13 @@ cargo deny check advisories # RustSec security advisories (needs ne user's own files: AniCraft ships none in the binary; the sample plug-ins are source under `examples/plugins` (MIT OR Apache-2.0). +### Find and Replace (2026-11-11, ADR 0058) + +New crates, from crates.io: `regex` 1 with `regex-syntax` and `regex-automata` (MIT OR +Apache-2.0) and `aho-corasick` (Unlicense OR MIT), built with only the `std`, `perf`, +`unicode-case` and `unicode-perl` features. They match Find and Replace's patterns in linear +time with size limits. No new licence. + ### Interface languages (2026-11-10, ADR 0040) New crate: `sys-locale` 0.3 (MIT OR Apache-2.0, crates.io), which reads the system's interface diff --git a/docs/roadmap.md b/docs/roadmap.md index 593b07f4..9c993367 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -18,6 +18,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported. Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | +| Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | | Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. | @@ -39,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | -| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. | +| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); documentation book. | ## Releases @@ -60,7 +61,7 @@ titled with its milestone. | M5 | Audio layers: import, waveform, playback sync | timeline, layers | | M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | -| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | +| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and ActionScript (on M6's plug-in host). From 39bcf2ac5a99d71baa316557e57902f40578b4a3 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:27:50 -0700 Subject: [PATCH 038/192] docs(adr): reserve 0059 for files from the desktop, recent files and the start screen (M8) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..6760c8e5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0059 | m8/files-and-start | Files from the desktop, recent files and a start screen | From 93308ee20c9f0b1436b4243a55457cbb2d6bd749 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:34:26 -0700 Subject: [PATCH 039/192] feat(engine): dropped files, recent files and their commands (M8) --- crates/engine/src/cmds_draw.rs | 2 +- crates/engine/src/cmds_drop.rs | 197 ++++++++++++++++ crates/engine/src/cmds_file.rs | 37 ++- crates/engine/src/cmds_library.rs | 2 +- crates/engine/src/cmds_plugin.rs | 1 + crates/engine/src/cmds_recent.rs | 363 ++++++++++++++++++++++++++++++ crates/engine/src/cmds_sound.rs | 2 +- crates/engine/src/confirm.rs | 2 +- crates/engine/src/drop_tests.rs | 215 ++++++++++++++++++ crates/engine/src/lib.rs | 13 ++ crates/engine/src/plugin_tests.rs | 2 +- 11 files changed, 824 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/cmds_drop.rs create mode 100644 crates/engine/src/cmds_recent.rs create mode 100644 crates/engine/src/drop_tests.rs diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index c447661a..d4189e53 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -911,7 +911,7 @@ const MAX_PLACE: usize = 1_000; /// does (ADR 0053): an instance of each symbol, a rectangle of each bitmap's size showing it, /// in the active layer's keyframe at the playhead, all selected; a sound goes onto that /// keyframe. One command, so one undo step however many items. -fn place(s: &mut Session, p: &Value) -> Result { +pub(crate) fn place(s: &mut Session, p: &Value) -> Result { let items: Vec = match p.get("items") { Some(list) => { let list = list.as_array().ok_or_else(|| EngineError::Param("param 'items' must be a list of {\"symbol\" | \"bitmap\" | \"sound\": id}".into()))?; diff --git a/crates/engine/src/cmds_drop.rs b/crates/engine/src/cmds_drop.rs new file mode 100644 index 00000000..aeb097b8 --- /dev/null +++ b/crates/engine/src/cmds_drop.rs @@ -0,0 +1,197 @@ +//! Files dropped onto the window (ADR 0059). What a file is, and where it was dropped, decide +//! what happens: documents open (`file.open`, which asks first over unsaved work); drawings, +//! images and sounds dropped on the stage go onto the active layer at the playhead at the drop +//! point, and dropped on the Library go into the Library (into the folder under the pointer). +//! The routing is a pure function the shell and tests share; `file.drop` does the import, so a +//! drop of several files is one undo step however many it brings in. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{FolderId, LibraryEntry, LibraryItem}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Most files one drop brings in. +pub const MAX_DROPPED: usize = 64; + +/// What a dropped file is, by its name (and, for an XFL folder, what is inside it). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropKind { + /// `.anicraft`, `.fla`, `.xfl` (or an XFL folder): opens as the document. + Document, + /// `.svg`. + Drawing, + /// `.png`, `.jpg`, `.jpeg`. + Image, + /// `.wav`, `.ogg`, `.mp3`. + Sound, + /// Anything else. + Unsupported, +} + +/// Where a file was dropped. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropTarget { + Stage, + Library, + /// Anywhere else on the window (panels, the timeline, the menu bar). + Window, +} + +/// What a drop does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropAction { + /// Open it as the document (`file.open`). + Open, + /// `file.drop` with `to: "stage"`. + ImportToStage, + /// `file.drop` with `to: "library"`. + ImportToLibrary, + /// Nothing; the message (English, translated where it is shown) says why. + Refuse(&'static str), +} + +pub fn kind_of(path: &Path) -> DropKind { + if crate::cmds_file::is_animate(path) { + return DropKind::Document; + } + let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + match ext.as_deref() { + Some("anicraft") => DropKind::Document, + Some("svg") => DropKind::Drawing, + Some("png" | "jpg" | "jpeg") => DropKind::Image, + _ if crate::cmds_sound::is_sound(path) => DropKind::Sound, + _ => DropKind::Unsupported, + } +} + +/// The message for a file AniCraft can't take. +pub const UNSUPPORTED: &str = "AniCraft opens .anicraft, .fla and .xfl documents, and imports SVG drawings, PNG and JPEG images, and WAV, Ogg and MP3 sounds"; + +/// What dropping a file of `kind` on `target` does. +pub fn route(kind: DropKind, target: DropTarget) -> DropAction { + match (kind, target) { + (DropKind::Document, _) => DropAction::Open, + (DropKind::Unsupported, _) => DropAction::Refuse(UNSUPPORTED), + (DropKind::Drawing, DropTarget::Library) => DropAction::Refuse("SVG drawings import to the stage: drop it there"), + (_, DropTarget::Library) => DropAction::ImportToLibrary, + (_, DropTarget::Stage) => DropAction::ImportToStage, + // Not over the stage or the Library: drop it on one of them. + (_, DropTarget::Window) => DropAction::Refuse("Drop drawings, images and sounds on the stage to place them, or on the Library to add them"), + } +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: "file.drop", + label: "Import Dropped Files", + menu: "", + shortcut: None, + params: "{paths: [..] (or path; SVG, PNG, JPEG, WAV, OGG, MP3; at most 64), to: stage | library, x?, y? (stage: the drop point in the edited space, default the stage centre), folder? (library: a folder id)} → {elements, items, layers}: on the stage each drawing, image and sound goes onto the active layer's keyframe at the playhead, centred on the drop point (a drawing with several layers or masks gets its own layers, as Import to Stage); in the Library images and sounds are added, into `folder`. One undo step", + mutates: true, + run: drop, + }] +} + +fn paths(p: &Value) -> Result> { + let list: Vec = match (p.get("paths"), opt_str(p, "path")?) { + (Some(v), None) => { + let a = v.as_array().ok_or_else(|| EngineError::Param("param 'paths' must be a list of file paths".into()))?; + a.iter().map(|x| x.as_str().map(PathBuf::from).ok_or_else(|| EngineError::Param("param 'paths' must be a list of file paths".into()))).collect::>()? + } + (None, Some(one)) => vec![PathBuf::from(one)], + _ => return Err(EngineError::Param("name the files with 'paths' (or one with 'path')".into())), + }; + if list.is_empty() || list.len() > MAX_DROPPED { + return Err(EngineError::Param(format!("drop 1 to {MAX_DROPPED} files at once"))); + } + Ok(list) +} + +fn drop(s: &mut Session, p: &Value) -> Result { + let files = paths(p)?; + let target = match str_req(p, "to")? { + "stage" => DropTarget::Stage, + "library" => DropTarget::Library, + other => return Err(EngineError::Param(format!("param 'to' must be stage or library, not '{other}'"))), + }; + // Everything is checked before anything is imported (the command is atomic anyway). + for f in &files { + match route(kind_of(f), target) { + DropAction::Open => return Err(EngineError::Param(format!("{} is a document: open it with file.open", f.display()))), + DropAction::Refuse(why) => return Err(EngineError::Param(format!("{}: {why}", f.display()))), + DropAction::ImportToStage | DropAction::ImportToLibrary => {} + } + } + let folder = match opt_u64(p, "folder")? { + Some(f) if target == DropTarget::Library => { + let id = FolderId(f); + if s.doc.folder(id).is_none() { + return Err(EngineError::State(format!("no Library folder with id {f}"))); + } + Some(id) + } + Some(_) => return Err(EngineError::Param("'folder' is for drops on the Library".into())), + None => None, + }; + let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0); + let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0); + if !(x.is_finite() && y.is_finite()) || x.abs() > 1.0e6 || y.abs() > 1.0e6 { + return Err(EngineError::Param("'x' and 'y' must be within a million pixels of the origin".into())); + } + let (mut elements, mut items, mut layers) = (Vec::new(), Vec::new(), 0u64); + for f in &files { + let path = f.display().to_string(); + if target == DropTarget::Library { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let item = match (v["bitmap"].as_u64(), v["sound"].as_u64()) { + (Some(b), _) => LibraryItem::Bitmap(anicraft_doc::BitmapId(b)), + (None, Some(snd)) => LibraryItem::Sound(anicraft_doc::SoundId(snd)), + _ => return Err(EngineError::State(format!("{path} added nothing to the Library"))), + }; + if let Some(folder) = folder { + // Into the folder under the pointer, numbered if it has an item of that name. + let name = s.doc.item_name(item).unwrap_or("").to_string(); + let free = s.doc.unique_name(Some(folder), &name); + s.doc.place_entry(LibraryEntry::Item(item), Some(folder)); + if free != name { + let mut params = crate::cmds_library::entry_json(LibraryEntry::Item(item)); + params["name"] = json!(free); + crate::cmds_library::rename(s, ¶ms)?; + } + } + items.push(crate::cmds_library::entry_json(LibraryEntry::Item(item))); + continue; + } + match kind_of(f) { + DropKind::Drawing => { + // A drawing's own shapes, on the active layer (or its own layers when it has + // several or masks), centred on the drop point. + let v = crate::cmds_file::import_to_stage(s, &json!({"path": path, "cx": x, "cy": y, "layer": "active"}))?; + layers += v["layers"].as_u64().unwrap_or(0); + elements.extend(s.selection.ids()); + } + _ => { + // An image or a sound: into the Library, then placed as Place on Stage does. + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let item = match (v["bitmap"].as_u64(), v["sound"].as_u64()) { + (Some(b), _) => json!({"bitmap": b}), + (None, Some(snd)) => json!({"sound": snd}), + _ => return Err(EngineError::State(format!("{path} added nothing to the Library"))), + }; + items.push(item.clone()); + let mut place = item; + place["x"] = json!(x); + place["y"] = json!(y); + let placed = crate::cmds_draw::place(s, &place)?; + if let Some(list) = placed["elements"].as_array() { + elements.extend(list.iter().filter_map(Value::as_u64).map(anicraft_doc::ElementId)); + } + } + } + } + if !elements.is_empty() { + s.select_only(elements.iter().copied()); + } + Ok(json!({"elements": elements.iter().map(|e| e.0).collect::>(), "items": items, "layers": layers, "files": files.len()})) +} diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 3ec7adbc..5d6a562f 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { label: "Import to Stage…", menu: "File/Import", shortcut: Some("Ctrl+R"), - params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred)}", + params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead)}", mutates: true, run: import_to_stage, }, @@ -149,7 +149,7 @@ pub fn is_animate(path: &std::path::Path) -> bool { matches!(ext.as_deref(), Some("fla" | "xfl")) || (crate::vfs::is_dir(path) && crate::vfs::is_file(&path.join("DOMDocument.xml"))) } -fn open(s: &mut Session, p: &Value) -> Result { +pub(crate) fn open(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); let unsaved = opt_bool(p, "unsaved")?.unwrap_or(false); let untitled = opt_bool(p, "untitled")?.unwrap_or(false); @@ -173,6 +173,8 @@ fn open(s: &mut Session, p: &Value) -> Result { // as it was in Animate (ADR 0042). let merged = crate::merge::merge_document(&mut doc); s.replace_document(doc, None); + // Open Recent reopens the Animate file (ADR 0059). + s.recent.add(&path); let mut info = s.info(); info["imported"] = json!(path.display().to_string()); info["report"] = json!(report.summary()); @@ -184,9 +186,11 @@ fn open(s: &mut Session, p: &Value) -> Result { return Ok(info); } let doc = format::load(&path)?; - s.replace_document(doc, (!untitled).then_some(path)); + s.replace_document(doc, (!untitled).then(|| path.clone())); if unsaved { s.mark_unsaved(); + } else if !untitled { + s.recent.add(&path); } Ok(s.info()) } @@ -199,6 +203,7 @@ fn save(s: &mut Session, p: &Value) -> Result { format::save(&s.doc, &path)?; s.path = Some(path.clone()); s.mark_saved(); + s.recent.add(&path); Ok(json!({"saved": path.display().to_string()})) } @@ -233,7 +238,7 @@ const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024; /// named after the file, in a keyframe at the playhead, selected, as one undo step. A drawing /// with clip paths or masks becomes a folder named after the file, with mask layers over the /// artwork they clip (ADR 0021). Centred on the stage unless `x`/`y` give its top-left corner. -fn import_to_stage(s: &mut Session, p: &Value) -> Result { +pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); if crate::cmds_sound::is_sound(&path) { return crate::cmds_sound::import_to_stage(s, &path); @@ -257,8 +262,20 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary()))); } let stage = s.doc.stage; - let x = opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5); - let y = opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5); + // `cx`/`cy` centre it on a point (a drop, ADR 0059); `x`/`y` give its top-left corner. + let x = match opt_f32(p, "cx")? { + Some(cx) => cx - drawing.width * 0.5, + None => opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5), + }; + let y = match opt_f32(p, "cy")? { + Some(cy) => cy - drawing.height * 0.5, + None => opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5), + }; + let onto_active = match opt_str(p, "layer")? { + None | Some("new") => false, + Some("active") => true, + Some(other) => return Err(EngineError::Param(format!("param 'layer' must be new or active, not '{other}'"))), + }; if !(x.is_finite() && y.is_finite()) { return Err(EngineError::Param("'x' and 'y' must be numbers".into())); } @@ -285,7 +302,13 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { let masks = drawing.layers.iter().filter(|l| l.mask.is_some()).count(); let (width, height, report) = (drawing.width, drawing.height, drawing.report); let mut layers = drawing.layers; - let (layer_id, ids, made, folder) = if layers.len() == 1 && masks == 0 { + let (layer_id, ids, made, folder) = if onto_active && layers.len() == 1 && masks == 0 { + // Onto the active layer's keyframe at the playhead, as a drop on the stage puts it. + let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default()); + let ids: Vec = els.iter().map(|e| e.id).collect(); + s.editable_keyframe()?.elements.extend(els); + (s.layer, ids, 0, None) + } else if layers.len() == 1 && masks == 0 { // One layer, named after the file, as Import to Stage always made. crate::cmds_timeline::new_layer(s, &json!({"name": name}))?; let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default()); diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs index a607bec6..2588fbea 100644 --- a/crates/engine/src/cmds_library.rs +++ b/crates/engine/src/cmds_library.rs @@ -182,7 +182,7 @@ fn new_folder(s: &mut Session, p: &Value) -> Result { Ok(json!({"folder": id.0, "name": name})) } -fn rename(s: &mut Session, p: &Value) -> Result { +pub(crate) fn rename(s: &mut Session, p: &Value) -> Result { let e = entry_of(p)?; if !s.doc.has_entry(e) { return Err(EngineError::State(format!("the Library has no {}", describe(e)))); diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 88e82aaa..48b77527 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -39,6 +39,7 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { } _ => match id.split('.').next().unwrap_or("") { "file" => Err("plug-ins can't open, save, import or export files"), + "prefs" => Err("plug-ins can't read or change your preferences"), "plugin" => Err("plug-ins can't install, run or remove plug-ins"), "control" => Err("plug-ins can't play the movie"), ns if DOCUMENT.contains(&ns) => Ok(()), diff --git a/crates/engine/src/cmds_recent.rs b/crates/engine/src/cmds_recent.rs new file mode 100644 index 00000000..a858c71c --- /dev/null +++ b/crates/engine/src/cmds_recent.rs @@ -0,0 +1,363 @@ +//! Recent files (ADR 0059): the documents opened or saved last, most recent first, with pinned +//! favourites kept above them. The list belongs to the session (it survives New and Open) and +//! is plain data: the desktop app keeps it in its preferences and puts it back at start, so the +//! engine never reads or writes the settings folder. `file.open` and `file.save` add to it; +//! these commands open, pin, remove and clear entries for menus, the CLI and MCP alike. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Most recent (unpinned) files kept, as Animate's Open Recent shows. +pub const MAX_RECENT: usize = 10; +/// Most pinned favourites. +pub const MAX_PINNED: usize = 10; +/// Longest path kept (anything longer is not a path a user picked). +const MAX_PATH_BYTES: usize = 4096; + +/// One file in the list. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RecentFile { + pub path: PathBuf, + /// A favourite: it stays at the top, and adding or clearing recent files leaves it alone. + pub pinned: bool, +} + +/// Pinned favourites first (in the order they were pinned), then the recent files, most recent +/// first. At most [`MAX_PINNED`] + [`MAX_RECENT`] entries, never the same file twice. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct RecentFiles { + entries: Vec, +} + +/// Whether two paths name the same file as the user sees it: Windows and macOS file names +/// ignore case (by default), and Windows takes either slash. +pub fn same_file(a: &Path, b: &Path) -> bool { + if cfg!(any(windows, target_os = "macos")) { + let norm = |p: &Path| p.to_string_lossy().replace('\\', "/").to_lowercase(); + norm(a) == norm(b) + } else { + a == b + } +} + +/// Whether a recent file is still there to open (a file, or an XFL folder). +pub fn exists(path: &Path) -> bool { + crate::vfs::is_file(path) || crate::vfs::is_dir(path) +} + +/// A short, stable key for a path (64-bit FNV-1a of its normalised text, as hex): the name its +/// thumbnail is kept under. +pub fn thumb_key(path: &Path) -> String { + let text = if cfg!(any(windows, target_os = "macos")) { path.to_string_lossy().replace('\\', "/").to_lowercase() } else { path.to_string_lossy().into_owned() }; + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in text.bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{h:016x}") +} + +/// Largest edge of a recent file's thumbnail, in pixels. +pub const THUMB_W: u32 = 240; +pub const THUMB_H: u32 = 135; + +/// The document's first frame as a small PNG that fits [`THUMB_W`] × [`THUMB_H`] (the start +/// screen's picture of a recent file), rendered by the CPU oracle. +pub fn thumbnail_png(doc: &anicraft_doc::Document) -> Result> { + let (w, h) = (doc.stage.width.max(1) as f32, doc.stage.height.max(1) as f32); + let scale = (THUMB_W as f32 / w).min(THUMB_H as f32 / h).min(1.0); + crate::cmds_file::render_png(doc, 0, scale) +} + +impl RecentFiles { + pub fn entries(&self) -> &[RecentFile] { + &self.entries + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + fn position(&self, path: &Path) -> Option { + self.entries.iter().position(|e| same_file(&e.path, path)) + } + + fn pinned_count(&self) -> usize { + self.entries.iter().take_while(|e| e.pinned).count() + } + + /// A file was opened or saved: it becomes the most recent. A pinned file keeps its place; + /// the oldest recent file beyond [`MAX_RECENT`] drops off. Returns whether the list changed. + pub fn add(&mut self, path: &Path) -> bool { + if path.as_os_str().is_empty() || path.as_os_str().len() > MAX_PATH_BYTES { + return false; + } + let before = self.entries.clone(); + if let Some(i) = self.position(path) { + if self.entries.get(i).is_some_and(|e| e.pinned) { + return false; + } + self.entries.remove(i); + } + let at = self.pinned_count(); + self.entries.insert(at, RecentFile { path: path.to_path_buf(), pinned: false }); + self.entries.truncate(at + MAX_RECENT); + before != self.entries + } + + /// Takes a file off the list (pinned or not). Returns whether it was there. + pub fn remove(&mut self, path: &Path) -> bool { + match self.position(path) { + Some(i) => { + self.entries.remove(i); + true + } + None => false, + } + } + + /// Pins a file (it goes below the other pinned files) or unpins it (it becomes the most + /// recent file). A file not on the list is added pinned. + pub fn pin(&mut self, path: &Path, pinned: bool) -> std::result::Result<(), String> { + let current = self.position(path).and_then(|i| self.entries.get(i)).map(|e| e.pinned); + if current == Some(pinned) { + return Ok(()); + } + if pinned && self.pinned_count() >= MAX_PINNED { + return Err(format!("at most {MAX_PINNED} files can be pinned; unpin one first")); + } + if path.as_os_str().is_empty() || path.as_os_str().len() > MAX_PATH_BYTES { + return Err("that is not a file path".into()); + } + self.remove(path); + let at = self.pinned_count(); + self.entries.insert(at, RecentFile { path: path.to_path_buf(), pinned }); + let pins = self.pinned_count(); + self.entries.truncate(pins + MAX_RECENT); + Ok(()) + } + + /// Clears the recent files; pinned favourites stay unless `pinned` too. Returns how many + /// were taken off. + pub fn clear(&mut self, pinned: bool) -> usize { + let before = self.entries.len(); + self.entries.retain(|e| e.pinned && !pinned); + before - self.entries.len() + } + + /// The list as read from a preferences file that anyone may have edited: empty and overlong + /// paths and repeats dropped, pinned files first, each part within its limit. + pub fn sanitized(self) -> RecentFiles { + let mut out = RecentFiles::default(); + let (pins, recents): (Vec, Vec) = self.entries.into_iter().partition(|e| e.pinned); + for e in pins.into_iter().chain(recents) { + let bad = e.path.as_os_str().is_empty() || e.path.as_os_str().len() > MAX_PATH_BYTES; + if bad || out.position(&e.path).is_some() { + continue; + } + let pins = out.pinned_count(); + if (e.pinned && pins >= MAX_PINNED) || (!e.pinned && out.entries.len() - pins >= MAX_RECENT) { + continue; + } + out.entries.push(e); + } + out + } +} + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "file.open_recent", + label: "Open Recent", + // The File menu shows the files themselves (a submenu the shell draws). + menu: "", + shortcut: None, + params: "{index? (in file.recent_list order, from 0) | path?, confirm? (needed over unsaved changes)}: opens it as file.open does; a file that is no longer there stays on the list, marked missing", + mutates: false, + run: open_recent, + }, + CommandSpec { + id: "file.recent_list", + label: "Recent Files", + menu: "", + shortcut: None, + params: "{} → {files: [{index, path, name, pinned, missing, thumb}]}: pinned favourites first, then the last 10 files opened or saved, most recent first (`thumb` names the start screen's picture)", + mutates: false, + run: list, + }, + CommandSpec { + id: "prefs.recent_pin", + label: "Pin to Recent Files", + menu: "", + shortcut: None, + params: "{index? | path?, pinned? (default: toggle)}: a pinned file stays at the top of Open Recent", + mutates: false, + run: pin, + }, + CommandSpec { id: "prefs.recent_remove", label: "Remove from Recent Files", menu: "", shortcut: None, params: "{index? | path?}", mutates: false, run: remove }, + CommandSpec { + id: "prefs.recent_clear", + label: "Clear Recent Files", + menu: "", + shortcut: None, + params: "{pinned? (default false: pinned favourites stay)} → {removed}", + mutates: false, + run: clear, + }, + ] +} + +/// The entry `index` or `path` names. +fn which(s: &Session, p: &Value) -> Result { + match (opt_u64(p, "index")?, opt_str(p, "path")?) { + (Some(i), None) => usize::try_from(i).ok().and_then(|i| s.recent.entries().get(i)).map(|e| e.path.clone()).ok_or_else(|| EngineError::Param(format!("no recent file {i}; file.recent_list has {}", s.recent.len()))), + (None, Some(path)) if !path.trim().is_empty() => Ok(PathBuf::from(path)), + (None, Some(_)) => Err(EngineError::Param("param 'path' must name a file".into())), + _ => Err(EngineError::Param("name the file with 'index' or 'path' (one of them)".into())), + } +} + +fn open_recent(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + if !exists(&path) { + return Err(EngineError::State(format!("{} is no longer there (moved, renamed or deleted); remove it from Open Recent", path.display()))); + } + crate::cmds_file::open(s, &json!({"path": path.display().to_string()})) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let files: Vec = s + .recent + .entries() + .iter() + .enumerate() + .map(|(i, e)| { + let name = e.path.file_name().map_or_else(|| e.path.display().to_string(), |n| n.to_string_lossy().into_owned()); + json!({"index": i, "path": e.path.display().to_string(), "name": name, "pinned": e.pinned, "missing": !exists(&e.path), "thumb": thumb_key(&e.path)}) + }) + .collect(); + Ok(json!({"files": files})) +} + +fn pin(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + let now = s.recent.entries().iter().find(|e| same_file(&e.path, &path)).is_some_and(|e| e.pinned); + let pinned = opt_bool(p, "pinned")?.unwrap_or(!now); + s.recent.pin(&path, pinned).map_err(EngineError::State)?; + Ok(json!({"path": path.display().to_string(), "pinned": pinned})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + if !s.recent.remove(&path) { + return Err(EngineError::State(format!("{} is not in the recent files", path.display()))); + } + Ok(json!({"removed": path.display().to_string()})) +} + +fn clear(s: &mut Session, p: &Value) -> Result { + let pinned = opt_bool(p, "pinned")?.unwrap_or(false); + Ok(json!({"removed": s.recent.clear(pinned)})) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn paths(r: &RecentFiles) -> Vec { + r.entries().iter().map(|e| format!("{}{}", if e.pinned { "*" } else { "" }, e.path.display())).collect() + } + + #[test] + fn most_recent_first_ten_at_most_never_twice() { + let mut r = RecentFiles::default(); + for i in 0..14 { + assert!(r.add(Path::new(&format!("f{i}.anicraft")))); + } + assert_eq!(r.len(), MAX_RECENT); + assert_eq!(paths(&r).first().map(String::as_str), Some("f13.anicraft")); + assert_eq!(paths(&r).last().map(String::as_str), Some("f4.anicraft"), "the oldest drop off"); + // Opening one again moves it to the top, without a second entry. + assert!(r.add(Path::new("f8.anicraft"))); + assert_eq!(paths(&r)[..2], ["f8.anicraft", "f13.anicraft"]); + assert_eq!(r.len(), MAX_RECENT); + assert!(!r.add(Path::new("f8.anicraft")), "already the most recent"); + assert!(!r.add(Path::new("")), "no empty paths"); + } + + #[test] + fn pinned_files_stay_on_top_and_survive_clearing() { + let mut r = RecentFiles::default(); + for f in ["a", "b", "c"] { + r.add(Path::new(f)); + } + r.pin(Path::new("a"), true).unwrap(); + assert_eq!(paths(&r), ["*a", "c", "b"]); + // New files go below the pins; opening a pinned file leaves it where it is. + r.add(Path::new("d")); + assert!(!r.add(Path::new("a"))); + assert_eq!(paths(&r), ["*a", "d", "c", "b"]); + // Pins don't count towards the ten recent files. + for i in 0..12 { + r.add(Path::new(&format!("n{i}"))); + } + assert_eq!(r.len(), 1 + MAX_RECENT); + assert_eq!(r.clear(false), MAX_RECENT); + assert_eq!(paths(&r), ["*a"]); + // Unpinning makes it the most recent file. + r.add(Path::new("z")); + r.pin(Path::new("a"), false).unwrap(); + assert_eq!(paths(&r), ["a", "z"]); + assert!(r.remove(Path::new("z"))); + assert!(!r.remove(Path::new("z"))); + assert_eq!(r.clear(true), 1); + assert!(r.is_empty()); + for i in 0..MAX_PINNED { + r.pin(Path::new(&format!("p{i}")), true).unwrap(); + } + assert!(r.pin(Path::new("one too many"), true).is_err()); + } + + #[test] + fn a_hand_edited_list_is_cleaned_up() { + let raw = r#"[{"path": "b"}, {"path": "", "pinned": true}, {"path": "a", "pinned": true}, {"path": "b"}, {"nonsense": 1}]"#; + let r: RecentFiles = serde_json::from_str::(raw).unwrap().sanitized(); + assert_eq!(paths(&r), ["*a", "b"]); + let many: Vec = (0..40).map(|i| RecentFile { path: PathBuf::from(format!("{i}")), pinned: i % 2 == 0 }).collect(); + let r = RecentFiles { entries: many }.sanitized(); + assert_eq!(r.entries().iter().filter(|e| e.pinned).count(), MAX_PINNED); + assert_eq!(r.entries().iter().filter(|e| !e.pinned).count(), MAX_RECENT); + assert!(r.entries().iter().take(MAX_PINNED).all(|e| e.pinned), "pins first"); + assert!(RecentFiles { entries: vec![RecentFile { path: PathBuf::from("x".repeat(5000)), pinned: false }] }.sanitized().is_empty()); + } + + #[test] + fn thumbnail_keys_are_stable_and_distinct() { + assert_eq!(thumb_key(Path::new("a/b.anicraft")), thumb_key(Path::new("a/b.anicraft"))); + assert_ne!(thumb_key(Path::new("a/b.anicraft")), thumb_key(Path::new("a/c.anicraft"))); + assert_eq!(thumb_key(Path::new("x")).len(), 16); + } + + #[test] + fn thumbnails_fit_the_start_screen() { + let png = thumbnail_png(&anicraft_doc::sample::demo()).unwrap(); + let img = image_size(&png); + assert!(img.0 <= THUMB_W && img.1 <= THUMB_H && img.0 > 0 && img.1 > 0, "{img:?}"); + } + + /// Width and height from a PNG's header. + fn image_size(png: &[u8]) -> (u32, u32) { + let be = |i: usize| u32::from_be_bytes([png[i], png[i + 1], png[i + 2], png[i + 3]]); + (be(16), be(20)) + } +} diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index 47666910..a5fb286f 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -99,7 +99,7 @@ fn sound_json(s: &Sound) -> Value { } /// Import to Library: a sound (or an image) goes into the library without being placed. -fn import_to_library(s: &mut Session, p: &Value) -> Result { +pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); if is_sound(&path) { let id = add_sound(s, &path, opt_str(p, "name")?)?; diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 57de4cc9..baed2de7 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -98,7 +98,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: true, }) } - "file.new" | "file.new_sample" | "file.open" | "file.recover" if s.is_dirty() => Some(Confirmation { + "file.new" | "file.new_sample" | "file.open" | "file.open_recent" | "file.recover" if s.is_dirty() => Some(Confirmation { title: "Discard unsaved changes?".into(), message: format!("“{}” has changes that are not saved. They will be lost, and its undo history is cleared.", doc_name(s)), action: "Discard Changes".into(), diff --git a/crates/engine/src/drop_tests.rs b/crates/engine/src/drop_tests.rs new file mode 100644 index 00000000..a323ce0b --- /dev/null +++ b/crates/engine/src/drop_tests.rs @@ -0,0 +1,215 @@ +//! Files dropped onto the window and recent files (ADR 0059): routing by type and target, what +//! `file.drop` brings in and where, one undo step, and the recent list that opening and saving +//! keep. + +use super::*; +use crate::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; +use serde_json::json; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-drop-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A 4 × 2 PNG, a one-rectangle SVG and a short WAV in `dir`. +fn media(dir: &Path) -> (String, String, String) { + let png = dir.join("photo.png"); + std::fs::write(&png, anicraft_render::encode_png(4, 2, &[255u8; 4 * 2 * 4]).unwrap()).unwrap(); + let svg = dir.join("badge.svg"); + std::fs::write(&svg, r##""##).unwrap(); + let wav = dir.join("beep.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &[0.25; 4000])).unwrap(); + (png.display().to_string(), svg.display().to_string(), wav.display().to_string()) +} + +#[test] +fn drops_route_by_file_type_and_target() { + use DropAction::*; + use DropTarget::*; + let k = |p: &str| kind_of(Path::new(p)); + assert_eq!(k("a.anicraft"), DropKind::Document); + assert_eq!(k("A.FLA"), DropKind::Document); + assert_eq!(k("b.xfl"), DropKind::Document); + assert_eq!(k("c.svg"), DropKind::Drawing); + assert_eq!(k("d.JPEG"), DropKind::Image); + assert_eq!(k("d.jpg"), DropKind::Image); + assert_eq!(k("e.png"), DropKind::Image); + assert_eq!(k("f.mp3"), DropKind::Sound); + assert_eq!(k("g.ogg"), DropKind::Sound); + assert_eq!(k("h.wav"), DropKind::Sound); + assert_eq!(k("i.psd"), DropKind::Unsupported); + assert_eq!(k("no extension"), DropKind::Unsupported); + // An XFL package is a folder with a DOMDocument.xml. + let dir = temp_dir("xfl").join("Movie"); + std::fs::create_dir_all(&dir).unwrap(); + assert_eq!(kind_of(&dir), DropKind::Unsupported, "a plain folder"); + std::fs::write(dir.join("DOMDocument.xml"), "").unwrap(); + assert_eq!(kind_of(&dir), DropKind::Document); + // Documents open wherever they land; media go where they are dropped. + for t in [Stage, Library, Window] { + assert_eq!(route(DropKind::Document, t), Open); + assert!(matches!(route(DropKind::Unsupported, t), Refuse(_))); + } + for kind in [DropKind::Drawing, DropKind::Image, DropKind::Sound] { + assert_eq!(route(kind, Stage), ImportToStage); + assert!(matches!(route(kind, Window), Refuse(_)), "only the stage and the Library take media"); + } + assert_eq!(route(DropKind::Image, Library), ImportToLibrary); + assert_eq!(route(DropKind::Sound, Library), ImportToLibrary); + assert!(matches!(route(DropKind::Drawing, Library), Refuse(m) if m.contains("stage"))); +} + +#[test] +fn media_dropped_on_the_stage_land_on_the_active_layer_at_the_drop_point_in_one_step() { + let dir = temp_dir("stage"); + let (png, svg, wav) = media(&dir); + let mut s = Session::default(); + run(&mut s, "timeline.insert_frame", json!({"count": 20})); + s.set_frame(5); + let layers = s.timeline().layers.len(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png, svg, wav], "to": "stage", "x": 100, "y": 60})); + assert_eq!(s.history_len(), history + 1, "one undo step for the whole drop"); + assert_eq!(s.timeline().layers.len(), layers, "everything went onto the active layer"); + assert_eq!(v["elements"].as_array().map(Vec::len), Some(2), "{v}"); + assert_eq!(s.selection.len(), 2, "what was dropped is selected"); + // Centred on the drop point, in the keyframe that shows at the playhead. + let layer = s.active_layer().unwrap(); + let key = layer.keyframe_at(5).unwrap(); + assert!(s.selection.ids().all(|id| key.elements.iter().any(|e| e.id == id))); + for id in s.selection.ids().collect::>() { + let b = s.element_bounds(id); + assert!((b.center().x - 100.0).abs() < 0.01 && (b.center().y - 60.0).abs() < 0.01, "{b:?}"); + } + assert!(key.sound.is_some(), "the sound is on the keyframe at the playhead"); + assert_eq!((s.doc.bitmaps.len(), s.doc.sounds.len()), (1, 1), "the image and the sound are in the Library"); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.bitmaps.is_empty() && s.doc.sounds.is_empty() && s.active_layer().unwrap().keyframe_at(5).is_none_or(|k| k.elements.is_empty())); +} + +#[test] +fn media_dropped_on_the_library_go_into_the_folder_under_the_pointer() { + let dir = temp_dir("library"); + let (png, svg, wav) = media(&dir); + let mut s = Session::default(); + let folder = run(&mut s, "library.new_folder", json!({"name": "Props"}))["folder"].as_u64().unwrap(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png.clone(), wav], "to": "library", "folder": folder})); + assert_eq!(s.history_len(), history + 1); + assert_eq!(v["items"].as_array().map(Vec::len), Some(2)); + let in_folder = s.doc.folder_contents(anicraft_doc::FolderId(folder)); + assert_eq!(in_folder.len(), 2, "{in_folder:?}"); + assert!(s.timeline().layers.iter().all(|l| l.keyframes.iter().all(|k| k.elements.is_empty() && k.sound.is_none())), "nothing placed on the stage"); + // The same image again: numbered, not refused. + run(&mut s, "file.drop", json!({"path": png.clone(), "to": "library", "folder": folder})); + let names: Vec = s.doc.folder_contents(anicraft_doc::FolderId(folder)).into_iter().filter_map(|e| s.doc.entry_name(e).map(str::to_string)).collect(); + assert!(names.contains(&"photo.png".to_string()) && names.contains(&"photo.png 2".to_string()), "{names:?}"); + // At the top level without a folder. + run(&mut s, "file.drop", json!({"path": png, "to": "library"})); + assert_eq!(s.doc.bitmaps.len(), 3); + // A drawing can't go into the Library; nothing is imported when one file is refused. + let before = s.doc.clone(); + assert!(s.execute("file.drop", &json!({"paths": [svg], "to": "library"})).is_err()); + assert!(s.doc == before); +} + +#[test] +fn drawings_with_layers_keep_them_and_bad_drops_change_nothing() { + let dir = temp_dir("bad"); + let (png, _, _) = media(&dir); + let masked = dir.join("masked.svg"); + std::fs::write(&masked, r##""##).unwrap(); + let mut s = Session::default(); + let layers = s.timeline().layers.len(); + run(&mut s, "file.drop", json!({"path": masked.display().to_string(), "to": "stage", "x": 10, "y": 10})); + assert!(s.timeline().layers.len() > layers + 1, "a masked drawing brings its folder and mask layer"); + let before = s.doc.clone(); + let doc = dir.join("x.anicraft"); + for p in [ + json!({"path": doc.display().to_string(), "to": "stage"}), + json!({"path": dir.join("y.psd").display().to_string(), "to": "stage"}), + json!({"paths": [png.clone(), dir.join("gone.png").display().to_string()], "to": "stage"}), + json!({"path": png.clone(), "to": "timeline"}), + json!({"path": png.clone(), "to": "library", "folder": u64::MAX}), + json!({"path": png.clone(), "to": "stage", "folder": 1}), + json!({"path": png.clone(), "to": "stage", "x": f64::MAX, "y": 0}), + json!({"paths": [], "to": "stage"}), + json!({"paths": vec![png.clone(); 65], "to": "stage"}), + json!({"paths": "x", "to": "stage"}), + json!({"paths": [1, 2], "to": "library"}), + json!({"to": "stage"}), + json!({}), + Value::Null, + ] { + assert!(s.execute("file.drop", &p).is_err(), "{p}"); + assert!(s.doc == before, "{p} changed the document"); + } + // A locked layer refuses the drop and says why. + let top = s.timeline().layers.len() - 1; + run(&mut s, "layer.select", json!({"index": top})); + run(&mut s, "layer.toggle_lock", json!({})); + let e = s.execute("file.drop", &json!({"path": png, "to": "stage"})).unwrap_err(); + assert!(e.to_string().contains("locked"), "{e}"); +} + +#[test] +fn opening_and_saving_keep_the_recent_list_and_open_recent_reopens() { + let dir = temp_dir("recent"); + let a = dir.join("a.anicraft"); + let b = dir.join("b.anicraft"); + let mut s = Session::new(anicraft_doc::sample::demo()); + run(&mut s, "file.save_as", json!({"path": a.display().to_string()})); + run(&mut s, "file.new", json!({"width": 1280, "height": 720})); + run(&mut s, "file.save_as", json!({"path": b.display().to_string()})); + let list = run(&mut s, "file.recent_list", json!({})); + let names: Vec<&str> = list["files"].as_array().unwrap().iter().filter_map(|f| f["name"].as_str()).collect(); + assert_eq!(names, ["b.anicraft", "a.anicraft"], "most recent first; New doesn't clear it"); + // Open Recent by index opens it, and moves it to the top. + run(&mut s, "file.open_recent", json!({"index": 1})); + assert_eq!(s.path.as_deref(), Some(a.as_path())); + assert_eq!(s.doc.stage.width, anicraft_doc::sample::demo().stage.width); + assert_eq!(s.recent.entries().first().map(|e| e.path.clone()), Some(a.clone())); + // Over unsaved work it asks first, like Open. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + assert!(s.confirmation("file.open_recent", &json!({"index": 1})).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.open_recent", &json!({"index": 1})).is_err()); + run(&mut s, "file.open_recent", json!({"index": 1, "confirm": true})); + assert_eq!(s.path.as_deref(), Some(b.as_path())); + // A file that is gone stays listed, marked missing, and says so when opened. + std::fs::remove_file(&a).unwrap(); + let list = run(&mut s, "file.recent_list", json!({})); + let gone = list["files"].as_array().unwrap().iter().find(|f| f["name"] == "a.anicraft").unwrap(); + assert_eq!(gone["missing"], true); + let e = s.execute("file.open_recent", &json!({"path": a.display().to_string()})).unwrap_err(); + assert!(e.to_string().contains("no longer there"), "{e}"); + // Pin, remove, clear. + run(&mut s, "prefs.recent_pin", json!({"path": a.display().to_string()})); + assert!(s.recent.entries().first().is_some_and(|e| e.pinned)); + run(&mut s, "prefs.recent_clear", json!({})); + assert_eq!(s.recent.len(), 1, "the pinned file stays"); + run(&mut s, "prefs.recent_remove", json!({"index": 0})); + assert!(s.recent.is_empty()); + // Hostile params never panic and never change the list. + run(&mut s, "file.open", json!({"path": b.display().to_string()})); + let before = s.recent.clone(); + for id in ["file.open_recent", "prefs.recent_pin", "prefs.recent_remove"] { + for p in [json!({"index": u64::MAX}), json!({"index": -1}), json!({"path": ""}), json!({"index": 0, "path": "x"}), json!({"pinned": "x"}), json!("x"), Value::Null] { + let _ = s.execute(id, &p); + assert_eq!(s.recent, before, "{id} {p}"); + } + } + // Restored autosaves and untitled opens aren't recent files. + let mut t = Session::default(); + run(&mut t, "file.open", json!({"path": b.display().to_string(), "unsaved": true})); + run(&mut t, "file.open", json!({"path": b.display().to_string(), "untitled": true, "confirm": true})); + assert!(t.recent.is_empty()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68be7acb..d061f292 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -10,6 +10,7 @@ mod cmds_bone; pub mod cmds_brush; mod cmds_camera; mod cmds_draw; +pub mod cmds_drop; pub mod cmds_erase; mod cmds_file; mod cmds_frames; @@ -22,6 +23,7 @@ mod cmds_path; pub mod cmds_raw; pub mod cmds_rawsub; mod cmds_rawpoints; +pub mod cmds_recent; mod cmds_recovery; mod cmds_script; pub mod cmds_plugin; @@ -108,6 +110,8 @@ impl CommandSpec { pub fn commands() -> Vec { let mut v = Vec::new(); v.extend(cmds_file::specs()); + v.extend(cmds_recent::specs()); + v.extend(cmds_drop::specs()); v.extend(cmds_recovery::specs()); v.extend(cmds_timeline::specs()); v.extend(cmds_camera::specs()); @@ -296,6 +300,10 @@ pub struct Session { gesture_cut: Option, /// The last picture of an open symbol in place, by its key (ADR 0045). picture_cache: RefCell)>>, + /// The files opened and saved last, and pinned favourites (ADR 0059). They belong to the + /// session, not the document: they survive New and Open. The desktop app keeps them in its + /// preferences. + pub recent: cmds_recent::RecentFiles, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -361,6 +369,7 @@ impl Session { pending_cut: None, gesture_cut: None, picture_cache: RefCell::new(None), + recent: cmds_recent::RecentFiles::default(), } } @@ -442,7 +451,9 @@ impl Session { let budget = self.history.budget_bytes; let clipboard = std::mem::take(&mut self.clipboard); let plugins = std::mem::take(&mut self.plugins); + let recent = std::mem::take(&mut self.recent); *self = Session::new(doc); + self.recent = recent; // The clipboard survives New/Open, so artwork can move between documents. self.clipboard = clipboard; self.plugins = plugins; @@ -986,3 +997,5 @@ mod eyedropper_tests; mod selection_tests; #[cfg(test)] mod scale_grid_tests; +#[cfg(test)] +mod drop_tests; diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index 35ced9f4..14e62081 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -169,7 +169,7 @@ fn every_command_namespace_has_a_plugin_policy() { let ns = c.id.split('.').next().unwrap_or(""); let verdict = plugin_may_call(c.id); match ns { - "file" | "plugin" | "control" => assert!(verdict.is_err(), "{} must be refused", c.id), + "file" | "plugin" | "control" | "prefs" => assert!(verdict.is_err(), "{} must be refused", c.id), _ => assert!(verdict.is_ok() || matches!(c.id, "edit.undo" | "edit.redo") || c.id.contains("copy") || c.id.contains("cut") || c.id.contains("paste"), "{} has no plug-in policy (add its namespace to plugin_may_call)", c.id), } } From f041cb1bd92a4f5ea4de541dc5538b33fa0fc59b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:47:05 -0700 Subject: [PATCH 040/192] feat(shell): drop files onto the window, File > Open Recent and a start screen (M8) --- Cargo.toml | 2 +- crates/doc/src/bitmap.rs | 1 + crates/doc/src/lib.rs | 2 +- src/a11y.rs | 2 +- src/app.rs | 68 ++++- src/drop.rs | 538 +++++++++++++++++++++++++++++++++++++++ src/guidelines_tests.rs | 5 +- src/i18n/tests.rs | 4 +- src/library.rs | 28 ++ src/main.rs | 11 +- src/menus.rs | 7 + src/panels.rs | 4 +- src/platform.rs | 23 ++ src/prefs.rs | 33 +++ src/recent.rs | 193 ++++++++++++++ src/stage.rs | 2 + src/start.rs | 315 +++++++++++++++++++++++ src/web.rs | 78 +++++- 18 files changed, 1304 insertions(+), 12 deletions(-) create mode 100644 src/drop.rs create mode 100644 src/recent.rs create mode 100644 src/start.rs diff --git a/Cargo.toml b/Cargo.toml index 562023b3..5d957ba6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -120,7 +120,7 @@ wasm-bindgen-futures = "0.4" js-sys = "0.3" # In the browser the page's language (navigator.languages) is the system's. sys-locale = { version = "0.3", features = ["js"] } -web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] } +web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] } [build-dependencies] # Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets. diff --git a/crates/doc/src/bitmap.rs b/crates/doc/src/bitmap.rs index 196de0bd..4df45cf5 100644 --- a/crates/doc/src/bitmap.rs +++ b/crates/doc/src/bitmap.rs @@ -222,6 +222,7 @@ pub(crate) mod base64_bytes { } } +pub use base64_bytes::decode as base64_decode; pub use base64_bytes::encode as base64_encode; #[cfg(test)] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8e92b3..157e233d 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -26,7 +26,7 @@ pub mod sample; pub mod sound; pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; -pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; +pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png}; pub use easing::Easing; pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform}; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; diff --git a/src/a11y.rs b/src/a11y.rs index 6f427639..328710a8 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -352,7 +352,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit"] { + for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index 3abc78d5..b70802a9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -420,6 +420,12 @@ pub struct App { heard: Option<(usize, u32)>, /// The panel Ctrl+F6 last moved focus to (where the next press continues from). pub last_panel: Option, + /// The start screen, while it is up (ADR 0059). + pub start: Option, + /// Files dragged over and dropped onto the window (ADR 0059). + pub drop: crate::drop::DropState, + /// Recent files' pictures for the start screen. + pub thumbs: crate::recent::Thumbs, } /// How finished this version is, shown next to the version number (docs/release.md). English: @@ -471,6 +477,8 @@ impl App { let _ = anicraft_engine::text::Fonts::get(); }); let mut session = session; + // Open Recent is the session's list, kept in the preferences (ADR 0059). + session.recent = prefs.recent.clone(); // The editor draws as Animate does: merge drawing, until Object Drawing (J) is switched on. session.style.object_drawing = false; let mut app = App { @@ -564,6 +572,9 @@ impl App { audio_clock: false, heard: None, last_panel: None, + start: None, + drop: Default::default(), + thumbs: Default::default(), }; app.apply_prefs(ctx); app.decode_sounds(); @@ -767,6 +778,18 @@ impl App { self.run("scene.select", json!({"scene": last})); } Some("files") => self.show_files = true, + Some("start") => { + // The start screen with sample recent files (one pinned, one missing). + crate::start::open(self); + if self.shot.is_some() { + crate::recent::sample_entries(self); + } + } + Some("drop") => self.drop.preview = Some((vec![PathBuf::from("sunset.png")], crate::drop::PreviewAt::Stage)), // i18n-exempt: a sample file name + Some("droplibrary") => { + self.run("library.new_folder", json!({"name": "Backgrounds"})); // i18n-exempt: a sample folder name + self.drop.preview = Some((vec![PathBuf::from("sunset.png")], crate::drop::PreviewAt::Library)); // i18n-exempt: a sample file name + } Some("recovery") => { // Work left behind by a session that didn't close cleanly (sample entries // unless ANICRAFT_RECOVERY_DIR holds real ones). @@ -1479,7 +1502,15 @@ impl App { /// new document resets. `selected` is how many elements were selected before it ran. pub(crate) fn announce(&mut self, id: &str, v: &Value, selected: usize) { match id { - "file.new" | "file.new_sample" | "file.open" => { + "file.new" | "file.new_sample" | "file.open" | "file.open_recent" => { + // The document is here: the start screen has done its job (ADR 0059). + self.start = None; + if id != "file.new" + && id != "file.new_sample" + && let Some(path) = self.s.path.clone().or_else(|| v["imported"].as_str().map(PathBuf::from)) + { + crate::recent::captured_on_open(self, &path); + } self.view.fit = true; self.library_sel = crate::library::first_item(&self.s.doc); self.decode_sounds(); @@ -1487,7 +1518,7 @@ impl App { // An imported file: say what came across and what didn't, and that saving // makes a new .anicraft document. Some(r) => self.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)), - None => self.status_ok(if id == "file.open" { tr!("Opened") } else { tr!("New document") }), + None => self.status_ok(if id == "file.open" || id == "file.open_recent" { tr!("Opened") } else { tr!("New document") }), } } "file.recover" => { @@ -1507,6 +1538,10 @@ impl App { self.status_ok(tr!("Discarded the autosaved copy")); } "file.save" | "file.save_as" => { + // The start screen's picture of it (ADR 0059). + if let Some(saved) = v["saved"].as_str() { + crate::recent::capture(self, std::path::Path::new(saved)); + } // In a browser the file goes to the downloads (ADR 0036). let path = v["saved"].as_str().unwrap_or(""); self.status_ok(if platform::WEB { tr!("Saved {path} to your downloads", path = path) } else { tr!("Saved {path}", path = path) }); @@ -1649,6 +1684,11 @@ impl App { } return; } + if matches!(id, "file.open_recent" | "file.recent_list") { + // The recent files with their pictures (the File menu lists them too). + crate::start::open(self); + return; + } if id == "tween.add_hint" { crate::shape_hints::add(self); return; @@ -2150,7 +2190,7 @@ impl App { /// The app icon (`assets/app-icon/`; the PNG carries its rounded corners) as a texture, decoded on /// first use and kept in the context. 128 px stays sharp at 64 pt on a 2× display. -fn app_mark(ctx: &egui::Context) -> egui::TextureHandle { +pub(crate) fn app_mark(ctx: &egui::Context) -> egui::TextureHandle { const PNG: &[u8] = include_bytes!("../assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png"); let id = egui::Id::new("anicraft-app-mark"); if let Some(tex) = ctx.data(|d| d.get_temp::(id)) { @@ -2237,7 +2277,22 @@ impl App { } let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2)); + crate::drop::begin_frame(self); egui::Panel::top("menu_bar").frame(bar(T.chrome)).show(ui, |ui| menus::bar(self, ui)); + if self.start.is_some() { + // The start screen takes the workspace's place (ADR 0059); the menus stay. + egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(T.pasteboard)).show(ui, |ui| crate::start::show(self, ui)); + } else { + self.workspace(ui); + } + self.windows(&ctx); + } + + /// The editor's panels: tools, stage, timeline, properties and Library. + fn workspace(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2)); egui::Panel::top("edit_bar").exact_size(theme::TARGET + 8.0).frame(bar(T.panel)).show(ui, |ui| panels::edit_bar(self, ui)); egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui)); // Docks start at their usual size, but never take most of a small window or a large @@ -2252,7 +2307,12 @@ impl App { egui::CentralPanel::default().frame(egui::Frame::NONE.fill(T.pasteboard)).show(ui, |ui| stage::show(self, ui)); crate::a11y::name_splitter(&ctx, "properties", tr!("Resize the right-hand panels")); crate::a11y::name_splitter(&ctx, "timeline", tr!("Resize the timeline")); + } + /// Dialogs and floating windows, the close guard and the end-of-frame upkeep. + fn windows(&mut self, ctx: &egui::Context) { + let ctx = ctx.clone(); + crate::drop::frame(self, &ctx); self.prompt_window(&ctx); crate::convert_symbol::window(self, &ctx); self.about_window(&ctx); @@ -2285,6 +2345,8 @@ impl App { // After this frame's edits: start a recovery copy when one is due (off this thread). autosave::tick(self, &ctx); + // Open Recent changed (an open, a save, a pin): into the preferences. + crate::recent::sync(self); // A browser asks before leaving a page with unsaved work (its close guard). platform::set_unsaved(self.s.is_dirty()); diff --git a/src/drop.rs b/src/drop.rs new file mode 100644 index 00000000..d7b94a56 --- /dev/null +++ b/src/drop.rs @@ -0,0 +1,538 @@ +//! Files dropped onto the window from the desktop or a browser (ADR 0059). Documents open (the +//! unsaved-changes guard as with File › Open); drawings, images and sounds dropped on the stage +//! go onto the active layer at the playhead where they were dropped, and dropped on the Library +//! go into it, into the folder under the pointer. While files are dragged over the window a +//! highlight shows where they will land. The routing is `anicraft_engine::cmds_drop::route`; +//! the import is the `file.drop` command, one undo step. +//! +//! Where a drop lands needs the pointer. Browsers report it while dragging (our own `dragover` +//! listener, `web::drag_pos`), but winit 0.30 gives no position with dragged files, and Windows +//! and macOS send no pointer moves during a drag. So a drop waits a moment for the pointer's +//! first move after it (the system sends one as the drag ends); without one it lands at the +//! centre of the view, and says so. + +use crate::app::App; +use crate::theme::{T, Type, color, font}; +use anicraft_engine::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; +use anicraft_engine::doc::FolderId; +use egui::{Pos2, Rect, Stroke, StrokeKind, vec2}; +use serde_json::json; +use std::path::{Path, PathBuf}; + +/// How long a drop waits for the pointer to say where it is, in seconds. +const WAIT_FOR_POINTER: f64 = 0.35; + +/// Where the stage was drawn this frame and how it maps to the edited space. +#[derive(Clone, Copy)] +pub struct StageGeo { + pub canvas: Rect, + pub origin: Pos2, + pub zoom: f32, + /// Previewing through the camera: artwork edits are paused. + pub paused: bool, +} + +impl StageGeo { + pub fn to_stage(self, p: Pos2) -> (f32, f32) { + let z = self.zoom.max(1e-6); + ((p.x - self.origin.x) / z, (p.y - self.origin.y) / z) + } +} + +/// Where a drop at a point lands. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Spot { + /// On the stage, at this point of the edited space. + Stage(f32, f32), + /// On the Library, into this folder (`None`: the top level). + Library(Option), + /// Somewhere else on the window. + Window, + /// The start screen is up: documents open, nothing imports. + Start, + /// The pointer's position isn't known (a drop on the desktop without a pointer move). + Unknown, +} + +/// What a drop does, worked out from its files and where it landed. +#[derive(Debug, Default, PartialEq)] +pub struct Plan { + /// The document to open (the first one dropped). + pub open: Option, + /// Files to import, and where. + pub import: Vec, + pub to: Option, + /// Files left out, each with why (in the interface language). + pub left_out: Vec<(PathBuf, String)>, +} + +/// Why a file can't go there, in the interface language. +fn refusal(kind: DropKind, to: DropTarget, start: bool) -> String { + match kind { + DropKind::Unsupported => tr!("AniCraft opens .anicraft, .fla and .xfl documents, and imports SVG drawings, PNG and JPEG images, and WAV, Ogg and MP3 sounds").into(), + _ if start => tr!("Open or create a document first, then drop drawings, images and sounds on its stage").into(), + DropKind::Drawing if to == DropTarget::Library => tr!("SVG drawings import to the stage: drop it there").into(), + _ => tr!("Drop drawings, images and sounds on the stage to place them, or on the Library to add them").into(), + } +} + +/// What dropping `files` at `spot` does. One document opens (AniCraft has one document +/// window); other files in the same drop are left out then. +pub fn plan(files: &[PathBuf], spot: Spot) -> Plan { + let mut out = Plan::default(); + if let Some(doc) = files.iter().find(|f| kind_of(f) == DropKind::Document) { + out.open = Some(doc.clone()); + for f in files.iter().filter(|f| *f != doc) { + out.left_out.push((f.clone(), tr!("AniCraft opens one document at a time; drop the others on their own").into())); + } + return out; + } + let to = match spot { + Spot::Library(_) => DropTarget::Library, + // Without a position, the stage (at the centre of the view). + Spot::Stage(..) | Spot::Unknown => DropTarget::Stage, + Spot::Window | Spot::Start => DropTarget::Window, + }; + for f in files { + let kind = kind_of(f); + match route(kind, to) { + DropAction::ImportToStage | DropAction::ImportToLibrary => out.import.push(f.clone()), + DropAction::Open => {} + DropAction::Refuse(_) => out.left_out.push((f.clone(), refusal(kind, to, spot == Spot::Start))), + } + } + if !out.import.is_empty() { + out.to = Some(to); + } + out +} + +/// A drop waiting for the pointer (desktop), or for the browser to read the files (web). +struct Waiting { + files: Vec, + since: f64, + /// Browser files still being read, by ticket. + #[cfg(target_arch = "wasm32")] + ticket: Option, +} + +/// The drop state the window keeps between frames. +#[derive(Default)] +pub struct DropState { + /// Where the stage was drawn this frame (set by `stage::show`). + pub stage: Option, + waiting: Option, + /// The pointer moved while files were dragged over the window: its position is current. + tracked: bool, + /// A drag shown without one (screenshots and tests): the files and where they hover. + pub preview: Option<(Vec, PreviewAt)>, + #[cfg(target_arch = "wasm32")] + web_spot: Option, +} + +/// Where a previewed drag hovers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewAt { + Stage, + Library, +} + +/// Where a drop at `p` lands, from this frame's layout. +pub fn spot_at(app: &App, p: Option) -> Spot { + if app.start.is_some() { + return Spot::Start; + } + let Some(p) = p else { return Spot::Unknown }; + if let Some(folder) = app.library.drop_zone.folder_at(p) { + return Spot::Library(folder); + } + match app.drop.stage { + Some(g) if g.canvas.contains(p) => { + let (x, y) = g.to_stage(p); + Spot::Stage(x, y) + } + _ => Spot::Window, + } +} + +/// Before the panels draw: forget last frame's targets (a hidden panel takes nothing). +pub fn begin_frame(app: &mut App) { + app.drop.stage = None; + app.library.drop_zone = Default::default(); +} + +/// The pointer's position over a dragged file, if it is known. +fn drag_pointer(app: &App, ctx: &egui::Context) -> Option { + #[cfg(target_arch = "wasm32")] + { + let _ = app; + let z = ctx.zoom_factor().max(1e-3); + crate::web::drag_pos().map(|(x, y)| egui::pos2(x / z, y / z)) + } + #[cfg(not(target_arch = "wasm32"))] + { + if app.drop.tracked { ctx.input(|i| i.pointer.latest_pos()) } else { None } + } +} + +/// After the panels drew: the highlight while files hover, and what was dropped. +pub fn frame(app: &mut App, ctx: &egui::Context) { + let (hovered, dropped, moved, now) = ctx.input(|i| { + let hovered: Vec = i.raw.hovered_files.iter().map(|h| h.path.clone().unwrap_or_else(|| PathBuf::from(guess_name(&h.mime)))).collect(); + let moved = i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_))); + (hovered, i.raw.dropped_files.clone(), moved, i.time) + }); + if !hovered.is_empty() { + app.drop.tracked |= moved; + let p = drag_pointer(app, ctx); + highlight(app, ctx, &hovered, p); + } else if let Some((files, at)) = app.drop.preview.clone() { + let p = preview_point(app, at); + highlight(app, ctx, &files, p); + } + if !dropped.is_empty() { + let files: Vec = dropped.iter().take(anicraft_engine::cmds_drop::MAX_DROPPED).map(|f| f.path().to_path_buf()).collect(); + if dropped.len() > anicraft_engine::cmds_drop::MAX_DROPPED { + app.status_err(tr!("Drop at most {n} files at once", n = anicraft_engine::cmds_drop::MAX_DROPPED)); + app.drop.tracked = false; + return; + } + app.playing = false; + #[cfg(target_arch = "wasm32")] + { + // The browser said where the drop is; it reads the files' bytes, which arrive later. + let spot = spot_at(app, drag_pointer(app, ctx)); + let handles: Vec = dropped.iter().filter_map(|f| f.web_file().cloned()).collect(); + let ticket = crate::web::read_dropped(handles); + app.drop.web_spot = Some(spot); + app.drop.waiting = Some(Waiting { files, since: now, ticket: Some(ticket) }); + crate::web::clear_drag_pos(); + } + #[cfg(not(target_arch = "wasm32"))] + { + if app.drop.tracked { + let spot = spot_at(app, ctx.input(|i| i.pointer.latest_pos())); + run(app, &files, spot); + } else { + app.drop.waiting = Some(Waiting { files, since: now }); + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + } + app.drop.tracked = false; + return; + } + if hovered.is_empty() { + // A drag that left the window (or was cancelled) starts over. + app.drop.tracked = false; + } + resolve_waiting(app, ctx, moved, now); +} + +#[cfg(not(target_arch = "wasm32"))] +fn resolve_waiting(app: &mut App, ctx: &egui::Context, moved: bool, now: f64) { + let Some(w) = &app.drop.waiting else { return }; + let timed_out = now - w.since > WAIT_FOR_POINTER; + if !moved && !timed_out { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + return; + } + let Some(w) = app.drop.waiting.take() else { return }; + let p = if moved { ctx.input(|i| i.pointer.latest_pos()) } else { None }; + run(app, &w.files, spot_at(app, p)); +} + +#[cfg(target_arch = "wasm32")] +fn resolve_waiting(app: &mut App, _ctx: &egui::Context, _moved: bool, _now: f64) { + let Some((ticket, read)) = crate::web::take_dropped() else { return }; + if app.drop.waiting.as_ref().and_then(|w| w.ticket) != Some(ticket) { + return; + } + let (Some(w), Some(spot)) = (app.drop.waiting.take(), app.drop.web_spot.take()) else { return }; + let _ = WAIT_FOR_POINTER; + let mut files = Vec::new(); + for (name, data) in read { + // Only the name: the browser never says which folder a file came from. + let path = PathBuf::from(&name); + match data.and_then(|d| anicraft_engine::vfs::put(&path, d).map_err(|e| e.to_string())) { + Ok(()) => files.push(path), + Err(e) => app.status_err(tr!("Could not open {name}: {e}", name = name, e = e)), + } + } + let _ = w.files; + if !files.is_empty() { + run(app, &files, spot); + } +} + +/// Carries out a drop. +pub fn run(app: &mut App, files: &[PathBuf], spot: Spot) { + let plan = plan(files, spot); + let names = |list: &[PathBuf]| list.iter().map(|p| crate::recent::display_name(p)).collect::>().join(", "); + if let Some(doc) = &plan.open { + app.start = None; + app.request("file.open", json!({"path": doc.display().to_string()})); + if let Some((_, why)) = plan.left_out.first() { + app.status_ok(tr!("Left out {files}: {why}", files = names(&plan.left_out.iter().map(|(p, _)| p.clone()).collect::>()), why = why)); + } + return; + } + let Some(to) = plan.to else { + // Nothing to import: one message says why. + if let Some((p, why)) = plan.left_out.first() { + app.status_err(tr!("Can't import {file}: {why}", file = crate::recent::display_name(p), why = why)); + } + return; + }; + let paths: Vec = plan.import.iter().map(|p| p.display().to_string()).collect(); + let n = plan.import.len(); + let done = match (to, spot) { + (DropTarget::Library, Spot::Library(folder)) => { + let v = app.run("file.drop", json!({"paths": paths, "to": "library", "folder": folder.map(|f| f.0)})); + if let Some(f) = folder { + app.library.expanded.extend(app.s.doc.folder_chain(f)); + } + v.map(|v| { + // The last file added is the Library's current item. + let last = v["items"].as_array().and_then(|a| a.last()).cloned().unwrap_or_default(); + match (last["bitmap"].as_u64(), last["sound"].as_u64()) { + (Some(b), _) => app.library_sel = Some(anicraft_engine::doc::LibraryItem::Bitmap(anicraft_engine::doc::BitmapId(b))), + (None, Some(snd)) => app.library_sel = Some(anicraft_engine::doc::LibraryItem::Sound(anicraft_engine::doc::SoundId(snd))), + _ => {} + } + match folder.and_then(|f| app.s.doc.folder(f)).map(|f| f.name.clone()) { + Some(name) => trn!("Added {n} file to “{folder}” in the Library", "Added {n} files to “{folder}” in the Library", n, folder = name), + None => trn!("Added {n} file to the Library", "Added {n} files to the Library", n), + } + }) + } + _ => { + let geo = app.drop.stage; + if geo.is_some_and(|g| g.paused) { + app.status_ok(tr!("Previewing through the camera: artwork edits are paused. Turn off View › Preview Through Camera to edit.")); + return; + } + let (centred, (x, y)) = match spot { + Spot::Stage(x, y) => (false, (x, y)), + _ => { + let c = app.view_center_stage(); + let c = match app.s.edit_view() { + Some(v) if v.scale.abs() > 1e-6 => ((c.x - v.origin.x) / v.scale, (c.y - v.origin.y) / v.scale), + _ => (c.x, c.y), + }; + (true, c) + } + }; + let v = app.run("file.drop", json!({"paths": paths, "to": "stage", "x": x, "y": y})); + v.map(|_| { + let layer = app.s.active_layer().map(|l| l.name.clone()).unwrap_or_default(); + let (frame, undo) = (app.s.frame + 1, app.undo_key()); + if centred { + trn!("Placed {n} file on {layer} at frame {frame}, in the middle of the view — {undo} to undo", "Placed {n} files on {layer} at frame {frame}, in the middle of the view — {undo} to undo", n, layer = layer, frame = frame, undo = undo) + } else { + trn!("Placed {n} file on {layer} at frame {frame} — {undo} to undo", "Placed {n} files on {layer} at frame {frame} — {undo} to undo", n, layer = layer, frame = frame, undo = undo) + } + }) + } + }; + if let Some(msg) = done { + app.decode_sounds(); + match plan.left_out.first() { + Some((p, why)) => app.status_ok(tr!("{done}. Left out {file}: {why}", done = msg, file = crate::recent::display_name(p), why = why)), + None => app.status_ok(msg), + } + } +} + +/// A name for a file the browser describes only by its type while it is dragged. +fn guess_name(mime: &str) -> &'static str { + match mime { + "image/svg+xml" => "drawing.svg", + "image/png" => "image.png", + "image/jpeg" => "image.jpg", + "audio/wav" | "audio/x-wav" | "audio/wave" => "sound.wav", + "audio/ogg" => "sound.ogg", + "audio/mpeg" | "audio/mp3" => "sound.mp3", + _ => "", + } +} + +/// Where a previewed drag hovers on screen: the stage's middle, or the Library's first folder. +fn preview_point(app: &App, at: PreviewAt) -> Option { + match at { + PreviewAt::Stage => app.drop.stage.map(|g| g.canvas.center() + vec2(-g.canvas.width() * 0.12, -g.canvas.height() * 0.08)), + PreviewAt::Library => app.library.drop_zone.rows.iter().find(|(_, f)| f.is_some()).map(|(r, _)| r.center()), + } +} + +/// The drop highlight: what lands where, drawn over everything. +fn highlight(app: &App, ctx: &egui::Context, files: &[PathBuf], p: Option) { + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("file_drop"))); + let screen = ctx.content_rect().shrink(3.0); + // Only the names are known while a browser drags (and sometimes not even those). + let known: Vec<&PathBuf> = files.iter().filter(|f| !f.as_os_str().is_empty()).collect(); + let docs: Vec<&&PathBuf> = known.iter().filter(|f| kind_of(f) == DropKind::Document).collect(); + let stroke = Stroke::new(2.0, T.accent); + let label = |at: Pos2, text: String, ok: bool| { + let c = if ok { color(Type::Body) } else { T.error }; + let galley = painter.layout_no_wrap(text, font(Type::Label), c); + let r = Rect::from_min_size(at, vec2(galley.rect.width(), galley.rect.height())).expand(6.0); + // Kept on screen. + let r = r.translate(vec2((screen.right() - r.right()).min(0.0), (screen.bottom() - r.bottom()).min(0.0))); + painter.rect_filled(r, T.rc(), T.panel); + painter.rect_stroke(r, T.rc(), Stroke::new(1.0, if ok { T.accent } else { T.error }), StrokeKind::Inside); + painter.galley(r.min + vec2(6.0, 6.0), galley, c); + }; + if let Some(doc) = docs.first() { + painter.rect_stroke(screen, T.rc(), stroke, StrokeKind::Inside); + let text = if app.s.is_dirty() { tr!("Open {name} (you'll be asked about unsaved changes)", name = crate::recent::display_name(doc)) } else { tr!("Open {name}", name = crate::recent::display_name(doc)) }; + label(screen.center_top() + vec2(-120.0, 12.0), text, true); + return; + } + let spot = spot_at(app, p); + let what = match known.len() { + 0 => tr!("these files").to_string(), + 1 => crate::recent::display_name(known[0]), + n => trn!("{n} file", "{n} files", n), + }; + let fits = |to: DropTarget| known.iter().all(|f| matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary)); + match (spot, p) { + (Spot::Stage(..), Some(p)) => { + if let Some(g) = app.drop.stage { + painter.rect_stroke(g.canvas.shrink(1.0), crate::theme::SQUARE, stroke, StrokeKind::Inside); + } + let r = 8.0; + painter.line_segment([p - vec2(r, 0.0), p + vec2(r, 0.0)], Stroke::new(1.5, T.accent)); + painter.line_segment([p - vec2(0.0, r), p + vec2(0.0, r)], Stroke::new(1.5, T.accent)); + let ok = fits(DropTarget::Stage); + let layer = app.s.active_layer().map(|l| l.name.clone()).unwrap_or_default(); + let text = if ok { tr!("Place {what} on {layer} at frame {frame}", what = what, layer = layer, frame = app.s.frame + 1) } else { refusal(DropKind::Unsupported, DropTarget::Stage, false) }; + label(p + vec2(14.0, 12.0), text, ok); + } + (Spot::Library(folder), Some(p)) => { + let zone = &app.library.drop_zone; + match zone.row_at(p).filter(|_| folder.is_some()) { + Some(row) => { + painter.rect_stroke(row, T.rc(), stroke, StrokeKind::Inside); + } + None => { + if let Some(panel) = zone.panel { + painter.rect_stroke(panel, T.rc(), stroke, StrokeKind::Inside); + } + } + } + let ok = fits(DropTarget::Library); + let text = match (ok, folder.and_then(|f| app.s.doc.folder(f))) { + (true, Some(f)) => tr!("Add {what} to “{folder}”", what = what, folder = f.name), + (true, None) => tr!("Add {what} to the Library", what = what), + (false, _) => match known.iter().find(|f| !fits_one(f, DropTarget::Library)) { + Some(f) => refusal(kind_of(f), DropTarget::Library, false), + None => refusal(DropKind::Unsupported, DropTarget::Library, false), + }, + }; + label(p + vec2(14.0, 12.0), text, ok); + } + (Spot::Unknown, _) => { + // The desktop doesn't say where the pointer is during a drag: say what each place does. + painter.rect_stroke(screen, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); + label(screen.center_top() + vec2(-180.0, 12.0), tr!("Drop {what} on the stage to place it, or on the Library to add it", what = what), true); + } + (spot, p) => { + let at = p.unwrap_or(screen.center_top()) + vec2(14.0, 12.0); + label(at, refusal(known.first().map_or(DropKind::Image, |f| kind_of(f)), DropTarget::Window, spot == Spot::Start), false); + } + } +} + +fn fits_one(f: &Path, to: DropTarget) -> bool { + matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p(s: &str) -> PathBuf { + PathBuf::from(s) + } + + #[test] + fn drops_are_routed_by_type_and_target() { + // A document opens wherever it lands, and only one at a time. + for spot in [Spot::Stage(1.0, 2.0), Spot::Library(None), Spot::Window, Spot::Start, Spot::Unknown] { + let plan = plan(&[p("walk.anicraft"), p("photo.png"), p("old.fla")], spot); + assert_eq!(plan.open, Some(p("walk.anicraft")), "{spot:?}"); + assert!(plan.import.is_empty()); + assert_eq!(plan.left_out.len(), 2); + } + let plan_at = |spot| plan(&[p("a.svg"), p("b.png"), p("c.mp3"), p("d.psd")], spot); + // On the stage: everything AniCraft reads, the rest left out with a reason. + let on_stage = plan_at(Spot::Stage(10.0, 20.0)); + assert_eq!((on_stage.to, on_stage.import.len(), on_stage.left_out.len()), (Some(DropTarget::Stage), 3, 1)); + assert!(on_stage.left_out[0].1.contains("SVG"), "says what AniCraft reads"); + // On the Library: images and sounds; a drawing is pointed to the stage. + let in_library = plan_at(Spot::Library(Some(FolderId(7)))); + assert_eq!((in_library.to, in_library.import.len(), in_library.left_out.len()), (Some(DropTarget::Library), 2, 2)); + assert!(in_library.left_out.iter().any(|(f, why)| f == &p("a.svg") && why.contains("stage"))); + // Elsewhere on the window, or over the start screen: nothing imports. + for spot in [Spot::Window, Spot::Start] { + let plan = plan_at(spot); + assert!(plan.import.is_empty() && plan.to.is_none() && plan.left_out.len() == 4, "{spot:?}"); + } + // No pointer position: the stage, at the middle of the view. + assert_eq!(plan_at(Spot::Unknown).to, Some(DropTarget::Stage)); + // Only unsupported files: nothing to do but say why. + let plan = plan(&[p("notes.txt")], Spot::Stage(0.0, 0.0)); + assert!(plan.to.is_none() && plan.open.is_none() && plan.left_out.len() == 1); + } + + #[test] + fn a_drop_lands_where_the_layout_says() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(PathBuf::from("unused.png"))); + app.run("library.new_folder", json!({"name": "Props"})); + let screen = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() }; + for _ in 0..3 { + let mut out = ctx.run_ui(screen.clone(), |ui| app.frame(ui)); + out.textures_delta.clear(); + } + let geo = app.drop.stage.expect("the stage drew"); + // The middle of the canvas maps into the stage. + match spot_at(&app, Some(geo.canvas.center())) { + Spot::Stage(x, y) => assert!(x.is_finite() && y.is_finite()), + other => panic!("{other:?}"), + } + let (row, folder) = *app.library.drop_zone.rows.iter().find(|(_, f)| f.is_some()).expect("the folder row drew"); + assert_eq!(spot_at(&app, Some(row.center())), Spot::Library(folder)); + assert_eq!(spot_at(&app, Some(egui::pos2(1.0, 1.0))), Spot::Window, "the menu bar takes nothing"); + assert_eq!(spot_at(&app, None), Spot::Unknown); + crate::start::open(&mut app); + assert_eq!(spot_at(&app, Some(geo.canvas.center())), Spot::Start); + } + + #[test] + fn dropped_media_land_on_the_stage_or_in_a_library_folder() { + let dir = std::env::temp_dir().join(format!("anicraft-shell-drop-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png = dir.join("dot.png"); + std::fs::write(&png, anicraft_engine::render::encode_png(2, 2, &[200u8; 16]).unwrap()).unwrap(); + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(PathBuf::from("unused.png"))); + let bitmaps = app.s.doc.bitmaps.len(); + run(&mut app, std::slice::from_ref(&png), Spot::Stage(50.0, 40.0)); + assert_eq!(app.s.doc.bitmaps.len(), bitmaps + 1); + assert_eq!(app.s.selection.len(), 1); + assert!(app.status.as_ref().is_some_and(|s| !s.error), "{:?}", app.status.as_ref().map(|s| &s.text)); + let folder = app.run("library.new_folder", json!({"name": "Props"})).and_then(|v| v["folder"].as_u64()).map(FolderId).unwrap(); + run(&mut app, std::slice::from_ref(&png), Spot::Library(Some(folder))); + assert_eq!(app.s.doc.folder_contents(folder).len(), 1); + assert!(app.library.expanded.contains(&folder), "the folder opens to show it"); + // An unsupported file: one clear message, nothing changes. + let before = app.s.doc.clone(); + run(&mut app, &[dir.join("notes.txt")], Spot::Stage(0.0, 0.0)); + assert!(app.s.doc == before); + assert!(app.status.as_ref().is_some_and(|s| s.error && s.text.contains("notes.txt"))); + // A document over unsaved work asks first. + run(&mut app, &[dir.join("other.anicraft")], Spot::Stage(0.0, 0.0)); + assert!(app.confirm.is_some()); + } +} diff --git a/src/guidelines_tests.rs b/src/guidelines_tests.rs index 02dc4682..937a86a4 100644 --- a/src/guidelines_tests.rs +++ b/src/guidelines_tests.rs @@ -1,6 +1,9 @@ //! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values. -const SOURCES: [(&str, &str); 20] = [ +const SOURCES: [(&str, &str); 23] = [ + ("drop.rs", include_str!("drop.rs")), + ("recent.rs", include_str!("recent.rs")), + ("start.rs", include_str!("start.rs")), ("actions_panel.rs", include_str!("actions_panel.rs")), ("test_movie.rs", include_str!("test_movie.rs")), ("autosave.rs", include_str!("autosave.rs")), diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 8a29f683..37233515 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -587,7 +587,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("element.set_color_effect", serde_json::json!({"style": style})); })); } - for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol"] { + for panel in ["start", "sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] { @@ -777,7 +777,7 @@ fn screen_reader_names_are_translated_too() { found.extend(untranslated_names("library item", |a, _| { a.library_sel = a.s.doc.library.first().map(|s| crate::app::LibraryItem::Symbol(s.id)); })); - for panel in ["select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testscript", "exporthtml", "envelope"] { + for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testscript", "exporthtml", "envelope"] { found.extend(untranslated_names(panel, |a, _| a.open_panel(Some(panel)))); } assert!(found.is_empty(), "{} screen-reader names not translated in the pseudo-locale:\n{}", found.len(), found.join("\n")); diff --git a/src/library.rs b/src/library.rs index ea2f72e4..da9afdc4 100644 --- a/src/library.rs +++ b/src/library.rs @@ -58,6 +58,33 @@ pub struct LibraryView { list_rect: Option, uses: Option<(StateId, HashMap, HashSet)>, preview: Option, + /// Where files dropped from the desktop land this frame (ADR 0059). + pub drop_zone: DropZone, +} + +/// The Library as a target for files dropped from the desktop (ADR 0059): the panel, and each +/// row with the folder a file dropped on it goes into. Cleared every frame before the panels +/// draw, so a hidden panel takes nothing. +#[derive(Default)] +pub struct DropZone { + pub panel: Option, + pub rows: Vec<(Rect, Option)>, +} + +impl DropZone { + /// The folder a file dropped at `p` goes into (`None` inside: the top level), or `None` + /// outside the panel. + pub fn folder_at(&self, p: Pos2) -> Option> { + if !self.panel.is_some_and(|r| r.contains(p)) { + return None; + } + Some(self.rows.iter().find(|(r, _)| r.contains(p)).and_then(|(_, f)| *f)) + } + + /// The row a drop at `p` lands on (a folder row, or the row inside that folder). + pub fn row_at(&self, p: Pos2) -> Option { + self.rows.iter().find(|(r, _)| r.contains(p)).map(|(r, _)| *r) + } } /// The current item's preview picture, and what it was made from. @@ -558,6 +585,7 @@ fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet Some(f), e => app.s.doc.parent_of(e), }; + app.library.drop_zone.rows.push((r.intersect(ui.clip_rect()), target)); if let Some(payload) = resp.dnd_hover_payload::>() && !payload.contains(&row.entry) { diff --git a/src/main.rs b/src/main.rs index 5f14701b..b83e1287 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,6 +32,7 @@ mod bone_tool; mod camera_tool; mod convert_symbol; mod dialogs; +mod drop; mod gpu_stage; mod icons; mod keymap; @@ -46,10 +47,12 @@ mod pathtools; mod platform; mod plugins_ui; mod prefs; +mod recent; mod scale_grid; mod sound; mod shape_hints; mod stage; +mod start; mod test_movie; mod theme; mod timeline; @@ -108,11 +111,17 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o // `--lang` before the window exists, so its first status line is in that language too. i18n::force(look.lang.as_deref()); let (session, report) = open_session(file); + let file_given = file.map(Path::to_path_buf); eframe::run_native( "AniCraft", options, Box::new(move |cc| { + let starting_fresh = file_given.is_none() && shot.is_none(); let mut a = app::App::new(cc, session, shot); + // No document to open: the start screen, unless it was switched off (ADR 0059). + if starting_fresh && a.prefs.start_screen { + start::open(&mut a); + } a.preview_look(&cc.egui_ctx, look.theme, look.scale); a.open_panel(open.as_deref()); // An imported document says what came across, as opening it from the menu does. @@ -180,7 +189,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu|colour]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu|colour]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/menus.rs b/src/menus.rs index 5eda634a..d5fd6612 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -140,6 +140,13 @@ fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option fn registry_items(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpec]) { for spec in cmds.iter().filter(|c| c.menu == top) { item(app, ui, spec); + if spec.id == "file.open" { + // Below Open, as in Animate: the recent files, and the start screen (ADR 0059). + ui.menu_button(tr!("Open Recent"), |ui| crate::recent::menu(app, ui)); + if ui_item(ui, tr!("Start Screen"), "", None) { + crate::start::open(app); + } + } } let mut subs: Vec<&str> = Vec::new(); for c in cmds { diff --git a/src/panels.rs b/src/panels.rs index 7cb27262..817c02e1 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -2095,5 +2095,7 @@ fn ease_curve(ui: &mut egui::Ui, e: anicraft_engine::doc::Easing) { } fn library(app: &mut App, ui: &mut egui::Ui) { - crate::library::panel(app, ui); + // Where the panel is, for files dropped on it (ADR 0059). + let r = ui.scope(|ui| crate::library::panel(app, ui)).response.rect; + app.library.drop_zone.panel = Some(r); } diff --git a/src/platform.rs b/src/platform.rs index 551fd8a5..b612b7c7 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -167,6 +167,29 @@ pub fn save_settings(json: &str) -> Result<(), String> { } } +/// A recent file's start-screen picture (ADR 0059): `Thumbnails/.png` in the settings +/// folder, or browser storage on the web. `None` when there is none yet. +pub fn load_thumbnail(key: &str) -> Option> { + #[cfg(target_arch = "wasm32")] + return crate::web::storage_get(&format!("anicraft.thumb.{key}")).and_then(|t| anicraft_engine::doc::base64_decode(&t)); + #[cfg(not(target_arch = "wasm32"))] + config_dir().and_then(|d| std::fs::read(d.join("Thumbnails").join(format!("{key}.png"))).ok()) // i18n-exempt: a folder name +} + +/// Keeps a recent file's picture (a small PNG) for the start screen. +pub fn save_thumbnail(key: &str, png: &[u8]) -> Result<(), String> { + #[cfg(target_arch = "wasm32")] + return crate::web::storage_set(&format!("anicraft.thumb.{key}"), &anicraft_engine::doc::base64_encode(png)); + #[cfg(not(target_arch = "wasm32"))] + { + let dir = config_dir().ok_or(tr!("no settings folder on this system"))?.join("Thumbnails"); // i18n-exempt: a folder name + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let (path, tmp) = (dir.join(format!("{key}.png")), dir.join(format!("{key}.png.tmp"))); + std::fs::write(&tmp, png).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, &path).map_err(|e| e.to_string()) + } +} + /// Why this build can't run `cmd`, if it can't: a web page can't start ffmpeg or keep files in /// a folder of the computer (ADR 0036). The desktop app runs everything. pub fn unavailable(cmd: &str) -> Option<&'static str> { diff --git a/src/prefs.rs b/src/prefs.rs index 256bdd5a..595e8c48 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -90,6 +90,12 @@ pub struct Prefs { pub autosave_edits: u32, /// Onion skin options (ADR 0047), kept from session to session. pub onion: OnionPrefs, + /// File › Open Recent and the start screen's list (ADR 0059): pinned favourites, then the + /// last 10 documents opened or saved. + #[serde(deserialize_with = "lenient_recent")] + pub recent: anicraft_engine::cmds_recent::RecentFiles, + /// Show the start screen when AniCraft starts without a document to open (ADR 0059). + pub start_screen: bool, } /// Onion skin options that carry over between sessions (ADR 0047). Whether onion skin and Edit @@ -140,10 +146,25 @@ impl Default for Prefs { autosave_secs: 60, autosave_edits: 25, onion: OnionPrefs::default(), + recent: Default::default(), + start_screen: true, } } } +/// The recent files as written, skipping entries that aren't one (a hand-edited file): one bad +/// entry must not reset every preference. +fn lenient_recent<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + use anicraft_engine::cmds_recent::{RecentFile, RecentFiles}; + let v = serde_json::Value::deserialize(d)?; + let list: Vec = match v { + serde_json::Value::Array(a) => a.into_iter().take(1000).collect(), + _ => Vec::new(), + }; + let good: Vec = list.into_iter().filter_map(|x| serde_json::from_value::(x).ok()).collect(); + Ok(serde_json::from_value::(serde_json::to_value(good).unwrap_or_default()).unwrap_or_default()) +} + /// Autosave intervals offered in Preferences: `(seconds, label)`. pub const AUTOSAVE_INTERVALS: [(u32, &str); 5] = [(30, tr_noop!("30 seconds")), (60, tr_noop!("1 minute")), (120, tr_noop!("2 minutes")), (300, tr_noop!("5 minutes")), (600, tr_noop!("10 minutes"))]; pub const AUTOSAVE_SECS_RANGE: std::ops::RangeInclusive = 15..=600; @@ -171,6 +192,7 @@ impl Prefs { self.autosave_edits = self.autosave_edits.min(*AUTOSAVE_EDITS_RANGE.end()); self.onion.before = self.onion.before.min(ONION_REACH_MAX); self.onion.after = self.onion.after.min(ONION_REACH_MAX); + self.recent = std::mem::take(&mut self.recent).sanitized(); self } @@ -273,5 +295,16 @@ mod tests { let p = Prefs::from_json(r#"{"autosave": false, "autosave_secs": 1, "autosave_edits": 99999999}"#); assert!(!p.autosave); assert_eq!((p.autosave_secs, p.autosave_edits), (15, 1000)); + // Older files have no recent files and show the start screen (ADR 0059); a list + // someone edited by hand is cleaned up. + let p = Prefs::from_json(r#"{"ui_scale": 1.25}"#); + assert!(p.recent.is_empty() && p.start_screen); + let p = Prefs::from_json(r#"{"recent": [{"path": "a.anicraft"}, {"path": "a.anicraft"}, {"path": ""}, 7], "start_screen": false}"#); + let paths: Vec<_> = p.recent.entries().iter().map(|e| e.path.display().to_string()).collect(); + assert_eq!(paths, ["a.anicraft"], "bad entries are skipped, the rest kept"); + assert!(!p.start_screen, "and the other preferences with them"); + let p = Prefs::from_json(r#"{"recent": [{"path": "b.anicraft"}, {"path": "a.anicraft", "pinned": true}, {"path": "b.anicraft"}]}"#); + let paths: Vec<_> = p.recent.entries().iter().map(|e| (e.path.display().to_string(), e.pinned)).collect(); + assert_eq!(paths, [("a.anicraft".to_string(), true), ("b.anicraft".to_string(), false)]); } } diff --git a/src/recent.rs b/src/recent.rs new file mode 100644 index 00000000..378748fa --- /dev/null +++ b/src/recent.rs @@ -0,0 +1,193 @@ +//! Recent files in the window (ADR 0059): File › Open Recent, the list kept in the preferences, +//! and the thumbnails the start screen shows. The list itself is the session's +//! (`anicraft_engine::cmds_recent`): `file.open` and `file.save` add to it, the `prefs.recent_*` +//! commands change it, and the window copies it into the preferences whenever it changes. + +use crate::app::App; +use crate::platform; +use crate::theme::{Type, text}; +use anicraft_engine::cmds_recent::{self, RecentFile}; +use serde_json::json; +use std::collections::HashMap; +use std::path::Path; + +/// Thumbnails loaded for the start screen, by thumbnail key (`None`: there is none). +#[derive(Default)] +pub struct Thumbs { + loaded: HashMap>, + /// Pictures made in memory (screenshot runs show sample entries without touching disk). + pub(crate) seeded: HashMap>, +} + +impl Thumbs { + /// The picture of `path`, decoded and uploaded once. + pub fn get(&mut self, ctx: &egui::Context, path: &Path) -> Option { + let key = cmds_recent::thumb_key(path); + if let Some(t) = self.loaded.get(&key) { + return t.clone(); + } + let png = self.seeded.get(&key).cloned().or_else(|| platform::load_thumbnail(&key)); + let tex = png.and_then(|png| anicraft_engine::doc::decode_png(&png)).and_then(|px| { + let (w, h) = (usize::try_from(px.width).ok()?, usize::try_from(px.height).ok()?); + (w > 0 && h > 0 && px.rgba.len() == w * h * 4).then(|| ctx.load_texture(format!("recent-{key}"), egui::ColorImage::from_rgba_unmultiplied([w, h], &px.rgba), egui::TextureOptions::LINEAR)) + }); + self.loaded.insert(key, tex.clone()); + tex + } + + /// Forgets `path`'s picture, so the next look reads the new one. + pub fn invalidate(&mut self, path: &Path) { + self.loaded.remove(&cmds_recent::thumb_key(path)); + } +} + +/// The picture of the open document's first frame, kept for `path` (after a save or an open). +/// Screenshot and test runs keep nothing on disk. +pub fn capture(app: &mut App, path: &Path) { + if app.shot.is_some() { + return; + } + let t = web_time::Instant::now(); + match cmds_recent::thumbnail_png(&app.s.doc) { + Ok(png) => { + if let Err(e) = platform::save_thumbnail(&cmds_recent::thumb_key(path), &png) { + eprintln!("could not keep the thumbnail of {}: {e}", path.display()); + } + app.thumbs.invalidate(path); + } + Err(e) => eprintln!("could not draw the thumbnail of {}: {e}", path.display()), + } + if cfg!(debug_assertions) { + eprintln!("thumbnail of {} in {:.1} ms", path.display(), t.elapsed().as_secs_f64() * 1000.0); + } +} + +/// After a document was opened: a picture if it has none yet (one made on save is kept). +pub fn captured_on_open(app: &mut App, path: &Path) { + if app.shot.is_none() && platform::load_thumbnail(&cmds_recent::thumb_key(path)).is_none() { + capture(app, path); + } +} + +/// Copies the session's list into the preferences when a command changed it, and saves them +/// (not in screenshot or test runs, which never write the user's preferences). +pub fn sync(app: &mut App) { + if app.s.recent == app.prefs.recent { + return; + } + app.prefs.recent = app.s.recent.clone(); + if app.shot.is_none() + && let Err(e) = app.prefs.save() + { + app.status_err(tr!("Could not save preferences: {e}", e = e)); + } +} + +/// The file's name, as the menu and the start screen show it. +pub fn display_name(path: &Path) -> String { + path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()) +} + +/// The name of the folder it is in. +pub fn folder_name(path: &Path) -> String { + path.parent().and_then(Path::file_name).map_or_else(String::new, |n| n.to_string_lossy().into_owned()) +} + +/// The recent files with whether each is still there. +pub fn entries(app: &App) -> Vec<(usize, RecentFile, bool)> { + app.s.recent.entries().iter().enumerate().map(|(i, e)| (i, e.clone(), !cmds_recent::exists(&e.path))).collect() +} + +/// File › Open Recent: pinned favourites, then the last files; a missing file is greyed out +/// with Remove beside it. Every action is a command. +pub fn menu(app: &mut App, ui: &mut egui::Ui) { + ui.set_min_width(320.0); + let list = entries(app); + if list.is_empty() { + ui.label(text(Type::Caption, tr!("No recent files yet. Documents you open or save show here."))); + return; + } + let mut act: Option<(&'static str, serde_json::Value)> = None; + let mut last_pinned = list.first().is_some_and(|(_, e, _)| e.pinned); + if last_pinned { + ui.label(text(Type::Caption, tr!("Pinned"))); + } + for (i, e, missing) in &list { + if last_pinned && !e.pinned { + ui.separator(); + last_pinned = false; + } + let name = display_name(&e.path); + ui.horizontal(|ui| { + let label = if *missing { tr!("{name} (missing)", name = name) } else { name.clone() }; + let r = ui.add_enabled(!*missing, egui::Button::new(label).min_size(egui::vec2(200.0, 0.0))); + let tip = e.path.display().to_string(); + let r = if *missing { r.on_disabled_hover_text(tr!("{path} is no longer there", path = tip)) } else { r.on_hover_text(tip) }; + if r.clicked() { + act = Some(("file.open_recent", json!({"index": i}))); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if *missing { + if ui.small_button(tr!("Remove")).on_hover_text(tr!("Take it off the list")).clicked() { + act = Some(("prefs.recent_remove", json!({"index": i}))); + } + } else if ui.small_button(if e.pinned { tr!("Unpin") } else { tr!("Pin") }).on_hover_text(if e.pinned { tr!("Let it move down the list again") } else { tr!("Keep it at the top of the list") }).clicked() { + act = Some(("prefs.recent_pin", json!({"index": i}))); + } + }); + }); + } + ui.separator(); + if ui.button(tr!("Clear Recent Files")).on_hover_text(tr!("Pinned files stay")).clicked() { + act = Some(("prefs.recent_clear", json!({}))); + } + if let Some((id, params)) = act { + // Opening keeps the menu's promise; pinning and removing keep the menu open. + if id == "file.open_recent" { + ui.close(); + } + open_or_run(app, id, params); + } +} + +/// Runs a recent-files command from a menu or the start screen; opening goes through +/// `request`, so unsaved work asks first. +pub fn open_or_run(app: &mut App, id: &str, params: serde_json::Value) { + if id == "file.open_recent" { + app.request(id, params); + } else if let Some(v) = app.run(id, params) + && id == "prefs.recent_clear" + { + let n = v["removed"].as_u64().unwrap_or(0) as usize; + app.status_ok(trn!("Cleared {n} recent file", "Cleared {n} recent files", n)); + } +} + +/// Sample entries for screenshot and test runs (`--open start`): two documents made from the +/// samples in a scratch folder (one pinned), and one that is missing. Their pictures stay in +/// memory; nothing goes into the settings folder. +pub fn sample_entries(app: &mut App) { + let folder = std::env::temp_dir().join("AniCraft samples"); // i18n-exempt: a folder name + let _ = anicraft_engine::vfs::create_dir_all(&folder); + let docs = [("Bouncing ball.anicraft", Some(anicraft_engine::doc::sample::demo()), true), ("Title card.anicraft", Some(anicraft_engine::doc::sample::interactive()), false), ("Old walk cycle.anicraft", None, false)]; // i18n-exempt: sample file names + let mut list = anicraft_engine::cmds_recent::RecentFiles::default(); + for (name, doc, pinned) in docs.into_iter().rev() { + let path = folder.join(name); + match doc { + Some(doc) => { + if let Ok(png) = cmds_recent::thumbnail_png(&doc) { + app.thumbs.seeded.insert(cmds_recent::thumb_key(&path), png); + } + let _ = anicraft_engine::format::save(&doc, &path); + } + None => { + let _ = anicraft_engine::vfs::remove_file(&path); + } + } + list.add(&path); + if pinned { + let _ = list.pin(&path, true); + } + } + app.s.recent = list; +} diff --git a/src/stage.rs b/src/stage.rs index fb2c2427..583b6e86 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -264,6 +264,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let cam_geo = crate::camera_tool::Geo { origin: st_origin, zoom: st_zoom, stage_rect, preview }; // Library items dragged onto the stage land at the pointer (ADR 0053). crate::library::stage_drop(app, ui, &resp, to_stage, preview); + // Files dropped from the desktop land here too (ADR 0059). + app.drop.stage = Some(crate::drop::StageGeo { canvas, origin, zoom, paused: preview }); // ---- tools ---------------------------------------------------------------------------- diff --git a/src/start.rs b/src/start.rs new file mode 100644 index 00000000..c5cee4af --- /dev/null +++ b/src/start.rs @@ -0,0 +1,315 @@ +//! The start screen (ADR 0059): what AniCraft shows when it starts without a document to open, +//! as Animate's Home screen does. New with stage-size presets (and a custom size), Open, the +//! recent files with their pictures, and the sample animation. It takes the place of the +//! workspace, never sits over it as a dialog: the menus keep working, Esc goes back to the +//! document, and New, Open or a recent file dismisses it once the document is there. + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::icons::{self, Icon}; +use crate::theme::{T, TARGET, Type, color, font, text}; +use egui::{Align2, Rect, Sense, Stroke, StrokeKind, Vec2, WidgetType, pos2, vec2}; +use serde_json::json; + +/// A New preset: its name (English, translated where drawn), stage width and height. +pub struct Preset { + pub name: &'static str, + pub width: u32, + pub height: u32, +} + +/// The sizes artists start from most: video in HD and Full HD, square and vertical social posts. +pub const PRESETS: [Preset; 4] = [ + Preset { name: tr_noop!("HD video"), width: 1280, height: 720 }, + Preset { name: tr_noop!("Full HD video"), width: 1920, height: 1080 }, + Preset { name: tr_noop!("Square post"), width: 1080, height: 1080 }, + Preset { name: tr_noop!("Vertical story"), width: 1080, height: 1920 }, +]; + +/// The frame rates offered for a new document. +pub const RATES: [f32; 5] = [12.0, 24.0, 25.0, 30.0, 60.0]; + +/// What the start screen holds between frames: the custom size being typed. +pub struct StartScreen { + pub width: u32, + pub height: u32, + pub fps: f32, +} + +impl Default for StartScreen { + fn default() -> Self { + let d = anicraft_engine::doc::Stage::default(); + StartScreen { width: d.width, height: d.height, fps: d.fps } + } +} + +/// `file.new`'s params for a size and rate. +pub fn new_params(width: u32, height: u32, fps: f32) -> serde_json::Value { + json!({"width": width, "height": height, "fps": fps}) +} + +/// Shows the start screen (File › Start Screen, and at launch). +pub fn open(app: &mut App) { + app.playing = false; + app.start = Some(StartScreen { fps: app.s.doc.stage.fps, ..StartScreen::default() }); + app.status_ok(tr!("Pick a size to start a new animation, or open one you made. Esc goes back to the document.")); +} + +/// The start screen in the space the workspace normally takes. +pub fn show(app: &mut App, ui: &mut egui::Ui) { + if ui.input(|i| i.key_pressed(egui::Key::Escape)) && !app.modal_open() { + app.start = None; + return; + } + let ctx = ui.ctx().clone(); + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + let width = ui.available_width().min(1120.0); + let pad = ((ui.available_width() - width) / 2.0).max(24.0); + ui.add_space(28.0); + ui.horizontal(|ui| { + ui.add_space(pad); + ui.vertical(|ui| { + ui.set_width(width - 48.0); + header(app, ui, &ctx); + ui.add_space(20.0); + ui.columns(2, |cols| { + if let [left, right] = cols { + new_column(app, left); + open_column(app, right, &ctx); + } + }); + ui.add_space(16.0); + footer(app, ui); + }); + }); + ui.add_space(28.0); + }); +} + +fn header(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context) { + ui.horizontal(|ui| { + ui.add(egui::Image::new((crate::app::app_mark(ctx).id(), vec2(44.0, 44.0)))); + ui.add_space(8.0); + ui.vertical(|ui| { + ui.label(text(Type::Title, "AniCraft")); // i18n-exempt: the product name + ui.label(text(Type::Caption, tr!("Version {version} · {stage}", version = env!("CARGO_PKG_VERSION"), stage = crate::i18n::t(crate::app::RELEASE_STAGE)))); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let back = ui.add(egui::Button::new(tr!("Back to the document")).shortcut_text(text(Type::Key, "Esc"))); // i18n-exempt: a key name + if back.on_hover_text(tr!("The document that is open stays as it is")).clicked() { + app.start = None; + } + }); + }); +} + +/// A preset tile: the stage's shape drawn to scale, its name and size. +fn tile(ui: &mut egui::Ui, name: &str, w: u32, h: u32) -> egui::Response { + let size = vec2(118.0, 112.0); + let (r, resp) = ui.allocate_exact_size(size, Sense::click()); + let size_text = format!("{w} × {h}"); + a11y::control(ui, &resp, WidgetType::Button, &tr!("New {name}, {size}", name = name, size = size_text), None); + let p = ui.painter(); + let hot = resp.hovered() || resp.has_focus(); + p.rect_filled(r, T.rc(), if hot { T.hover } else { T.panel_alt }); + p.rect_stroke(r, T.rc(), Stroke::new(1.0, if hot { T.accent } else { T.border }), StrokeKind::Inside); + // The stage's aspect, in a 64-point box. + let box_ = Rect::from_center_size(pos2(r.center().x, r.top() + 38.0), vec2(64.0, 52.0)); + let aspect = w.max(1) as f32 / h.max(1) as f32; + let shape = if aspect >= box_.width() / box_.height() { vec2(box_.width(), box_.width() / aspect) } else { vec2(box_.height() * aspect, box_.height()) }; + p.rect_filled(Rect::from_center_size(box_.center(), shape), crate::theme::SQUARE, T.text_faint); + p.text(pos2(r.center().x, r.bottom() - 34.0), Align2::CENTER_CENTER, name, font(Type::Label), color(Type::Body)); + p.text(pos2(r.center().x, r.bottom() - 16.0), Align2::CENTER_CENTER, size_text, font(Type::DataSmall), T.text_dim); + a11y::focus_ring(ui, &resp); + resp +} + +fn new_column(app: &mut App, ui: &mut egui::Ui) { + ui.label(text(Type::Heading, tr!("Create new"))); + ui.add_space(6.0); + let fps = app.start.as_ref().map_or(24.0, |s| s.fps); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(10.0, 10.0); + for p in &PRESETS { + if tile(ui, crate::i18n::t(p.name), p.width, p.height).clicked() { + app.request("file.new", new_params(p.width, p.height, fps)); + } + } + }); + ui.add_space(12.0); + ui.label(text(Type::Label, tr!("Custom size"))); + let Some(st) = app.start.as_mut() else { return }; + let max = anicraft_engine::doc::MAX_STAGE_EDGE; + let mut create = false; + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut st.width).range(1..=max).suffix(" px")).named(tr!("Custom width")); // i18n-exempt: a unit + ui.label(text(Type::Data, "×")); // i18n-exempt: a symbol + ui.add(egui::DragValue::new(&mut st.height).range(1..=max).suffix(" px")).named(tr!("Custom height")); // i18n-exempt: a unit + ui.add_space(8.0); + egui::ComboBox::from_id_salt("start_fps") + .selected_text(text(Type::Data, tr!("{fps} fps", fps = st.fps))) + .show_ui(ui, |ui| { + for r in RATES { + ui.selectable_value(&mut st.fps, r, text(Type::Data, tr!("{fps} fps", fps = r))); + } + }) + .response + .set_name(tr!("Frame rate")); + ui.add_space(8.0); + create = ui.add(egui::Button::new(tr!("Create")).min_size(vec2(0.0, TARGET))).clicked(); + }); + ui.label(text(Type::Caption, tr!("The frame rate is for every new document made here. Change the size later in Modify › Document Settings."))); + let (w, h, f) = (st.width, st.height, st.fps); + if create { + app.request("file.new", new_params(w, h, f)); + } +} + +fn open_column(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context) { + ui.label(text(Type::Heading, tr!("Open"))); + ui.add_space(6.0); + ui.horizontal(|ui| { + if ui.add(egui::Button::new(tr!("Open…")).min_size(vec2(0.0, TARGET))).on_hover_text(tr!("An AniCraft document, or an Animate .fla or .xfl")).clicked() { + app.invoke("file.open"); + } + if ui.add(egui::Button::new(tr!("Sample animation")).min_size(vec2(0.0, TARGET))).on_hover_text(tr!("A short animation to look at and take apart")).clicked() { + app.request("file.new_sample", json!({})); + } + }); + ui.label(text(Type::Caption, tr!("Or drop a document anywhere on this window."))); + ui.add_space(14.0); + ui.label(text(Type::Heading, tr!("Recent"))); + ui.add_space(6.0); + let list = crate::recent::entries(app); + if list.is_empty() { + ui.label(text(Type::Caption, tr!("Documents you open or save show here, with a picture of their first frame."))); + return; + } + let mut act: Option<(&'static str, serde_json::Value)> = None; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(10.0, 10.0); + for (i, e, missing) in &list { + card(app, ui, ctx, *i, e, *missing, &mut act); + } + }); + if let Some((id, params)) = act { + crate::recent::open_or_run(app, id, params); + } +} + +/// A recent file: its picture, name and folder. A click opens it; a missing file is dimmed with +/// Remove; Pin keeps it first. +fn card(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context, i: usize, e: &anicraft_engine::cmds_recent::RecentFile, missing: bool, act: &mut Option<(&'static str, serde_json::Value)>) { + let thumb = Vec2::new(anicraft_engine::cmds_recent::THUMB_W as f32 * 0.66, anicraft_engine::cmds_recent::THUMB_H as f32 * 0.66); + let name = crate::recent::display_name(&e.path); + ui.vertical(|ui| { + ui.set_width(thumb.x); + let (r, resp) = ui.allocate_exact_size(thumb, if missing { Sense::hover() } else { Sense::click() }); + let label = if missing { tr!("{name}, missing", name = name) } else if e.pinned { tr!("Open {name}, pinned", name = name) } else { tr!("Open {name}", name = name) }; + a11y::control(ui, &resp, WidgetType::Button, &label, None); + let hot = !missing && (resp.hovered() || resp.has_focus()); + let p = ui.painter(); + p.rect_filled(r, T.rc(), T.panel_alt); + match (!missing).then(|| app.thumbs.get(ctx, &e.path)).flatten() { + Some(tex) => { + let s = tex.size_vec2(); + let fit = (r.width() / s.x.max(1.0)).min(r.height() / s.y.max(1.0)); + let img = Rect::from_center_size(r.center(), s * fit); + p.image(tex.id(), img, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => icons::paint(p, Rect::from_center_size(r.center(), vec2(28.0, 28.0)), Icon::Image, T.text_faint), + } + p.rect_stroke(r, T.rc(), Stroke::new(if hot { 1.5 } else { 1.0 }, if hot { T.accent } else { T.border }), StrokeKind::Inside); + a11y::focus_ring(ui, &resp); + let tip = e.path.display().to_string(); + let resp = if missing { resp.on_hover_text(tr!("{path} is no longer there", path = tip)) } else { resp.on_hover_text(tip) }; + if resp.clicked() { + *act = Some(("file.open_recent", json!({"index": i}))); + } + let c = if missing { T.text_dim } else { color(Type::Body) }; + ui.add(egui::Label::new(text(Type::Body, name.clone()).color(c)).truncate()); + ui.horizontal(|ui| { + let note = if missing { tr!("Missing").to_string() } else if e.pinned { tr!("Pinned").to_string() } else { crate::recent::folder_name(&e.path) }; + ui.add(egui::Label::new(text(if missing || e.pinned { Type::Caption } else { Type::Path }, note).color(T.text_dim)).truncate()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if missing { + if ui.small_button(tr!("Remove")).on_hover_text(tr!("Take it off the list")).clicked() { + *act = Some(("prefs.recent_remove", json!({"index": i}))); + } + } else if ui.small_button(if e.pinned { tr!("Unpin") } else { tr!("Pin") }).on_hover_text(if e.pinned { tr!("Let it move down the list again") } else { tr!("Keep it at the top of the list") }).clicked() { + *act = Some(("prefs.recent_pin", json!({"index": i}))); + } + }); + }); + }); +} + +fn footer(app: &mut App, ui: &mut egui::Ui) { + ui.separator(); + ui.horizontal(|ui| { + let mut on = app.prefs.start_screen; + if crate::theme::checkbox(ui, &mut on, tr!("Show this screen when AniCraft starts")).changed() { + let mut p = app.prefs.clone(); + p.start_screen = on; + let ctx = ui.ctx().clone(); + app.set_prefs(&ctx, p); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(text(Type::Caption, tr!("File › Start Screen brings it back"))); + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + + fn app() -> (App, egui::Context) { + let ctx = egui::Context::default(); + let app = App::with_context(&ctx, Session::new(anicraft_engine::doc::sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + (app, ctx) + } + + #[test] + fn every_preset_makes_a_document_of_its_size() { + let (mut app, _) = app(); + for p in &PRESETS { + for fps in [24.0, 30.0] { + crate::start::open(&mut app); + app.request("file.new", new_params(p.width, p.height, fps)); + let st = app.s.doc.stage; + assert_eq!((st.width, st.height, st.fps), (p.width, p.height, fps), "{}", p.name); + assert!(app.start.is_none(), "New dismisses the start screen"); + } + } + let names: Vec<(u32, u32)> = PRESETS.iter().map(|p| (p.width, p.height)).collect(); + for want in [(1280, 720), (1920, 1080), (1080, 1080)] { + assert!(names.contains(&want), "{want:?} is a preset"); + } + // A custom size, and one past the limit that the engine refuses (the screen stays). + crate::start::open(&mut app); + app.request("file.new", new_params(640, 480, 12.0)); + assert_eq!((app.s.doc.stage.width, app.s.doc.stage.height, app.s.doc.stage.fps), (640, 480, 12.0)); + crate::start::open(&mut app); + app.request("file.new", new_params(anicraft_engine::doc::MAX_STAGE_EDGE + 1, 10, 24.0)); + assert!(app.start.is_some(), "a refused New leaves the start screen up"); + } + + #[test] + fn over_unsaved_work_new_asks_first_and_esc_goes_back() { + let (mut app, ctx) = app(); + app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + crate::start::open(&mut app); + app.request("file.new", new_params(1920, 1080, 24.0)); + assert!(app.confirm.is_some(), "unsaved work asks first"); + assert!(app.start.is_some(), "and the start screen waits for the answer"); + app.confirm = None; + // Esc returns to the work, untouched. + let input = egui::RawInput { events: vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + assert!(app.start.is_none()); + assert!(app.s.is_dirty(), "the work is still there"); + } +} diff --git a/src/web.rs b/src/web.rs index e0e248fb..b18c9495 100644 --- a/src/web.rs +++ b/src/web.rs @@ -36,6 +36,9 @@ const PICKER_ID: &str = "anicraft_file_input"; /// Largest file taken from the picker (the engine's own limits are lower for most kinds). const MAX_PICK_BYTES: f64 = 512.0 * 1024.0 * 1024.0; +/// Files read from a drop: each one's name, and its bytes or why the browser couldn't read it. +pub type ReadFiles = Vec<(String, Result, String>)>; + thread_local! { /// Files the picker delivered, waiting for the next frame. static PICKED: RefCell> = const { RefCell::new(Vec::new()) }; @@ -44,6 +47,12 @@ thread_local! { static UNSAVED: Cell = const { Cell::new(false) }; /// Sessions whose tab is still open (they hold their lock); `None` until the browser said. static LIVE: RefCell>> = const { RefCell::new(None) }; + /// Where the pointer is over the canvas while files are dragged (CSS pixels from its + /// top-left corner), ADR 0059: egui is told only that something hovers. + static DRAG_POS: Cell> = const { Cell::new(None) }; + /// Dropped files read so far, by ticket: each file's name and bytes. + static DROPPED: RefCell> = const { RefCell::new(Vec::new()) }; + static TICKET: Cell = const { Cell::new(0) }; } /// Starts the editor on the page's canvas. @@ -75,13 +84,19 @@ async fn run() -> Result<(), String> { // Text needs a face to lay out with, and a page can't see the computer's fonts. anicraft_engine::text::Fonts::register(fonts()); let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + track_drags(&canvas); eframe::WebRunner::new() .start( canvas, eframe::WebOptions::default(), Box::new(move |cc| { CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone())); - Ok(Box::new(crate::app::App::new(cc, session, None))) + let mut app = crate::app::App::new(cc, session, None); + // The start screen, unless it was switched off (ADR 0059). + if app.prefs.start_screen { + crate::start::open(&mut app); + } + Ok(Box::new(app)) }), ) .await @@ -169,6 +184,67 @@ pub fn take_picked() -> Option { }) } +/// Keeps where the pointer is while files are dragged over the canvas (eframe's own listener +/// tells egui only that files hover, ADR 0059). +fn track_drags(canvas: &web_sys::HtmlCanvasElement) { + let target = canvas.clone(); + let on_over = Closure::::new(move |e: web_sys::DragEvent| { + let r = target.get_bounding_client_rect(); + DRAG_POS.with(|p| p.set(Some((e.client_x() as f32 - r.left() as f32, e.client_y() as f32 - r.top() as f32)))); + }); + if canvas.add_event_listener_with_callback("dragover", on_over.as_ref().unchecked_ref()).is_ok() { + on_over.forget(); + } + let on_leave = Closure::::new(|_e: web_sys::DragEvent| DRAG_POS.with(|p| p.set(None))); + if canvas.add_event_listener_with_callback("dragleave", on_leave.as_ref().unchecked_ref()).is_ok() { + on_leave.forget(); + } +} + +/// Where the pointer was over the canvas during the drag, in CSS pixels. +pub fn drag_pos() -> Option<(f32, f32)> { + DRAG_POS.with(Cell::get) +} + +pub fn clear_drag_pos() { + DRAG_POS.with(|p| p.set(None)); +} + +/// Reads dropped files' bytes; they arrive together through [`take_dropped`] with the ticket +/// returned here. +pub fn read_dropped(files: Vec) -> u64 { + let ticket = TICKET.with(|t| { + t.set(t.get().wrapping_add(1)); + t.get() + }); + wasm_bindgen_futures::spawn_local(async move { + let mut out = Vec::with_capacity(files.len()); + for file in files { + let name = file.name(); + let data = if file.size() > MAX_PICK_BYTES { + Err(tr!("it is larger than {size} MB", size = MAX_PICK_BYTES as u64 >> 20)) + } else { + match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await { + Ok(buf) => Ok(js_sys::Uint8Array::new(&buf).to_vec()), + Err(_) => Err(tr!("the browser could not read it").to_string()), + } + }; + out.push((name, data)); + } + DROPPED.with(|d| d.borrow_mut().push((ticket, out))); + repaint(); + }); + ticket +} + +/// The next dropped files the browser finished reading. +pub fn take_dropped() -> Option<(u64, ReadFiles)> { + DROPPED.with(|d| { + let mut d = d.borrow_mut(); + (!d.is_empty()).then(|| d.remove(0)) + }) +} + /// Offers `data` as a download named after `path`'s file name. pub fn download(path: &Path, data: &[u8]) { let name = path.file_name().map_or_else(|| "download".to_string(), |n| n.to_string_lossy().into_owned()); From 7dfa507368cf5ff217d932b34bf3ad3f47f656e6 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:50:08 -0700 Subject: [PATCH 041/192] docs: ADR 0059, roadmap and changelog for drops, recent files and the start screen (M8) --- CHANGELOG.md | 18 ++++ crates/engine/src/cmds_recent.rs | 2 + ...e-desktop-recent-files-and-start-screen.md | 85 +++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 6 +- docs/web.md | 7 +- 6 files changed, 114 insertions(+), 5 deletions(-) create mode 100644 docs/adr/0059-files-from-the-desktop-recent-files-and-start-screen.md diff --git a/CHANGELOG.md b/CHANGELOG.md index fde88dfd..e814bba3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ ## Unreleased +* **Files from the desktop, recent files and a start screen** (ADR 0059, M8). + * **Drop files onto the window**: `.anicraft`, `.fla` and `.xfl` open (asking first over + unsaved work); SVG drawings, PNG and JPEG images and WAV, Ogg and MP3 sounds dropped on the + **stage** go onto the active layer at the playhead, centred where they were dropped, and + dropped on the **Library** go into the folder under the pointer. One undo step per drop. + A highlight shows where they will land; anything AniCraft can't take gets one clear + status line. In the web editor too. + * **File › Open Recent**: the last 10 documents opened or saved, with pinned favourites on + top, missing files greyed out with Remove, and Clear Recent Files. Kept in the + preferences (browser storage on the web). + * **Start screen** when AniCraft starts without a document: New with HD, Full HD, square + and vertical presets or a custom size and frame rate, Open, the sample animation, and the + recent files with a picture of their first frame (captured on save). Esc goes back to the + document; File › Start Screen brings it back; it can be switched off. + * New commands for the CLI and MCP: `file.drop`, `file.open_recent`, `file.recent_list`, + `prefs.recent_pin`, `prefs.recent_remove`, `prefs.recent_clear`; `file.import` takes + `cx`/`cy` and `layer: "active"`. + * **Colour effects, complete** (ADR 0056, M2). * **Properties › Colour effect**: Animate's Style menu (None, Brightness, Tint, Advanced, Alpha) with each style's controls: brightness −100..100 %, tint colour and amount, diff --git a/crates/engine/src/cmds_recent.rs b/crates/engine/src/cmds_recent.rs index a858c71c..c2de5508 100644 --- a/crates/engine/src/cmds_recent.rs +++ b/crates/engine/src/cmds_recent.rs @@ -350,7 +350,9 @@ mod tests { #[test] fn thumbnails_fit_the_start_screen() { + let t = std::time::Instant::now(); let png = thumbnail_png(&anicraft_doc::sample::demo()).unwrap(); + eprintln!("thumbnail of the sample: {:.2} ms, {} bytes", t.elapsed().as_secs_f64() * 1000.0, png.len()); let img = image_size(&png); assert!(img.0 <= THUMB_W && img.1 <= THUMB_H && img.0 > 0 && img.1 > 0, "{img:?}"); } diff --git a/docs/adr/0059-files-from-the-desktop-recent-files-and-start-screen.md b/docs/adr/0059-files-from-the-desktop-recent-files-and-start-screen.md new file mode 100644 index 00000000..34f10284 --- /dev/null +++ b/docs/adr/0059-files-from-the-desktop-recent-files-and-start-screen.md @@ -0,0 +1,85 @@ +# ADR 0059: Files from the desktop, recent files and a start screen + +* Status: accepted (2026-11-11) +* Relates to: ADR 0004 (destructive actions), ADR 0006 (platform layer), ADR 0022 + (accessibility), ADR 0036 (web build), ADR 0040 (interface languages), ADR 0050 and 0053 + (Library folders, Place on Stage), roadmap M8 + +## Context + +Files came in only through File › Open and the Import dialogs. Artists coming from Animate expect +the everyday paths: drop a file on the window, reopen something from File › Open Recent, and a Home +screen when the app starts with nothing open. All three touch the shell, the platform layer and the +engine, and two of them keep state (the recent list, its pictures) between sessions. + +## Decision + +1. **Routing is a pure function in the engine** (`cmds_drop::kind_of`, `cmds_drop::route`). A file's + kind comes from its name (an XFL folder from its `DOMDocument.xml`): document (`.anicraft`, `.fla`, + `.xfl`), drawing (SVG), image (PNG, JPEG), sound (WAV, Ogg, MP3) or unsupported. With the target + (stage, Library, elsewhere) it gives one action: open, import to the stage, import to the Library, + or refuse with a reason. The shell's `drop::plan` adds what only the window knows: one document + opens at a time (the others in the drop are left out, and the status line says so), and over the + start screen nothing imports. +2. **`file.drop` does the import, one undo step** (`{paths, to: stage | library, x, y, folder}`). + On the stage each image and sound goes into the Library and is placed as `library.place` places + it: centred on the drop point in the active layer's keyframe at the playhead (sounds onto that + keyframe). A one-layer SVG goes into the same keyframe (`file.import`'s new `layer: "active"` and + `cx`/`cy`); a drawing with several layers or masks keeps its own layers, as Import to Stage gives + it. On the Library, images and sounds go into the folder under the pointer, numbered when the + folder already has that name. Every file is checked before anything is imported; a locked layer + refuses the whole drop. Documents go through `file.open` with the unsaved-changes guard + (`request`), never through `file.drop`. +3. **Where a drop lands needs the pointer, which the desktop doesn't give during a drag.** winit + 0.30 reports dragged files without a position, and Windows and macOS send no pointer moves while + a drag is over the window. So a dropped file waits up to 0.35 s for the pointer's first move + (the system sends one as the drag ends) and is routed there; without one, media land on the stage + in the middle of the view and the status line says so. In a browser our own `dragover` listener + on the canvas keeps the position, so the target is exact and the highlight follows the pointer; + the browser then reads the bytes into the in-memory store (`vfs`) and the same `file.drop` runs. + The highlight shows the target when the position is known (the stage outlined with a crosshair + and "Place … on at frame N", the Library folder row or panel with "Add … to ", + the whole window for a document); when it isn't, it says what each place does. winit 0.31's drag + events carry a position: moving to it makes the desktop exact too. +4. **The recent list is the session's, persisted by the shell.** `cmds_recent::RecentFiles` lives on + `Session` (it survives New and Open, like plug-ins): pinned favourites first (at most 10), then + the last 10 files opened or saved, most recent first, never twice (paths compared without case + on Windows and macOS). `file.open` and `file.save` add to it (not restored autosaves or untitled + opens); `file.open_recent`, `file.recent_list`, `prefs.recent_pin`, `prefs.recent_remove` and + `prefs.recent_clear` (pinned files stay unless `pinned: true`) work in the CLI and MCP like any + command. The window copies the list into `Prefs::recent` whenever it changes and puts it back at + start; the engine never reads the settings folder. Preferences parse the list leniently (a bad + entry is skipped, not every preference reset) and sanitise it. A missing file stays listed, greyed + out with Remove, because a disconnected drive comes back; `file.open_recent` on it says it is no + longer there. `prefs` is a new namespace: plug-ins may not call it. +5. **Thumbnails are captured on save** (and on open when none exists): the CPU oracle renders the + first frame to fit 240 × 135 (`cmds_recent::thumbnail_png`, about 1.2 ms and 6 KB for the sample + in a release build), kept as `Thumbnails/.png` in the settings folder (browser storage, + base64, on the web), the key a 64-bit FNV-1a of the normalised path. Screenshot and test runs + write nothing. +6. **The start screen replaces the workspace, never covers it.** It shows when AniCraft starts with + no file to open (Preferences › `start_screen`, a checkbox on the screen itself), from File › Start + Screen, and from Open Recent in the palette. The menus and status bar stay; Esc or "Back to the + document" returns to the document behind, untouched. New offers HD 1280 × 720, Full HD 1920 × + 1080, Square 1080 × 1080, Vertical 1080 × 1920 and a custom size with a frame rate; Open…, the + sample animation and the recent files (picture, name, folder, Pin or Remove) sit beside it. Every + choice goes through `request`, so unsaved work asks first, and the screen goes once the document + is there (a refused or cancelled New leaves it up). + +## Consequences + +* Drops, recent files and the start screen work headless and from scripts; the shell only decides + where the pointer was. +* On the desktop the drop target depends on the system's first pointer move after a drag. Where it + doesn't come, media land in the middle of the view: never lost, but not where they were dropped. +* On the web a recent file can be reopened while the page keeps its bytes; after a reload it shows + as missing (the browser never gives a path back), its picture still there. +* The start screen at every launch is the default; artists who want the sample or their last + document straight away switch it off on the screen. + +## Not yet + +* Exact desktop drop positions (winit 0.31), and dropping folders of images as a sequence. +* SVG into the Library (as a graphic symbol), and dropping onto the timeline (a layer and frame). +* Opening several dropped documents (needs document tabs), and reopening the last document at start. +* Templates on the start screen, and thumbnails that follow the poster frame. diff --git a/docs/adr/README.md b/docs/adr/README.md index 6760c8e5..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0059 | m8/files-and-start | Files from the desktop, recent files and a start screen | diff --git a/docs/roadmap.md b/docs/roadmap.md index 524212ce..50d65616 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,7 +16,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. Not yet: exact drop positions on the desktop (winit 0.30 gives none during a drag; a drop waits for the first pointer move, else lands mid-view), SVG into the Library, drops on the timeline, several documents at once. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported. Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | @@ -39,7 +39,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | -| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. | +| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. | ## Releases @@ -60,7 +60,7 @@ titled with its milestone. | M5 | Audio layers: import, waveform, playback sync | timeline, layers | | M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | -| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | +| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and ActionScript (on M6's plug-in host). diff --git a/docs/web.md b/docs/web.md index ac7ee2b3..7ffdbb2d 100644 --- a/docs/web.md +++ b/docs/web.md @@ -54,7 +54,12 @@ autosave) work. On another host, serve over HTTPS for the same reason. Compressi a crash. Copies of tabs that are still open are never offered. Browsers keep only a few MB per site, so documents with large images or sounds may not fit; the status bar says when a copy fails. -* **Preferences** are kept in the browser's storage too. +* **Dropping files** on the page works as on the desktop (ADR 0059): documents open, drawings, + images and sounds land where they are dropped on the stage or in the Library. An XFL folder + can't be dropped (the browser hands over files, not folders): drop the `.fla`. +* **Preferences** are kept in the browser's storage too, with Open Recent and the start + screen's pictures. A recent file reopens while the page still holds it; after a reload it + shows as missing (the browser never gives its path back): open it again with Open. * **Leaving the page** with unsaved changes asks first. * **Shortcuts** are the desktop ones; on a Mac they use ⌘. From cbcba63dde2e894e7b0bed9f5d39898b2d942f90 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:03:44 +0100 Subject: [PATCH 042/192] CI: nightly release dry run (#169) release.yml also runs nightly on main with craft-common-actions' dry-run: every release build except macOS, with nothing signed, pushed or drafted. Breakage that only the release build hits (riscv64, Flatpak, FreeBSD, packaging) then shows up the next morning instead of on release day, as it did on 11 Nov 2026. --- .github/workflows/release.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d99e4a98..4c08976b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,6 +8,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "0 1 * * *" push: branches: [release] workflow_dispatch: @@ -26,6 +30,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: anicraft app-title: AniCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From 1ddb650af941ddd15e3ae076f91327ee74e28621 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 14:59:17 -0700 Subject: [PATCH 043/192] docs: reserve ADR 0060 for Publish Settings and Publish (M8) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..8f01bf2e 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0060 | m8/publish-settings | Publish Settings and Publish | From 7c9126e3b3d540fac044c450936cda9ed1c85414 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 15:03:44 -0700 Subject: [PATCH 044/192] feat(doc): publish profile in the document, every format with its options (M8) --- crates/doc/src/lib.rs | 21 +- crates/doc/src/publish.rs | 366 +++++++++++++++++++++++++++++++++++ crates/doc/src/sample.rs | 6 +- crates/engine/src/history.rs | 2 +- 4 files changed, 388 insertions(+), 7 deletions(-) create mode 100644 crates/doc/src/publish.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8e92b3..6266a663 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -22,6 +22,7 @@ pub mod path_table; pub mod width; pub mod stroke_style; pub mod player; +pub mod publish; pub mod sample; pub mod sound; @@ -1110,6 +1111,9 @@ pub struct Document { /// (ADR 0013 tier 1); empty when there is none. #[serde(default, skip_serializing_if = "String::is_empty")] pub document_class: String, + /// File › Publish Settings: the formats Publish writes and their options (ADR 0060). + #[serde(default, skip_serializing_if = "publish_is_default")] + pub publish: Arc, /// Next free id for layers, elements and symbols. pub next_id: u64, } @@ -1133,6 +1137,8 @@ struct DocumentFile { library_tree: Arc, #[serde(default)] document_class: String, + #[serde(default)] + publish: Arc, #[serde(default = "first_id")] next_id: u64, } @@ -1143,7 +1149,7 @@ impl From for Document { if let Some(tl) = f.timeline { scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl })); } - Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, next_id: f.next_id } + Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, next_id: f.next_id } } } @@ -1155,18 +1161,22 @@ fn library_tree_is_empty(t: &Arc) -> bool { t.is_empty() } +fn publish_is_default(p: &Arc) -> bool { + p.is_default() +} + /// What `timeline(i)` returns for a scene that does not exist (never for a sanitized document). static NO_TIMELINE: Timeline = Timeline { layers: Vec::new() }; impl PartialEq for Document { fn eq(&self, o: &Document) -> bool { - self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) + self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) } } impl Default for Document { fn default() -> Self { - let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), next_id: 1 }; let id = LayerId(d.alloc_id()); d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1"))); d @@ -1272,6 +1282,11 @@ impl Document { if !self.document_class.is_empty() && !actions::valid_class_name(&self.document_class) { self.document_class.clear(); } + let mut publish = (*self.publish).clone(); + publish.sanitize(); + if publish != *self.publish { + self.publish = Arc::new(publish); + } for sym in &mut self.library { max_id = max_id.max(sym.id.0); if sym.linkage.as_ref().is_some_and(|l| l.check().is_err()) { diff --git a/crates/doc/src/publish.rs b/crates/doc/src/publish.rs new file mode 100644 index 00000000..86343d5c --- /dev/null +++ b/crates/doc/src/publish.rs @@ -0,0 +1,366 @@ +//! Publish Settings (ADR 0060): which formats File › Publish writes, each with its options and +//! output name, kept in the document as Animate keeps them. +//! +//! Every format is always present, in the fixed order Publish runs them; a format is on or off. +//! Outputs are templates relative to the document's folder: `{name}` is the document's file name +//! without its extension. A file written before publish settings existed has none and gets +//! [`PublishProfile::default`] (the HTML canvas page on, the rest off) the first time it opens. + +use serde::{Deserialize, Serialize}; + +/// The formats File › Publish can write, in the order it writes them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PublishFormat { + Html, + Gif, + Video, + Lottie, + SpriteSheet, + PngSequence, + Png, + Svg, + Audio, +} + +impl PublishFormat { + /// Every format, in the order Publish runs them. + pub const ALL: [PublishFormat; 9] = [ + PublishFormat::Html, + PublishFormat::Gif, + PublishFormat::Video, + PublishFormat::Lottie, + PublishFormat::SpriteSheet, + PublishFormat::PngSequence, + PublishFormat::Png, + PublishFormat::Svg, + PublishFormat::Audio, + ]; + + /// The stable key used by commands and the file format. + pub fn key(self) -> &'static str { + match self { + PublishFormat::Html => "html", + PublishFormat::Gif => "gif", + PublishFormat::Video => "video", + PublishFormat::Lottie => "lottie", + PublishFormat::SpriteSheet => "sprite_sheet", + PublishFormat::PngSequence => "png_sequence", + PublishFormat::Png => "png", + PublishFormat::Svg => "svg", + PublishFormat::Audio => "audio", + } + } + + pub fn from_key(key: &str) -> Option { + PublishFormat::ALL.into_iter().find(|f| f.key() == key) + } + + /// The English name of the format (translated where it is drawn). + pub fn label(self) -> &'static str { + match self { + PublishFormat::Html => "HTML canvas", + PublishFormat::Gif => "Animated GIF", + PublishFormat::Video => "Video", + PublishFormat::Lottie => "Lottie", + PublishFormat::SpriteSheet => "Sprite sheet", + PublishFormat::PngSequence => "PNG sequence", + PublishFormat::Png => "PNG image", + PublishFormat::Svg => "SVG image", + PublishFormat::Audio => "Audio", + } + } + + /// The output a new profile gives the format. + pub fn default_output(self) -> &'static str { + match self { + PublishFormat::Html => "{name}.html", + PublishFormat::Gif => "{name}.gif", + PublishFormat::Video => "{name}.webm", + PublishFormat::Lottie => "{name}.json", + PublishFormat::SpriteSheet => "{name}_sheet.png", + PublishFormat::PngSequence => "{name}_frames", + PublishFormat::Png => "{name}.png", + PublishFormat::Svg => "{name}.svg", + PublishFormat::Audio => "{name}.wav", + } + } + + /// The file extensions the output may end in (none for the PNG sequence: a folder). + pub fn extensions(self) -> &'static [&'static str] { + match self { + PublishFormat::Html => &["html", "htm"], + PublishFormat::Gif => &["gif"], + PublishFormat::Video => &["webm", "mp4"], + PublishFormat::Lottie => &["json"], + PublishFormat::SpriteSheet | PublishFormat::Png => &["png"], + PublishFormat::PngSequence => &[], + PublishFormat::Svg => &["svg"], + PublishFormat::Audio => &["wav"], + } + } +} + +/// Longest output template, in characters. +pub const MAX_OUTPUT_CHARS: usize = 512; +/// Longest HTML page title, in characters. +pub const MAX_TITLE_CHARS: usize = 256; +/// Largest export scale. +pub const MAX_PUBLISH_SCALE: f32 = 8.0; + +/// Movie frames to publish (every scene in order, 0-based): `None` ends are the movie's ends. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct FrameRange { + #[serde(skip_serializing_if = "Option::is_none")] + pub from: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub to: Option, +} + +macro_rules! format_settings { + ($(#[$meta:meta])* $name:ident, $format:expr, $enabled:expr, { $($(#[$fmeta:meta])* $field:ident : $ty:ty = $default:expr),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] + #[serde(default)] + pub struct $name { + /// Publish writes this format. + pub enabled: bool, + /// A path relative to the document's folder; `{name}` is the document's name. + pub output: String, + $($(#[$fmeta])* pub $field: $ty,)* + } + impl Default for $name { + fn default() -> Self { + $name { enabled: $enabled, output: $format.default_output().to_string(), $($field: $default,)* } + } + } + }; +} + +format_settings!( + /// The movie as one web page (`file.export_html`, ADR 0028). + HtmlSettings, PublishFormat::Html, true, { + /// The page's title; empty: the output's file name. + title: String = String::new(), + sound: bool = true, + fit: bool = true, + } +); +format_settings!( + /// An animated GIF (`file.export_gif`). + GifSettings, PublishFormat::Gif, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + #[serde(rename = "loop")] + looping: bool = true, + } +); +format_settings!( + /// WebM or MP4 through the user's ffmpeg (`file.export_video`). + VideoSettings, PublishFormat::Video, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + audio: bool = true, + } +); +format_settings!( + /// A Lottie animation (`file.export_lottie`). + LottieSettings, PublishFormat::Lottie, false, { + range: FrameRange = FrameRange::default(), + background: bool = false, + } +); +format_settings!( + /// A sprite sheet and its JSON frame map (`file.export_sprite_sheet`). + SpriteSheetSettings, PublishFormat::SpriteSheet, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + /// 0: as square as it can be. + columns: u32 = 0, + padding: u32 = 0, + background: bool = false, + } +); +format_settings!( + /// One PNG per frame in a folder (`file.export_png_sequence`). + PngSequenceSettings, PublishFormat::PngSequence, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + } +); +format_settings!( + /// One frame as a PNG (`file.export_png`). + PngSettings, PublishFormat::Png, false, { + /// The movie frame (0-based, every scene in order). + frame: u32 = 0, + scale: f32 = 1.0, + } +); +format_settings!( + /// One frame as an SVG (`file.export_svg`). + SvgSettings, PublishFormat::Svg, false, { + /// The movie frame (0-based, every scene in order). + frame: u32 = 0, + } +); +format_settings!( + /// The movie's soundtrack as a WAV (`file.export_audio`). + AudioSettings, PublishFormat::Audio, false, { + range: FrameRange = FrameRange::default(), + rate: u32 = 44_100, + /// 16, 24, or 32 (float). + bits: u32 = 16, + } +); + +/// What File › Publish writes: every format with its options (ADR 0060). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PublishProfile { + pub html: HtmlSettings, + pub gif: GifSettings, + pub video: VideoSettings, + pub lottie: LottieSettings, + pub sprite_sheet: SpriteSheetSettings, + pub png_sequence: PngSequenceSettings, + pub png: PngSettings, + pub svg: SvgSettings, + pub audio: AudioSettings, +} + +fn clean_scale(s: f32) -> f32 { + if s.is_finite() && s > 0.0 { s.min(MAX_PUBLISH_SCALE) } else { 1.0 } +} + +fn clip(s: &mut String, max: usize) { + if s.chars().count() > max { + *s = s.chars().take(max).collect(); + } +} + +impl PublishProfile { + pub fn is_default(&self) -> bool { + *self == PublishProfile::default() + } + + /// Whether Publish writes `f`, and its output template. + pub fn target(&self, f: PublishFormat) -> (bool, &str) { + match f { + PublishFormat::Html => (self.html.enabled, &self.html.output), + PublishFormat::Gif => (self.gif.enabled, &self.gif.output), + PublishFormat::Video => (self.video.enabled, &self.video.output), + PublishFormat::Lottie => (self.lottie.enabled, &self.lottie.output), + PublishFormat::SpriteSheet => (self.sprite_sheet.enabled, &self.sprite_sheet.output), + PublishFormat::PngSequence => (self.png_sequence.enabled, &self.png_sequence.output), + PublishFormat::Png => (self.png.enabled, &self.png.output), + PublishFormat::Svg => (self.svg.enabled, &self.svg.output), + PublishFormat::Audio => (self.audio.enabled, &self.audio.output), + } + } + + /// `f`'s on/off switch and output template, to change. + pub fn target_mut(&mut self, f: PublishFormat) -> (&mut bool, &mut String) { + match f { + PublishFormat::Html => (&mut self.html.enabled, &mut self.html.output), + PublishFormat::Gif => (&mut self.gif.enabled, &mut self.gif.output), + PublishFormat::Video => (&mut self.video.enabled, &mut self.video.output), + PublishFormat::Lottie => (&mut self.lottie.enabled, &mut self.lottie.output), + PublishFormat::SpriteSheet => (&mut self.sprite_sheet.enabled, &mut self.sprite_sheet.output), + PublishFormat::PngSequence => (&mut self.png_sequence.enabled, &mut self.png_sequence.output), + PublishFormat::Png => (&mut self.png.enabled, &mut self.png.output), + PublishFormat::Svg => (&mut self.svg.enabled, &mut self.svg.output), + PublishFormat::Audio => (&mut self.audio.enabled, &mut self.audio.output), + } + } + + /// The formats that are on, in publishing order. + pub fn enabled(&self) -> Vec { + PublishFormat::ALL.into_iter().filter(|f| self.target(*f).0).collect() + } + + /// Brings every value into range, so whatever a file holds, publishing can run: scales in + /// (0, 8], a known sample rate and bit depth, bounded text. + pub fn sanitize(&mut self) { + for f in PublishFormat::ALL { + let (_, output) = self.target_mut(f); + clip(output, MAX_OUTPUT_CHARS); + if output.trim().is_empty() { + *output = f.default_output().to_string(); + } + } + clip(&mut self.html.title, MAX_TITLE_CHARS); + for s in [&mut self.gif.scale, &mut self.video.scale, &mut self.sprite_sheet.scale, &mut self.png_sequence.scale, &mut self.png.scale] { + *s = clean_scale(*s); + } + self.sprite_sheet.padding = self.sprite_sheet.padding.min(256); + self.sprite_sheet.columns = self.sprite_sheet.columns.min(10_000); + self.audio.rate = self.audio.rate.clamp(8_000, 192_000); + if !matches!(self.audio.bits, 16 | 24 | 32) { + self.audio.bits = 16; + } + for r in [&mut self.gif.range, &mut self.video.range, &mut self.lottie.range, &mut self.sprite_sheet.range, &mut self.png_sequence.range, &mut self.audio.range] { + if let (Some(a), Some(b)) = (r.from, r.to) + && b < a + { + *r = FrameRange { from: Some(b), to: Some(a) }; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys_round_trip_and_defaults_are_distinct() { + for f in PublishFormat::ALL { + assert_eq!(PublishFormat::from_key(f.key()), Some(f)); + } + let p = PublishProfile::default(); + assert_eq!(p.enabled(), vec![PublishFormat::Html], "a new document publishes its web page"); + let mut outs: Vec<&str> = PublishFormat::ALL.iter().map(|f| p.target(*f).1).collect(); + outs.sort_unstable(); + outs.dedup(); + assert_eq!(outs.len(), PublishFormat::ALL.len(), "no two formats write the same file by default"); + } + + #[test] + fn profile_round_trips_and_missing_fields_default() { + let mut p = PublishProfile::default(); + p.gif.enabled = true; + p.gif.scale = 0.5; + p.gif.looping = false; + p.gif.range = FrameRange { from: Some(2), to: Some(9) }; + p.html.title = "Walk".into(); + p.audio.bits = 24; + let text = serde_json::to_string(&p).unwrap(); + assert!(text.contains("\"loop\":false") && text.contains("\"enabled\":true"), "{text}"); + let back: PublishProfile = serde_json::from_str(&text).unwrap(); + assert_eq!(back, p); + // A profile from an older build, with fields and formats missing. + let partial: PublishProfile = serde_json::from_str(r#"{"gif": {"enabled": true}}"#).unwrap(); + assert!(partial.gif.enabled && partial.html.enabled); + assert_eq!(partial.gif.output, "{name}.gif"); + assert_eq!(partial.gif.scale, 1.0); + } + + #[test] + fn sanitize_brings_everything_into_range() { + let mut p = PublishProfile::default(); + p.gif.scale = f32::NAN; + p.png.scale = 1e9; + p.audio.rate = 5; + p.audio.bits = 7; + p.sprite_sheet.padding = u32::MAX; + p.video.output = " ".into(); + p.html.title = "x".repeat(10_000); + p.lottie.range = FrameRange { from: Some(9), to: Some(2) }; + p.sanitize(); + assert_eq!((p.gif.scale, p.png.scale, p.audio.rate, p.audio.bits, p.sprite_sheet.padding), (1.0, MAX_PUBLISH_SCALE, 8_000, 16, 256)); + assert_eq!(p.video.output, "{name}.webm"); + assert_eq!(p.html.title.chars().count(), MAX_TITLE_CHARS); + assert_eq!(p.lottie.range, FrameRange { from: Some(2), to: Some(9) }); + } +} diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 039d057e..0729c03e 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -41,7 +41,7 @@ fn key(start: u32, duration: u32, elements: Vec>, tween: Option Document { - let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), next_id: 1 }; let (w, h) = (1280.0, 720.0); // --- library ------------------------------------------------------------------------- @@ -147,7 +147,7 @@ pub fn demo() -> Document { /// whose last frame traces a line and goes back to the menu. pub fn interactive() -> Document { use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, Target}; - let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), next_id: 1 }; const LEN: u32 = 36; let solid = |c: u32| Paint::Solid(Rgba::hex(c)); @@ -211,7 +211,7 @@ pub fn interactive() -> Document { /// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens. /// Every element keeps one `Arc` across its keyframes, as a real tweened shape does. pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document { - let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), next_id: 1 }; let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000)); let mut seed = 0x2545_f491_u32; let mut rnd = move || { diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 3ada0b02..f894a177 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -245,6 +245,6 @@ pub fn unique_bytes(old: &Document, new: &Document) -> usize { /// Estimated total bytes of a document (as if nothing were shared). Used for reporting. pub fn document_bytes(doc: &Document) -> usize { - let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: doc.next_id }; + let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), next_id: doc.next_id }; unique_bytes(doc, &empty) } From 8a314052f1e4700c0556262186e9e1c1f489ef98 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 15:11:47 -0700 Subject: [PATCH 045/192] feat(engine): publish.settings_get/set and file.publish, cancellable with one report (M8) --- crates/engine/src/cmds_file.rs | 27 +- crates/engine/src/cmds_plugin.rs | 5 +- crates/engine/src/confirm.rs | 18 + crates/engine/src/lib.rs | 11 + crates/engine/src/plugin_tests.rs | 2 + crates/engine/src/publish.rs | 801 +++++++++++++++++++++++++++++ crates/engine/src/publish_tests.rs | 305 +++++++++++ crates/engine/src/tests.rs | 7 + 8 files changed, 1174 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/publish.rs create mode 100644 crates/engine/src/publish_tests.rs diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 3ec7adbc..0e8b471d 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -439,7 +439,16 @@ fn export_sprite_sheet(s: &mut Session, p: &Value) -> Result { } // Frames render in parallel, then go onto the sheet in order. let doc = &s.doc; - let frames: Vec = (from..=to).into_par_iter().map(|f| render(&anicraft_doc::evaluate(doc, f), &view).map(|(pm, _)| pm)).collect::>()?; + // A publish counts the frames, and stops between them when cancelled (ADR 0060). + let job = s.job.as_deref(); + let frames: Vec = (from..=to) + .into_par_iter() + .map(|f| { + let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + crate::publish::tick(job, 1)?; + Ok(pm) + }) + .collect::>()?; let mut sheet = anicraft_render::Pixmap::new(sheet_w as u32, sheet_h as u32)?; let stride = sheet_w as usize; let delays = gif_delays(n, doc.stage.fps); @@ -567,6 +576,7 @@ fn export_video(s: &mut Session, p: &Value) -> Result { text }); let doc = &s.doc; + let job = s.job.as_deref(); let mut written = 0u32; let mut failure: Option = None; if let Some(mut stdin) = child.stdin.take() { @@ -585,11 +595,22 @@ fn export_video(s: &mut Session, p: &Value) -> Result { } written += 1; } + if let Err(e) = crate::publish::tick(job, batch.len() as u64) { + failure = Some(e); + break; + } } } + if matches!(failure, Some(EngineError::Cancelled)) { + // Cancelled while publishing: ffmpeg stops, and its unfinished file goes. + let _ = child.kill(); + } let status = child.wait()?; let log = messages.join().unwrap_or_default(); if let Some(e) = failure { + if matches!(e, EngineError::Cancelled) { + let _ = crate::vfs::remove_file(&path); + } return Err(e); } if !status.success() || written != to - from + 1 { @@ -616,6 +637,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { // Output is identical to a serial export. Files are written here, on the command's thread, // where `vfs` knows whether they go to disk or to the browser (ADR 0036). let doc = &s.doc; + let job = s.job.as_deref(); let mut files = 0usize; let frames: Vec = (from..=to).collect(); for batch in frames.chunks(64) { @@ -624,6 +646,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { crate::vfs::write(&dir.join(format!("frame_{:05}.png", f + 1)), png)?; files += 1; } + crate::publish::tick(job, batch.len() as u64)?; } Ok(json!({"frames": files, "dir": dir.display().to_string()})) } @@ -723,6 +746,7 @@ fn export_gif(s: &mut Session, p: &Value) -> Result { } // Render and colour-quantize frames in parallel; encode in order. let doc = &s.doc; + let job = s.job.as_deref(); let delays = gif_delays(n as usize, doc.stage.fps); let frames: Vec> = (from..to.saturating_add(1)) .into_par_iter() @@ -732,6 +756,7 @@ fn export_gif(s: &mut Session, p: &Value) -> Result { let mut rgba = pm.to_rgba8(); let mut frame = gif::Frame::from_rgba_speed(w, h, &mut rgba, 10); frame.delay = delay; + crate::publish::tick(job, 1)?; Ok(frame) }) .collect::>>()?; diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index b42c7a88..af5dc312 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -38,7 +38,10 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { Err("plug-ins don't use your clipboard") } _ => match id.split('.').next().unwrap_or("") { - "file" => Err("plug-ins can't open, save, import or export files"), + "file" => Err("plug-ins can't open, save, import, export or publish files"), + // Reading the settings is harmless; changing them changes what Publish writes where. + "publish" if id == "publish.settings_get" => Ok(()), + "publish" => Err("plug-ins can't change what Publish writes"), "plugin" => Err("plug-ins can't install, run or remove plug-ins"), "control" => Err("plug-ins can't play the movie"), ns if DOCUMENT.contains(&ns) => Ok(()), diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 5dae7f2a..519d8203 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -113,6 +113,24 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { let path = Path::new(p.get("path").and_then(Value::as_str)?); crate::vfs::exists(path).then(|| overwrite(path, "Exporting")) } + "file.publish" => { + // Publishing replaces what is already there; what this session published itself + // it replaces without asking again (ADR 0060). + let found = crate::publish::existing(s, &crate::publish::planned(s, p)?); + let names: Vec = found.iter().take(3).map(|f| f.display().to_string()).collect(); + let more = found.len().saturating_sub(names.len()); + (!found.is_empty()).then(|| Confirmation { + title: if found.len() == 1 { "Replace published file?".into() } else { "Replace published files?".into() }, + message: format!( + "Publishing replaces {} already there: {}{}. This cannot be undone.", + if found.len() == 1 { "a file".to_string() } else { plural(found.len(), "file") }, + names.join(", "), + if more > 0 { format!(" and {more} more") } else { String::new() } + ), + action: "Publish".into(), + irreversible: true, + }) + } "file.export_sprite_sheet" => { // The sheet and its frame map: either one already there is replaced. let path = Path::new(p.get("path").and_then(Value::as_str)?); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dd8e01e4..3ed3850f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,6 +45,7 @@ pub mod render_service; pub mod selection; pub mod params; pub mod player; +pub mod publish; pub mod vfs; use anicraft_doc::{DisplayList, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, evaluate_layer_elements, evaluate_scene}; @@ -77,6 +78,9 @@ pub enum EngineError { Render(#[from] anicraft_render::RenderError), #[error("{0}")] NeedsConfirmation(String), + /// A running publish was cancelled (ADR 0060). + #[error("cancelled")] + Cancelled, } pub type Result = std::result::Result; @@ -110,6 +114,7 @@ impl CommandSpec { pub fn commands() -> Vec { let mut v = Vec::new(); v.extend(cmds_file::specs()); + v.extend(publish::specs()); v.extend(cmds_recovery::specs()); v.extend(cmds_timeline::specs()); v.extend(cmds_camera::specs()); @@ -300,6 +305,10 @@ pub struct Session { gesture_cut: Option, /// The last picture of an open symbol in place, by its key (ADR 0045). picture_cache: RefCell)>>, + /// A publish this session runs: its Cancel and frame count, which exports check (ADR 0060). + pub job: Option>, + /// Files this session's publishes wrote: publishing again replaces them without asking. + pub published: std::collections::BTreeSet, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -365,6 +374,8 @@ impl Session { pending_cut: None, gesture_cut: None, picture_cache: RefCell::new(None), + job: None, + published: std::collections::BTreeSet::new(), } } diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index 35ced9f4..1adf6c0d 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -170,6 +170,8 @@ fn every_command_namespace_has_a_plugin_policy() { let verdict = plugin_may_call(c.id); match ns { "file" | "plugin" | "control" => assert!(verdict.is_err(), "{} must be refused", c.id), + // Publish Settings (ADR 0060): read yes, change no (it says what Publish writes). + "publish" => assert_eq!(verdict.is_ok(), c.id == "publish.settings_get", "{}", c.id), _ => assert!(verdict.is_ok() || matches!(c.id, "edit.undo" | "edit.redo") || c.id.contains("copy") || c.id.contains("cut") || c.id.contains("paste"), "{} has no plug-in policy (add its namespace to plugin_may_call)", c.id), } } diff --git a/crates/engine/src/publish.rs b/crates/engine/src/publish.rs new file mode 100644 index 00000000..2ff78c45 --- /dev/null +++ b/crates/engine/src/publish.rs @@ -0,0 +1,801 @@ +//! File › Publish Settings and File › Publish (ADR 0060). +//! +//! The document holds a [`PublishProfile`]: every format, on or off, with its options and an +//! output template relative to the document's folder (`{name}` is the document's name). Publish +//! turns the formats that are on into a [`Step`] each (the export command and its params), and +//! runs them in order through the same export commands File › Export uses, on a session of its +//! own: on the caller's thread for `file.publish` (CLI, MCP, the web build one step per frame), +//! or on a background worker in the desktop editor ([`Publisher`]). A [`Control`] cancels the +//! run between and inside exports and counts frames for the progress view. One [`Report`] says +//! what each format wrote, skipped or left out. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::Document; +use anicraft_doc::publish::{FrameRange, MAX_OUTPUT_CHARS, MAX_PUBLISH_SCALE, MAX_TITLE_CHARS, PublishFormat, PublishProfile}; +use serde_json::{Map, Value, json}; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "publish.settings_get", + label: "Publish Settings…", + menu: "File", + shortcut: Some("Ctrl+Shift+F12"), + params: "{} (the document's publish profile, and where each format would go)", + mutates: false, + run: settings_get, + }, + CommandSpec { + id: "publish.settings_set", + label: "Publish Settings", + menu: "", + shortcut: None, + params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", + mutates: true, + run: settings_set, + }, + CommandSpec { + id: "file.publish", + label: "Publish", + menu: "File", + shortcut: Some("Shift+F12"), + params: "{formats? ([format, …]: only these; default: the ones Publish Settings has on), confirm? (to replace files already there)}", + mutates: false, + run: publish_cmd, + }, + ] +} + +// ----- cancel and progress ------------------------------------------------------------------- + +/// Shared between a running publish and whoever watches it: Cancel, and frames done of the +/// format running. Exports check it between frames (`tick`). +#[derive(Debug, Default)] +pub struct Control { + cancel: AtomicBool, + done: AtomicU64, + total: AtomicU64, +} + +impl Control { + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + } + pub fn cancelled(&self) -> bool { + self.cancel.load(Ordering::Relaxed) + } + /// Frames done and frames in all, of the format running (0 in all: no frame count). + pub fn progress(&self) -> (u64, u64) { + (self.done.load(Ordering::Relaxed), self.total.load(Ordering::Relaxed)) + } + fn begin(&self, total: u64) { + self.done.store(0, Ordering::Relaxed); + self.total.store(total, Ordering::Relaxed); + } +} + +/// An export made `frames` more frames: counts them, and stops it when Publish was cancelled. +pub(crate) fn tick(job: Option<&Control>, frames: u64) -> Result<()> { + let Some(j) = job else { return Ok(()) }; + j.done.fetch_add(frames, Ordering::Relaxed); + if j.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) } +} + +// ----- where things go ----------------------------------------------------------------------- + +/// The folder outputs are relative to and the `{name}` they use: the document's folder and file +/// name. An untitled document has no folder on disk, so it can't publish until it is saved; in +/// the browser (no folders, files become downloads) it publishes as "Untitled". +pub fn base(path: Option<&Path>) -> std::result::Result<(PathBuf, String), String> { + match path { + Some(p) => { + let name = p.file_stem().map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned()); + Ok((p.parent().map(Path::to_path_buf).unwrap_or_default(), name)) + } + None if crate::vfs::in_memory() => Ok((PathBuf::new(), "Untitled".into())), + None => Err("save the document first: Publish writes its files beside it".into()), + } +} + +/// Output template `template` of format `f`, for a document named `name`: a path inside the +/// document's folder. `{name}` is the only placeholder; the path may go into folders below +/// but never above or elsewhere (a document opened from someone else can't write anywhere +/// else on this computer); a file without an extension gets the format's. +pub fn resolve(f: PublishFormat, template: &str, name: &str) -> std::result::Result { + let t = template.trim(); + if t.is_empty() { + return Err("the output name is empty".into()); + } + if t.chars().count() > MAX_OUTPUT_CHARS { + return Err(format!("the output name is longer than {MAX_OUTPUT_CHARS} characters")); + } + let text = t.replace("{name}", name); + if t.replace("{name}", "").contains(['{', '}']) { + return Err(format!("“{t}” has a placeholder Publish doesn't know: {{name}} (the document's name) is the only one")); + } + let mut rel = PathBuf::new(); + for c in Path::new(&text).components() { + match c { + Component::Normal(part) => rel.push(part), + Component::CurDir => {} + _ => return Err(format!("“{t}” must stay in the document's folder (a name, or folders below it like web/{{name}}.html)")), + } + } + if rel.as_os_str().is_empty() { + return Err("the output name is empty".into()); + } + let exts = f.extensions(); + if !exts.is_empty() { + match rel.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase) { + None => { + let file = rel.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + rel.set_file_name(format!("{file}.{}", exts.first().copied().unwrap_or(""))); + } + Some(e) if exts.contains(&e.as_str()) => {} + Some(_) => return Err(format!("{} goes to {}", f.label(), exts.iter().map(|e| format!(".{e}")).collect::>().join(" or "))), + } + } + Ok(rel) +} + +// ----- the plan -------------------------------------------------------------------------------- + +/// One format to publish: the export command that writes it and its params. +#[derive(Clone, Debug)] +pub struct Step { + pub format: PublishFormat, + pub command: &'static str, + pub params: Value, + /// The files (or, for the PNG sequence, the folder) it writes. + pub outputs: Vec, + /// The scene the export runs in (one-frame formats), and frames it makes (0: not counted). + pub scene: usize, + pub frames: u64, + /// Why it won't run here, when it won't. + pub skip: Option, +} + +fn range_params(p: &mut Map, r: FrameRange, last: u32) -> u64 { + if let Some(f) = r.from { + p.insert("from".into(), json!(f)); + } + if let Some(t) = r.to { + p.insert("to".into(), json!(t)); + } + let from = r.from.unwrap_or(0).min(last); + let to = r.to.unwrap_or(last).min(last); + u64::from(to.saturating_sub(from)) + 1 +} + +/// The steps Publish runs for `doc` saved at `path`: the formats that are on (or `only`), in +/// order, or why it can't run (an output that isn't one, two formats writing the same file). +pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>) -> std::result::Result, String> { + let (dir, name) = base(path)?; + let prof = &doc.publish; + let formats: Vec = match only { + Some(list) => PublishFormat::ALL.into_iter().filter(|f| list.contains(f)).collect(), + None => prof.enabled(), + }; + let last = doc.frame_count().saturating_sub(1); + let mut steps: Vec = Vec::new(); + for f in formats { + let rel = resolve(f, prof.target(f).1, &name).map_err(|e| format!("{}: {e}", f.label()))?; + let out = dir.join(&rel); + let path_s = out.display().to_string(); + let mut p = Map::new(); + let (mut scene, mut skip) = (0, None); + let (command, frames, outputs) = match f { + PublishFormat::Html => { + let h = &prof.html; + if !h.title.trim().is_empty() { + p.insert("title".into(), json!(h.title)); + } + p.insert("sound".into(), json!(h.sound)); + p.insert("fit".into(), json!(h.fit)); + ("file.export_html", 0, vec![out]) + } + PublishFormat::Gif => { + let g = &prof.gif; + let n = range_params(&mut p, g.range, last); + p.insert("scale".into(), json!(g.scale)); + p.insert("loop".into(), json!(g.looping)); + ("file.export_gif", n, vec![out]) + } + PublishFormat::Video => { + let v = &prof.video; + let n = range_params(&mut p, v.range, last); + p.insert("scale".into(), json!(v.scale)); + p.insert("audio".into(), json!(v.audio)); + if crate::vfs::in_memory() { + skip = Some("video is made with ffmpeg, which a web browser can't run".to_string()); + } + ("file.export_video", n, vec![out]) + } + PublishFormat::Lottie => { + let l = &prof.lottie; + range_params(&mut p, l.range, last); + p.insert("background".into(), json!(l.background)); + ("file.export_lottie", 0, vec![out]) + } + PublishFormat::SpriteSheet => { + let sh = &prof.sprite_sheet; + let n = range_params(&mut p, sh.range, last); + p.insert("scale".into(), json!(sh.scale)); + if sh.columns > 0 { + p.insert("columns".into(), json!(sh.columns)); + } + p.insert("padding".into(), json!(sh.padding)); + p.insert("background".into(), json!(sh.background)); + let map = out.with_extension("json"); + ("file.export_sprite_sheet", n, vec![out, map]) + } + PublishFormat::PngSequence => { + let q = &prof.png_sequence; + let n = range_params(&mut p, q.range, last); + p.insert("scale".into(), json!(q.scale)); + ("file.export_png_sequence", n, vec![out]) + } + PublishFormat::Png => { + let (sc, local) = doc.locate(prof.png.frame.min(last)); + scene = sc; + p.insert("frame".into(), json!(local)); + p.insert("scale".into(), json!(prof.png.scale)); + ("file.export_png", 1, vec![out]) + } + PublishFormat::Svg => { + let (sc, local) = doc.locate(prof.svg.frame.min(last)); + scene = sc; + p.insert("frame".into(), json!(local)); + ("file.export_svg", 1, vec![out]) + } + PublishFormat::Audio => { + let a = &prof.audio; + range_params(&mut p, a.range, last); + p.insert("rate".into(), json!(a.rate)); + p.insert("bits".into(), json!(a.bits)); + if !anicraft_doc::sound::has_sounds(doc) { + skip = Some("the movie has no sounds".to_string()); + } + ("file.export_audio", 0, vec![out]) + } + }; + let key = if f == PublishFormat::PngSequence { "dir" } else { "path" }; + p.insert(key.into(), json!(path_s)); + // Publish's own confirmation covers replacing files (`existing`). + p.insert("confirm".into(), json!(true)); + // Two formats writing one file would leave only the second (names compared as the + // case-insensitive file systems of Windows and macOS see them). + let same = |a: &Path, b: &Path| a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase(); + if let Some(other) = steps.iter().find(|s| s.outputs.iter().any(|o| outputs.iter().any(|n| same(o, n)))) { + return Err(format!("{} and {} would both write {}: give one of them another output name", other.format.label(), f.label(), rel.display())); + } + steps.push(Step { format: f, command, params: Value::Object(p), outputs, scene, frames, skip }); + } + Ok(steps) +} + +/// Files already there that publishing `steps` would replace (a PNG sequence's folder when it +/// holds exported frames), leaving out those this session published itself. +pub fn existing(s: &Session, steps: &[Step]) -> Vec { + let mut v = Vec::new(); + for st in steps.iter().filter(|st| st.skip.is_none()) { + for o in &st.outputs { + if s.published.contains(o) { + continue; + } + let there = if st.format == PublishFormat::PngSequence { + crate::vfs::list(o, 10_000).iter().any(|e| { + let n = e.file_name().map(|n| n.to_string_lossy()).unwrap_or_default(); + n.starts_with("frame_") && n.ends_with(".png") + }) + } else { + crate::vfs::exists(o) + }; + if there { + v.push(o.clone()); + } + } + } + v +} + +/// The formats `file.publish` params name, if they name any. +fn only(p: &Value) -> Result>> { + match p.get("formats") { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(list)) => list + .iter() + .take(64) + .map(|v| v.as_str().and_then(PublishFormat::from_key).ok_or_else(|| EngineError::Param(format!("unknown format {v} (html, gif, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))) + .collect::>>() + .map(Some), + Some(_) => Err(EngineError::Param("param 'formats' must be a list of format names".into())), + } +} + +/// The plan `file.publish` with `p` would run, for the confirmation (ADR 0004). +pub(crate) fn planned(s: &Session, p: &Value) -> Option> { + plan(&s.doc, s.path.as_deref(), only(p).ok()?.as_deref()).ok() +} + +// ----- running --------------------------------------------------------------------------------- + +/// How one format went. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Status { + Published, + Skipped, + Failed, + Cancelled, +} + +impl Status { + pub fn key(self) -> &'static str { + match self { + Status::Published => "published", + Status::Skipped => "skipped", + Status::Failed => "failed", + Status::Cancelled => "cancelled", + } + } +} + +/// What one format did: the files it wrote, and what its exporter left out or why it failed. +#[derive(Clone, Debug)] +pub struct Outcome { + pub format: PublishFormat, + pub status: Status, + pub files: Vec, + /// The exporter's report of what it approximated or left out (HTML, Lottie), or why the + /// format was skipped, failed or stopped. + pub message: String, +} + +impl Outcome { + pub fn to_json(&self) -> Value { + json!({ + "format": self.format.key(), + "label": self.format.label(), + "status": self.status.key(), + "files": self.files.iter().map(|f| f.display().to_string()).collect::>(), + "message": self.message, + }) + } +} + +/// Every format's outcome, in order. +#[derive(Clone, Debug, Default)] +pub struct Report { + pub outcomes: Vec, +} + +impl Report { + pub fn count(&self, s: Status) -> usize { + self.outcomes.iter().filter(|o| o.status == s).count() + } + pub fn files(&self) -> Vec { + self.outcomes.iter().flat_map(|o| o.files.iter().cloned()).collect() + } + /// One sentence per format with something to say (left out, skipped, failed), in order. + pub fn summary(&self) -> String { + self.outcomes + .iter() + .filter(|o| !o.message.is_empty()) + .map(|o| { + let m = o.message.trim_end_matches('.'); + match o.status { + Status::Published => format!("{}: {m}.", o.format.label()), + Status::Skipped => format!("{} skipped: {m}.", o.format.label()), + Status::Failed => format!("{} failed: {m}.", o.format.label()), + Status::Cancelled => format!("{}: {m}.", o.format.label()), + } + }) + .collect::>() + .join(" ") + } + pub fn to_json(&self) -> Value { + json!({ + "published": self.count(Status::Published), + "skipped": self.count(Status::Skipped), + "failed": self.count(Status::Failed), + "cancelled": self.count(Status::Cancelled) > 0, + "files": self.files().iter().map(|f| f.display().to_string()).collect::>(), + "formats": self.outcomes.iter().map(Outcome::to_json).collect::>(), + "report": self.summary(), + }) + } +} + +/// Runs the steps of a publish one at a time, on a session of its own (the document as it was +/// when Publish started), so the editor keeps working while it runs. +pub struct Publisher { + s: Session, + steps: Vec, + next: usize, + report: Report, + control: Arc, +} + +impl Publisher { + pub fn new(doc: Document, path: Option, steps: Vec, control: Arc) -> Publisher { + let mut s = Session::new(doc); + s.path = path; + s.job = Some(control.clone()); + Publisher { s, steps, next: 0, report: Report::default(), control } + } + + /// The format running next (or now), if any is left. + pub fn current(&self) -> Option { + self.steps.get(self.next).map(|s| s.format) + } + + pub fn done(&self) -> bool { + self.next >= self.steps.len() + } + + /// Runs the next format; `None` when every format has run. Once cancelled, the formats + /// left are cancelled without running. + pub fn step(&mut self) -> Option<&Outcome> { + let st = self.steps.get(self.next)?.clone(); + self.next += 1; + let out = self.run(&st); + self.report.outcomes.push(out); + self.report.outcomes.last() + } + + fn run(&mut self, st: &Step) -> Outcome { + let mut out = Outcome { format: st.format, status: Status::Published, files: Vec::new(), message: String::new() }; + if self.control.cancelled() { + out.status = Status::Cancelled; + out.message = "not published (cancelled)".into(); + return out; + } + if let Some(why) = &st.skip { + out.status = Status::Skipped; + out.message.clone_from(why); + return out; + } + self.control.begin(st.frames); + // Folders below the document's are made as needed. + for o in &st.outputs { + let dir = if st.format == PublishFormat::PngSequence { Some(o.as_path()) } else { o.parent() }; + if let Some(d) = dir.filter(|d| !d.as_os_str().is_empty()) + && let Err(e) = crate::vfs::create_dir_all(d) + { + out.status = Status::Failed; + out.message = format!("could not make the folder {}: {e}", d.display()); + return out; + } + } + self.s.scene = st.scene.min(self.s.doc.scenes.len().saturating_sub(1)); + self.s.editing.clear(); + self.s.frame = 0; + let result = crate::find_command(st.command).ok_or_else(|| EngineError::UnknownCommand(st.command.into())).and_then(|spec| (spec.run)(&mut self.s, &st.params)); + match result { + Ok(v) => { + out.files.clone_from(&st.outputs); + out.message = v.get("report").and_then(Value::as_str).unwrap_or("").to_string(); + } + Err(EngineError::Cancelled) => { + out.status = Status::Cancelled; + out.message = if st.format == PublishFormat::PngSequence { "stopped part-way (the frames written so far are kept)".into() } else { "stopped before it was written".into() }; + } + Err(e) => { + out.status = Status::Failed; + out.message = e.to_string(); + } + } + out + } + + /// Runs every format left. + pub fn run_all(&mut self) { + while self.step().is_some() {} + } + + pub fn report(&self) -> &Report { + &self.report + } +} + +fn publish_cmd(s: &mut Session, p: &Value) -> Result { + let steps = plan(&s.doc, s.path.as_deref(), only(p)?.as_deref()).map_err(EngineError::State)?; + if steps.is_empty() { + return Err(EngineError::State("no format is on in Publish Settings: turn one on first".into())); + } + let control = s.job.clone().unwrap_or_default(); + let mut job = Publisher::new(s.doc.clone(), s.path.clone(), steps, control); + job.run_all(); + let report = job.report(); + s.published.extend(report.files()); + Ok(report.to_json()) +} + +// ----- the settings commands ------------------------------------------------------------------- + +fn settings_get(s: &mut Session, _: &Value) -> Result { + Ok(settings_json(&s.doc, s.path.as_deref())) +} + +/// The profile, and for each format whether it is on, its output and where that goes now (or +/// why it can't go anywhere). +pub fn settings_json(doc: &Document, path: Option<&Path>) -> Value { + let base = base(path); + let formats: Vec = PublishFormat::ALL + .iter() + .map(|f| { + let (on, output) = doc.publish.target(*f); + let mut o = json!({"format": f.key(), "label": f.label(), "enabled": on, "output": output}); + match base.as_ref().map_err(Clone::clone).and_then(|(dir, name)| resolve(*f, output, name).map(|r| dir.join(r))) { + Ok(at) => { + o["path"] = json!(at.display().to_string()); + o["exists"] = json!(crate::vfs::exists(&at)); + } + Err(e) => o["error"] = json!(e), + } + o + }) + .collect(); + let (folder, name) = base.map_or((Value::Null, Value::Null), |(d, n)| (json!(d.display().to_string()), json!(n))); + json!({"profile": serde_json::to_value(&*doc.publish).unwrap_or(Value::Null), "formats": formats, "folder": folder, "name": name}) +} + +/// Keys each format's options take (besides `enabled` and `output`). +fn option_keys(f: PublishFormat) -> &'static [&'static str] { + match f { + PublishFormat::Html => &["title", "sound", "fit"], + PublishFormat::Gif => &["from", "to", "scale", "loop"], + PublishFormat::Video => &["from", "to", "scale", "audio"], + PublishFormat::Lottie => &["from", "to", "background"], + PublishFormat::SpriteSheet => &["from", "to", "scale", "columns", "padding", "background"], + PublishFormat::PngSequence => &["from", "to", "scale"], + PublishFormat::Png => &["frame", "scale"], + PublishFormat::Svg => &["frame"], + PublishFormat::Audio => &["from", "to", "rate", "bits"], + } +} + +/// A movie-frame param: absent (unchanged), null (the movie's end) or a frame. +fn opt_end(p: &Value, key: &str) -> Result>> { + match p.get(key) { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(_) => opt_u32(p, key).map(|v| Some(v.map(|f| f.min(crate::MAX_FRAME)))), + } +} + +fn set_range(r: &mut FrameRange, p: &Value) -> Result<()> { + if let Some(v) = opt_end(p, "from")? { + r.from = v; + } + if let Some(v) = opt_end(p, "to")? { + r.to = v; + } + if let (Some(a), Some(b)) = (r.from, r.to) + && b < a + { + return Err(EngineError::Param("'to' must not be before 'from'".into())); + } + Ok(()) +} + +fn set_scale(v: &mut f32, p: &Value) -> Result<()> { + if let Some(x) = opt_f32(p, "scale")? { + if !(x > 0.0 && x <= MAX_PUBLISH_SCALE) { + return Err(EngineError::Param(format!("param 'scale' must be in (0, {MAX_PUBLISH_SCALE}]"))); + } + *v = x; + } + Ok(()) +} + +fn set_bool(v: &mut bool, p: &Value, key: &str) -> Result<()> { + if let Some(b) = opt_bool(p, key)? { + *v = b; + } + Ok(()) +} + +/// Changes format `f`'s switch, output and options from `p`. +fn apply(prof: &mut PublishProfile, f: PublishFormat, p: &Value) -> Result<()> { + if let Some(obj) = p.as_object() { + let known = option_keys(f); + if let Some(k) = obj.keys().find(|k| !matches!(k.as_str(), "format" | "enabled" | "output" | "confirm") && !known.contains(&k.as_str())) { + return Err(EngineError::Param(format!("{} has no option '{k}' (it has {})", f.label(), known.join(", ")))); + } + } + if let Some(o) = opt_str(p, "output")? { + resolve(f, o, "name").map_err(|e| EngineError::Param(format!("{}: {e}", f.label())))?; + *prof.target_mut(f).1 = o.trim().to_string(); + } + if let Some(b) = opt_bool(p, "enabled")? { + *prof.target_mut(f).0 = b; + } + match f { + PublishFormat::Html => { + let h = &mut prof.html; + if let Some(t) = opt_str(p, "title")? { + if t.chars().count() > MAX_TITLE_CHARS { + return Err(EngineError::Param(format!("param 'title' is at most {MAX_TITLE_CHARS} characters"))); + } + h.title = t.to_string(); + } + set_bool(&mut h.sound, p, "sound")?; + set_bool(&mut h.fit, p, "fit")?; + } + PublishFormat::Gif => { + let g = &mut prof.gif; + set_range(&mut g.range, p)?; + set_scale(&mut g.scale, p)?; + set_bool(&mut g.looping, p, "loop")?; + } + PublishFormat::Video => { + let v = &mut prof.video; + set_range(&mut v.range, p)?; + set_scale(&mut v.scale, p)?; + set_bool(&mut v.audio, p, "audio")?; + } + PublishFormat::Lottie => { + set_range(&mut prof.lottie.range, p)?; + set_bool(&mut prof.lottie.background, p, "background")?; + } + PublishFormat::SpriteSheet => { + let sh = &mut prof.sprite_sheet; + set_range(&mut sh.range, p)?; + set_scale(&mut sh.scale, p)?; + if let Some(c) = opt_u32(p, "columns")? { + sh.columns = c.min(10_000); + } + if let Some(x) = opt_u32(p, "padding")? { + if x > 256 { + return Err(EngineError::Param("param 'padding' must be at most 256".into())); + } + sh.padding = x; + } + set_bool(&mut sh.background, p, "background")?; + } + PublishFormat::PngSequence => { + set_range(&mut prof.png_sequence.range, p)?; + set_scale(&mut prof.png_sequence.scale, p)?; + } + PublishFormat::Png => { + if let Some(fr) = opt_u32(p, "frame")? { + prof.png.frame = fr.min(crate::MAX_FRAME); + } + set_scale(&mut prof.png.scale, p)?; + } + PublishFormat::Svg => { + if let Some(fr) = opt_u32(p, "frame")? { + prof.svg.frame = fr.min(crate::MAX_FRAME); + } + } + PublishFormat::Audio => { + let a = &mut prof.audio; + set_range(&mut a.range, p)?; + if let Some(r) = opt_u32(p, "rate")? { + if !(8_000..=192_000).contains(&r) { + return Err(EngineError::Param("param 'rate' must be between 8000 and 192000".into())); + } + a.rate = r; + } + if let Some(b) = opt_u32(p, "bits")? { + if !matches!(b, 16 | 24 | 32) { + return Err(EngineError::Param("param 'bits' must be 16, 24 or 32 (float)".into())); + } + a.bits = b; + } + } + } + Ok(()) +} + +fn settings_set(s: &mut Session, p: &Value) -> Result { + let mut prof = match p.get("profile") { + None | Some(Value::Null) => (*s.doc.publish).clone(), + Some(v) => { + let mut prof: PublishProfile = serde_json::from_value(v.clone()).map_err(|e| EngineError::Param(format!("param 'profile' is not a publish profile: {e}")))?; + prof.sanitize(); + prof + } + }; + match opt_str(p, "format")? { + Some(k) => { + let f = PublishFormat::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown format '{k}' (html, gif, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))?; + apply(&mut prof, f, p)?; + } + None if p.get("profile").is_none_or(Value::is_null) && p.as_object().is_some_and(|o| o.keys().any(|k| k != "confirm" && k != "profile")) => { + return Err(EngineError::Param("name the 'format' to change, or pass a whole 'profile'".into())); + } + None => {} + } + if prof != *s.doc.publish { + s.doc.publish = Arc::new(prof); + } + Ok(settings_json(&s.doc, s.path.as_deref())) +} + +/// Writes `files` (path, bytes) as one uncompressed ZIP archive (what the browser downloads +/// when Publish writes more than one file). Paths keep their folders, with `/` between them. +pub fn zip(files: &[(PathBuf, Vec)]) -> std::result::Result, String> { + let mut out: Vec = Vec::new(); + let mut central: Vec = Vec::new(); + let n = u16::try_from(files.len()).map_err(|_| "too many files for one archive".to_string())?; + let le16 = |v: &mut Vec, x: u16| v.extend_from_slice(&x.to_le_bytes()); + let le32 = |v: &mut Vec, x: u32| v.extend_from_slice(&x.to_le_bytes()); + for (path, data) in files { + let name: String = path.components().filter_map(|c| if let Component::Normal(p) = c { Some(p.to_string_lossy().into_owned()) } else { None }).collect::>().join("/"); + let name_len = u16::try_from(name.len()).map_err(|_| "a file name is too long".to_string())?; + let size = u32::try_from(data.len()).map_err(|_| format!("{name} is too large for a ZIP archive (4 GB)"))?; + let offset = u32::try_from(out.len()).map_err(|_| "the archive is too large (4 GB)".to_string())?; + let crc = crc32(data); + // Local file header: version 2.0, UTF-8 names (bit 11), stored. + le32(&mut out, 0x0403_4b50); + for x in [20u16, 0x0800, 0, 0, 0x21] { + le16(&mut out, x); + } + for x in [crc, size, size] { + le32(&mut out, x); + } + le16(&mut out, name_len); + le16(&mut out, 0); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(data); + // Its central directory entry. + le32(&mut central, 0x0201_4b50); + for x in [20u16, 20, 0x0800, 0, 0, 0x21] { + le16(&mut central, x); + } + for x in [crc, size, size] { + le32(&mut central, x); + } + for x in [name_len, 0, 0, 0, 0] { + le16(&mut central, x); + } + le32(&mut central, 0); + le32(&mut central, offset); + central.extend_from_slice(name.as_bytes()); + } + let at = u32::try_from(out.len()).map_err(|_| "the archive is too large (4 GB)".to_string())?; + let len = u32::try_from(central.len()).map_err(|_| "the archive is too large".to_string())?; + out.extend_from_slice(¢ral); + le32(&mut out, 0x0605_4b50); + for x in [0u16, 0, n, n] { + le16(&mut out, x); + } + le32(&mut out, len); + le32(&mut out, at); + le16(&mut out, 0); + Ok(out) +} + +/// CRC-32 (IEEE 802.3, reflected, as ZIP uses), a byte at a time from a table. +fn crc32(data: &[u8]) -> u32 { + const TABLE: [u32; 256] = { + let mut t = [0u32; 256]; + let mut i = 0; + while i < 256 { + let mut c = i as u32; + let mut k = 0; + while k < 8 { + c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + k += 1; + } + t[i] = c; + i += 1; + } + t + }; + let mut c = !0u32; + for &b in data { + c = TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8); + } + !c +} + +#[cfg(test)] +#[path = "publish_tests.rs"] +mod tests; diff --git a/crates/engine/src/publish_tests.rs b/crates/engine/src/publish_tests.rs new file mode 100644 index 00000000..e8522153 --- /dev/null +++ b/crates/engine/src/publish_tests.rs @@ -0,0 +1,305 @@ +//! Publish Settings and Publish (ADR 0060): the profile in the file, where outputs go, the +//! plan, running every exporter with its options, cancelling, the combined report, the +//! confirmation, the browser's archive. + +use super::*; +use crate::{EngineError, Session, vfs}; +use anicraft_doc::sample; +use serde_json::json; +use std::path::{Path, PathBuf}; + +fn temp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("anicraft-publish-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// The demo, saved as `walk.anicraft` in a fresh folder. +fn saved(name: &str) -> (Session, PathBuf) { + let dir = temp(name); + let mut s = Session::new(sample::demo()); + run(&mut s, "file.save", json!({"path": dir.join("walk.anicraft").display().to_string()})); + (s, dir) +} + +#[test] +fn templates_resolve_inside_the_documents_folder() { + let r = |f, t: &str| resolve(f, t, "walk"); + assert_eq!(r(PublishFormat::Html, "{name}.html").unwrap(), PathBuf::from("walk.html")); + assert_eq!(r(PublishFormat::Gif, "web/{name}-small.gif").unwrap(), Path::new("web").join("walk-small.gif")); + assert_eq!(r(PublishFormat::Gif, "./{name}").unwrap(), PathBuf::from("walk.gif"), "a missing extension is the format's"); + assert_eq!(r(PublishFormat::Video, "{name}.MP4").unwrap(), PathBuf::from("walk.MP4")); + assert_eq!(r(PublishFormat::PngSequence, "{name}_frames").unwrap(), PathBuf::from("walk_frames"), "a folder has no extension"); + for bad in ["../{name}.gif", "/tmp/{name}.gif", "web/../../x.gif", "{title}.gif", "{name.gif", " ", "{name}.png"] { + assert!(r(PublishFormat::Gif, bad).is_err(), "{bad}"); + } + #[cfg(windows)] + assert!(r(PublishFormat::Gif, "C:\\x.gif").is_err() && r(PublishFormat::Gif, "C:x.gif").is_err()); + assert!(r(PublishFormat::Gif, &"a".repeat(600)).is_err()); + // The folder and name come from the document's path. + assert_eq!(base(Some(Path::new("art/walk.anicraft"))).unwrap(), (PathBuf::from("art"), "walk".to_string())); + assert!(base(None).is_err(), "an untitled document on disk saves first"); +} + +#[test] +fn settings_round_trip_through_the_file_and_older_files_get_defaults() { + let (mut s, dir) = saved("roundtrip"); + let v = run(&mut s, "publish.settings_set", json!({"format": "gif", "enabled": true, "output": "web/{name}.gif", "scale": 0.5, "loop": false, "from": 2, "to": 9})); + let gif = v["formats"].as_array().unwrap().iter().find(|f| f["format"] == "gif").unwrap(); + assert_eq!(gif["path"], json!(dir.join("web").join("walk.gif").display().to_string())); + run(&mut s, "publish.settings_set", json!({"format": "html", "title": "Walk cycle", "sound": false})); + run(&mut s, "publish.settings_set", json!({"format": "audio", "rate": 22050, "bits": 24, "to": null})); + let path = dir.join("walk.anicraft"); + run(&mut s, "file.save", json!({})); + let back = crate::format::load(&path).unwrap(); + assert_eq!(*back.publish, *s.doc.publish); + let p = &back.publish; + assert!(p.gif.enabled && !p.gif.looping && p.gif.scale == 0.5 && p.gif.range == FrameRange { from: Some(2), to: Some(9) }); + assert_eq!((p.html.title.as_str(), p.html.sound, p.audio.rate, p.audio.bits), ("Walk cycle", false, 22050, 24)); + // An untouched profile isn't written at all, so files from before publish settings look + // the same: they open with the HTML page on and the rest off. + let mut fresh = Session::new(sample::demo()); + let text = serde_json::to_string(&fresh.doc).unwrap(); + assert!(!text.contains("\"publish\"")); + let older: anicraft_doc::Document = serde_json::from_str(&text).unwrap(); + assert_eq!(older.publish.enabled(), vec![PublishFormat::Html]); + // Settings are a document change: undo takes them back. + run(&mut fresh, "publish.settings_set", json!({"format": "svg", "enabled": true})); + assert!(fresh.is_dirty() && fresh.doc.publish.svg.enabled); + run(&mut fresh, "edit.undo", json!({})); + assert!(!fresh.doc.publish.svg.enabled); + // A whole profile, as publish.settings_get gives it. + let whole = run(&mut s, "publish.settings_get", json!({}))["profile"].clone(); + run(&mut fresh, "publish.settings_set", json!({"profile": whole})); + assert_eq!(*fresh.doc.publish, *s.doc.publish); +} + +#[test] +fn settings_refuse_what_publish_couldnt_use() { + let mut s = Session::new(sample::demo()); + let before = s.doc.publish.clone(); + for bad in [ + json!({"format": "flash"}), + json!({"format": "gif", "rate": 44100}), + json!({"format": "gif", "scale": 0}), + json!({"format": "gif", "scale": 9}), + json!({"format": "gif", "from": 9, "to": 2}), + json!({"format": "gif", "output": "../x.gif"}), + json!({"format": "gif", "output": "x.png"}), + json!({"format": "audio", "bits": 8}), + json!({"format": "audio", "rate": 1}), + json!({"format": "sprite_sheet", "padding": 999}), + json!({"format": "html", "title": "x".repeat(300)}), + json!({"format": "html", "enabled": "yes"}), + json!({"enabled": true}), + json!({"profile": 5}), + json!({"profile": {"gif": {"scale": "big"}}}), + ] { + assert!(s.execute("publish.settings_set", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc.publish, before, "a refused change changes nothing"); + assert!(!s.is_dirty()); +} + +#[test] +fn the_plan_runs_each_exporter_with_its_options() { + let mut doc = sample::demo(); + let p = std::sync::Arc::make_mut(&mut doc.publish); + p.gif.enabled = true; + p.gif.scale = 0.25; + p.gif.looping = false; + p.gif.range = FrameRange { from: Some(1), to: Some(4) }; + p.sprite_sheet.enabled = true; + p.sprite_sheet.columns = 2; + p.svg.enabled = true; + p.svg.frame = 5; + let steps = plan(&doc, Some(Path::new("art/walk.anicraft")), None).unwrap(); + let order: Vec = steps.iter().map(|s| s.format).collect(); + assert_eq!(order, [PublishFormat::Html, PublishFormat::Gif, PublishFormat::SpriteSheet, PublishFormat::Svg], "in Publish's order"); + let gif = &steps[1]; + assert_eq!(gif.command, "file.export_gif"); + assert_eq!((gif.params["scale"].as_f64(), gif.params["loop"].as_bool(), gif.params["from"].as_u64(), gif.params["to"].as_u64(), gif.frames), (Some(0.25), Some(false), Some(1), Some(4), 4)); + assert_eq!(gif.params["path"], json!(Path::new("art").join("walk.gif").display().to_string())); + assert_eq!(steps[2].outputs, vec![Path::new("art").join("walk_sheet.png"), Path::new("art").join("walk_sheet.json")], "the sheet and its frame map"); + assert_eq!(steps[2].params["columns"], 2); + assert_eq!((steps[3].scene, steps[3].params["frame"].as_u64()), (0, Some(5))); + // Only some formats, when asked. + let some = plan(&doc, Some(Path::new("walk.anicraft")), Some(&[PublishFormat::Svg])).unwrap(); + assert_eq!(some.len(), 1); + // Two formats writing one file is refused, whatever the case. + std::sync::Arc::make_mut(&mut doc.publish).png.enabled = true; + std::sync::Arc::make_mut(&mut doc.publish).png.output = "{name}_SHEET.png".into(); + let err = plan(&doc, Some(Path::new("walk.anicraft")), None).unwrap_err(); + assert!(err.contains("Sprite sheet") && err.contains("PNG image"), "{err}"); + // Untitled, it asks to save first. + assert!(plan(&doc, None, None).unwrap_err().contains("save")); +} + +#[test] +fn publish_writes_every_format_and_reports_once() { + let (mut s, dir) = saved("all"); + for p in [ + json!({"format": "gif", "enabled": true, "scale": 0.1, "to": 3}), + json!({"format": "lottie", "enabled": true, "to": 3}), + json!({"format": "sprite_sheet", "enabled": true, "scale": 0.1, "to": 3, "columns": 2}), + json!({"format": "png_sequence", "enabled": true, "scale": 0.1, "to": 2, "output": "out/{name}_frames"}), + json!({"format": "png", "enabled": true, "scale": 0.1, "frame": 2}), + json!({"format": "svg", "enabled": true}), + json!({"format": "audio", "enabled": true}), + json!({"format": "video", "enabled": false}), + ] { + run(&mut s, "publish.settings_set", p); + } + let v = run(&mut s, "file.publish", json!({})); + let formats = v["formats"].as_array().unwrap(); + let status = |k: &str| formats.iter().find(|f| f["format"] == k).map(|f| f["status"].clone()).unwrap_or(Value::Null); + for k in ["html", "gif", "lottie", "sprite_sheet", "png_sequence", "png", "svg"] { + assert_eq!(status(k), "published", "{k}: {v}"); + } + assert_eq!(status("audio"), "skipped", "the demo has no sounds"); + assert_eq!(status("video"), Value::Null, "off formats don't run"); + assert_eq!((v["published"].as_u64(), v["skipped"].as_u64(), v["failed"].as_u64(), v["cancelled"].as_bool()), (Some(7), Some(1), Some(0), Some(false))); + let report = v["report"].as_str().unwrap(); + assert!(report.contains("Audio skipped: the movie has no sounds."), "{report}"); + // The files are there, made with each format's options. + for f in ["walk.html", "walk.gif", "walk.json", "walk_sheet.png", "walk_sheet.json", "walk.png", "walk.svg"] { + assert!(dir.join(f).is_file(), "{f}"); + } + let frames = std::fs::read_dir(dir.join("out").join("walk_frames")).unwrap().count(); + assert_eq!(frames, 3, "frames 1 to 3, in a folder made for them"); + let gif = std::fs::read(dir.join("walk.gif")).unwrap(); + let (w, h) = (u16::from_le_bytes([gif[6], gif[7]]), u16::from_le_bytes([gif[8], gif[9]])); + let view = anicraft_render::View::stage(&s.doc, 0.1); + assert_eq!((u32::from(w), u32::from(h)), (view.width, view.height), "the GIF's scale"); + let sheet: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("walk_sheet.json")).unwrap()).unwrap(); + assert_eq!(sheet["frames"].as_object().unwrap().len(), 4); + assert_eq!(v["files"].as_array().unwrap().len(), 8); + + // Publishing again replaces this session's own files without asking... + run(&mut s, "file.publish", json!({"formats": ["svg"]})); + // ...but another session (the next time the app starts) asks first. + run(&mut s, "file.save", json!({})); + let mut t = Session::default(); + run(&mut t, "file.open", json!({"path": dir.join("walk.anicraft").display().to_string()})); + let err = t.execute("file.publish", &json!({})).unwrap_err(); + assert!(matches!(err, EngineError::NeedsConfirmation(_)), "{err}"); + assert!(err.to_string().contains("walk.html"), "{err}"); + let c = t.confirmation("file.publish", &json!({})).unwrap(); + assert!(c.irreversible && c.message.contains("and 5 more"), "{}", c.message); + run(&mut t, "file.publish", json!({"confirm": true})); + assert!(t.confirmation("file.publish", &json!({})).is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn one_failing_format_doesnt_stop_the_others() { + let (mut s, dir) = saved("fail"); + run(&mut s, "publish.settings_set", json!({"format": "gif", "enabled": true, "scale": 8})); + run(&mut s, "publish.settings_set", json!({"format": "svg", "enabled": true})); + let v = run(&mut s, "file.publish", json!({})); + assert_eq!((v["published"].as_u64(), v["failed"].as_u64()), (Some(2), Some(1)), "{v}"); + assert!(v["report"].as_str().unwrap().starts_with("Animated GIF failed: that GIF would be too large"), "{v}"); + assert!(dir.join("walk.svg").is_file() && !dir.join("walk.gif").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn cancel_stops_cleanly() { + let (mut s, dir) = saved("cancel"); + for p in [json!({"format": "gif", "enabled": true, "scale": 0.1}), json!({"format": "svg", "enabled": true}), json!({"format": "png_sequence", "enabled": true, "scale": 0.1})] { + run(&mut s, "publish.settings_set", p); + } + // Cancelled after the first format: the rest never run. + let control = Arc::new(Control::default()); + let steps = plan(&s.doc, s.path.as_deref(), None).unwrap(); + let mut job = Publisher::new(s.doc.clone(), s.path.clone(), steps, control.clone()); + assert_eq!(job.current(), Some(PublishFormat::Html)); + assert_eq!(job.step().map(|o| o.status), Some(Status::Published)); + control.cancel(); + job.run_all(); + let r = job.report(); + assert!(job.done() && r.count(Status::Cancelled) == 3, "{:?}", r.to_json()); + assert!(dir.join("walk.html").is_file() && !dir.join("walk.gif").exists() && !dir.join("walk.svg").exists() && !dir.join("walk_frames").exists()); + assert_eq!(r.to_json()["cancelled"], true); + + // Cancelled inside an export: the GIF stops between frames and writes nothing. + let stop = Arc::new(Control::default()); + stop.cancel(); + s.job = Some(stop.clone()); + let gif = dir.join("inside.gif"); + assert!(matches!(s.execute("file.export_gif", &json!({"path": gif.display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(!gif.exists()); + let seq = dir.join("seq"); + assert!(matches!(s.execute("file.export_png_sequence", &json!({"dir": seq.display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(matches!(s.execute("file.export_sprite_sheet", &json!({"path": dir.join("s.png").display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(!dir.join("s.png").exists()); + // Progress counts frames made. + let watch = Arc::new(Control::default()); + s.job = Some(watch.clone()); + watch.begin(4); + run(&mut s, "file.export_gif", json!({"path": gif.display().to_string(), "scale": 0.1, "to": 3})); + assert_eq!(watch.progress(), (4, 4)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn publish_refuses_what_it_cant_run() { + let mut s = Session::new(sample::demo()); + assert!(s.execute("file.publish", &json!({})).unwrap_err().to_string().contains("save the document first")); + for bad in [json!({"formats": "gif"}), json!({"formats": ["gif", 3]}), json!({"formats": ["nope"]}), json!({"formats": [null]})] { + assert!(s.execute("file.publish", &bad).is_err(), "{bad}"); + assert!(s.confirmation("file.publish", &bad).is_none()); + } + let (mut t, dir) = saved("none"); + run(&mut t, "publish.settings_set", json!({"format": "html", "enabled": false})); + assert!(t.execute("file.publish", &json!({})).unwrap_err().to_string().contains("no format is on")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn in_a_browser_every_file_comes_back_and_several_make_one_zip() { + std::thread::spawn(|| { + vfs::use_memory(); + // Untitled: the browser has no folders, so it publishes as "Untitled". + let mut s = Session::new(sample::demo()); + for p in [json!({"format": "gif", "enabled": true, "scale": 0.1, "to": 2}), json!({"format": "video", "enabled": true}), json!({"format": "svg", "enabled": true, "output": "img/{name}.svg"})] { + run(&mut s, "publish.settings_set", p); + } + let v = run(&mut s, "file.publish", json!({})); + let video = v["formats"].as_array().unwrap().iter().find(|f| f["format"] == "video").unwrap().clone(); + assert_eq!(video["status"], "skipped"); + assert!(video["message"].as_str().unwrap().contains("web browser")); + let files = vfs::take_written(); + let names: Vec = files.iter().map(|(p, _)| p.to_string_lossy().replace('\\', "/")).collect(); + assert_eq!(names, ["Untitled.gif", "Untitled.html", "img/Untitled.svg"]); + let z = zip(&files).unwrap(); + // The end record says three entries; each name is in the archive with `/` between folders. + let end = z.len() - 22; + assert_eq!(&z[end..end + 4], &[0x50, 0x4b, 0x05, 0x06]); + assert_eq!(u16::from_le_bytes([z[end + 10], z[end + 11]]), 3); + assert!(z.windows(16).any(|w| w == b"img/Untitled.svg")); + let total: usize = files.iter().map(|(_, d)| d.len()).sum(); + assert!(z.len() > total && z.len() < total + 400, "stored, not compressed: {} for {total}", z.len()); + }) + .join() + .unwrap(); +} + +#[test] +fn crc32_matches_the_standard_check_value() { + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + assert_eq!(crc32(b""), 0); +} + +#[test] +fn plugins_may_read_but_not_change_or_run_publishing() { + use crate::cmds_plugin::plugin_may_call; + assert!(plugin_may_call("publish.settings_get").is_ok()); + assert!(plugin_may_call("publish.settings_set").is_err()); + assert!(plugin_may_call("file.publish").is_err()); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3127fcb4..bb7af08d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -638,6 +638,13 @@ fn panic_hunt_every_command() { json!({"on": "x", "left": f64::NAN, "right": "y", "top": null}), json!({"left": -1e7, "right": 1e7, "top": -1e7, "bottom": 1e7}), json!({"on": true, "symbol": u64::MAX}), + // Publish Settings (ADR 0060): ends past the movie, junk scales and names, whole + // profiles out of range. + json!({"format": "gif", "from": u64::MAX, "to": -1, "scale": f64::NAN, "output": "{name}\u{0}.gif"}), + json!({"format": "png", "frame": u64::MAX, "scale": 1e-30, "output": "a/b/c/../../{name}"}), + json!({"format": "sprite_sheet", "columns": u64::MAX, "padding": 256, "from": null, "to": null, "output": "{name}{name}{name}.png"}), + json!({"profile": {"gif": {"scale": 1e30, "range": {"from": 5, "to": 1}, "output": ""}, "audio": {"bits": 3, "rate": 0}, "html": {"title": "x"}}}), + json!({"profile": {"png": {"frame": 99_999, "enabled": true}}, "format": "svg", "enabled": true}), ]; // File commands are exercised separately (they touch the disk). let skip = |id: &str| id.starts_with("file."); From 08ed29ee97e614d49415a6dac86c4ac08e3adaed Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 15:20:23 -0700 Subject: [PATCH 046/192] feat(shell): Publish Settings window, background Publish with progress and report, presets (M8) --- src/a11y.rs | 2 +- src/app.rs | 32 ++ src/guidelines_tests.rs | 3 +- src/i18n/tests.rs | 2 +- src/main.rs | 3 +- src/prefs.rs | 34 ++ src/publish_panel.rs | 783 ++++++++++++++++++++++++++++++++++++++++ 7 files changed, 855 insertions(+), 4 deletions(-) create mode 100644 src/publish_panel.rs diff --git a/src/a11y.rs b/src/a11y.rs index 51e6842c..ef61b773 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -352,7 +352,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index 24e4670f..814ab7d0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -386,6 +386,8 @@ pub struct App { pub show_actions: bool, /// Edit › Find and Replace (Ctrl+F) and its results (ADR 0058). pub find: crate::find_panel::FindState, + /// File › Publish Settings and the publish running or last run (ADR 0060). + pub publish: crate::publish_panel::PublishState, /// Window › Movie Explorer, the Library dock's other tab (ADR 0058). pub explorer: crate::movie_explorer::ExplorerView, pub actions: crate::actions_panel::State, @@ -551,6 +553,7 @@ impl App { show_plugins: false, show_actions: false, find: Default::default(), + publish: Default::default(), explorer: Default::default(), actions: crate::actions_panel::State::default(), test_movie: None, @@ -796,6 +799,23 @@ impl App { self.find.with = "planet".into(); crate::find_panel::step(self, true); } + Some("publish") | Some("publishreport") => { + // Publish Settings (ADR 0060) on the sample, saved in a temporary folder: the GIF + // on and its options showing; or the report of publishing it (the HTML page and + // a small GIF, the soundtrack skipped: the sample has no sounds). + let dir = std::env::temp_dir().join("anicraft-publish-shot"); + let _ = std::fs::create_dir_all(&dir); + self.s.path = Some(dir.join("walk.anicraft")); + self.run("publish.settings_set", json!({"format": "gif", "enabled": true, "scale": 0.5, "from": 0, "to": 23})); + self.run("publish.settings_set", json!({"format": "audio", "enabled": true})); + self.prefs.publish_presets.insert("Web banner".into(), (*self.s.doc.publish).clone()); // i18n-exempt: a sample preset name the user typed + self.publish.selected = anicraft_engine::doc::publish::PublishFormat::Gif; + if which == Some("publish") { + crate::publish_panel::open(self); + } else { + crate::publish_panel::publish_now(self); + } + } Some("explorer") => { // The Movie Explorer tab (ADR 0058), its first rows open: scene, layers, keyframes // and the instances on them, opening into their symbols. @@ -1483,6 +1503,11 @@ impl App { /// Runs a command and reports the outcome; routine destructive edits say how to undo. pub fn perform(&mut self, id: &str, params: Value) -> Option { + if id == "file.publish" { + // File › Publish runs in the background, with its own progress view (ADR 0060). + crate::publish_panel::start(self, ¶ms); + return None; + } let selected = self.s.selection.len(); // A browser's autosaved copy opens as a file (ADR 0036): it is a restore all the same. let restored = autosave::restored_session(id, ¶ms); @@ -1693,6 +1718,12 @@ impl App { crate::find_panel::open(self); return; } + if id == "publish.settings_get" { + // File › Publish Settings (Ctrl+Shift+F12): its window (headless, the command + // returns the settings). + crate::publish_panel::open(self); + return; + } if id == "control.test_movie" { // Control › Test Movie: the player in its own window (headless, the command plays // the movie and reports). @@ -2304,6 +2335,7 @@ impl App { crate::plugins_ui::show(self, &ctx); crate::actions_panel::show(self, &ctx); crate::find_panel::show(self, &ctx); + crate::publish_panel::show(self, &ctx); crate::test_movie::show(self, &ctx); crate::envelope::show(self, &ctx); diff --git a/src/guidelines_tests.rs b/src/guidelines_tests.rs index 29e418af..79b94c68 100644 --- a/src/guidelines_tests.rs +++ b/src/guidelines_tests.rs @@ -1,6 +1,6 @@ //! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values. -const SOURCES: [(&str, &str); 22] = [ +const SOURCES: [(&str, &str); 23] = [ ("actions_panel.rs", include_str!("actions_panel.rs")), ("test_movie.rs", include_str!("test_movie.rs")), ("autosave.rs", include_str!("autosave.rs")), @@ -22,6 +22,7 @@ const SOURCES: [(&str, &str); 22] = [ ("bone_tool.rs", include_str!("bone_tool.rs")), ("find_panel.rs", include_str!("find_panel.rs")), ("movie_explorer.rs", include_str!("movie_explorer.rs")), + ("publish_panel.rs", include_str!("publish_panel.rs")), ("main.rs", ""), ]; diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index a5e1955d..e749ce23 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -587,7 +587,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("element.set_color_effect", serde_json::json!({"style": style})); })); } - for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer"] { + for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] { diff --git a/src/main.rs b/src/main.rs index 015c152c..f14e92fc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,6 +28,7 @@ mod autosave; mod brushtool; mod envelope; mod find_panel; +mod publish_panel; mod erasertool; mod bone_tool; mod camera_tool; @@ -182,7 +183,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu|colour]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|publish|publishreport|sound|envelope|library|librarymenu|colour]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/prefs.rs b/src/prefs.rs index 256bdd5a..5fcd979e 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -90,8 +90,14 @@ pub struct Prefs { pub autosave_edits: u32, /// Onion skin options (ADR 0047), kept from session to session. pub onion: OnionPrefs, + /// Publish Settings presets, by name (ADR 0060): yours on this computer, for any document. + pub publish_presets: std::collections::BTreeMap, } +/// Most publish presets kept, and the longest name one has. +pub const MAX_PUBLISH_PRESETS: usize = 100; +pub const MAX_PRESET_NAME: usize = 64; + /// Onion skin options that carry over between sessions (ADR 0047). Whether onion skin and Edit /// Multiple Frames are on, and anchored markers, last for the session only, as in Animate. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -140,6 +146,7 @@ impl Default for Prefs { autosave_secs: 60, autosave_edits: 25, onion: OnionPrefs::default(), + publish_presets: Default::default(), } } } @@ -171,6 +178,15 @@ impl Prefs { self.autosave_edits = self.autosave_edits.min(*AUTOSAVE_EDITS_RANGE.end()); self.onion.before = self.onion.before.min(ONION_REACH_MAX); self.onion.after = self.onion.after.min(ONION_REACH_MAX); + self.publish_presets = std::mem::take(&mut self.publish_presets) + .into_iter() + .filter(|(name, _)| !name.trim().is_empty() && name.chars().count() <= MAX_PRESET_NAME) + .take(MAX_PUBLISH_PRESETS) + .map(|(name, mut p)| { + p.sanitize(); + (name, p) + }) + .collect(); self } @@ -243,6 +259,24 @@ mod tests { assert!(fonts.regular("No Such Font Family 12345").is_none()); } + #[test] + fn publish_presets_round_trip_and_hostile_ones_are_dropped() { + let mut gif = anicraft_engine::doc::publish::PublishProfile::default(); + gif.gif.enabled = true; + gif.gif.scale = 0.5; + let mut p = Prefs::default(); + p.publish_presets.insert("Web small".into(), gif.clone()); + let back = Prefs::from_json(&serde_json::to_string(&p).unwrap()); + assert_eq!(back.publish_presets.get("Web small"), Some(&gif)); + let hostile = format!(r#"{{"publish_presets": {{"": {{}}, "{}": {{}}, "ok": {{"gif": {{"scale": 1e30}}, "audio": {{"bits": 3}}}}, "junk": 5}}}}"#, "n".repeat(100)); + let p = Prefs::from_json(&hostile); + assert!(p.publish_presets.is_empty() || p.publish_presets.len() == 1, "{:?}", p.publish_presets.keys()); + if let Some(ok) = p.publish_presets.get("ok") { + assert_eq!((ok.gif.scale, ok.audio.bits), (anicraft_engine::doc::publish::MAX_PUBLISH_SCALE, 16)); + } + assert_eq!(Prefs::from_json(r#"{"publish_presets": {"": {}, "a": {"gif": {"enabled": true}}}}"#).publish_presets.len(), 1); + } + #[test] fn broken_or_hostile_files_fall_back_to_defaults() { assert_eq!(Prefs::from_json("not json"), Prefs::default()); diff --git a/src/publish_panel.rs b/src/publish_panel.rs new file mode 100644 index 00000000..48a76f1e --- /dev/null +++ b/src/publish_panel.rs @@ -0,0 +1,783 @@ +//! File › Publish Settings (Ctrl+Shift+F12) and File › Publish (Shift+F12), ADR 0060. +//! +//! Publish Settings is a window that stays open while you work: every format with a checkbox, +//! and for the one selected its output name (relative to the document's folder, `{name}` the +//! document's name, checked as you type) and the same options its File › Export command has. +//! Each change is `publish.settings_set`: saved in the document, one undo step. Presets (yours, +//! in Preferences) apply a whole profile at once. +//! +//! Publish runs the formats that are on, in order, on a worker thread (`engine::publish:: +//! Publisher`, a session of its own), so the editor never waits. Its window shows each format's +//! progress and a Cancel button, then one report: what each wrote, skipped, left out or why it +//! failed. In a browser there are no threads: one format runs per frame, and the files come +//! back as downloads, as one ZIP when there are several. + +use crate::a11y::Named; +use crate::app::App; +use crate::theme::{FORM_LABEL_DIALOG, T, TARGET, Type, form_note, form_row, text}; +use anicraft_engine::doc::publish::{FrameRange, PublishFormat, PublishProfile}; +use anicraft_engine::publish::{self, Control, Outcome, Publisher, Report, Status}; +use serde_json::{Value, json}; +use std::sync::Arc; + +/// The Publish Settings window and the publish running or last run (view state). +pub struct PublishState { + pub open: bool, + /// The format whose options show. + pub selected: PublishFormat, + /// The output being typed, before it is checked and kept. + output_edit: Option<(PublishFormat, String)>, + /// The preset last applied or saved, and the name in the Save field. + preset: Option, + preset_name: String, + /// Delete was clicked once: the second click deletes (a preset is gone for good). + confirm_delete: bool, + job: Option, + /// The last publish's report, while its window is open. + pub report: Option, +} + +impl Default for PublishState { + fn default() -> Self { + PublishState { open: false, selected: PublishFormat::Html, output_edit: None, preset: None, preset_name: String::new(), confirm_delete: false, job: None, report: None } + } +} + +impl PublishState { + pub fn running(&self) -> bool { + self.job.is_some() + } +} + +/// A message from the worker. +enum Msg { + Started(PublishFormat), + Done(Box), + Finished, +} + +/// Where the publish runs. +enum Runner { + /// A worker thread (the desktop). + Thread(std::sync::mpsc::Receiver), + /// Here, one format per frame (a browser, or when no thread could start). + Here(Box), +} + +/// A publish in progress. +struct Job { + control: Arc, + /// The formats it runs, and the file each writes first (for its row). + formats: Vec<(PublishFormat, String)>, + running: Option, + done: Vec, + runner: Runner, + /// The document's name, for the browser's ZIP. + name: String, +} + +/// The format's name, in the interface language. +pub fn label(f: PublishFormat) -> &'static str { + crate::i18n::t(match f { + PublishFormat::Html => tr_noop!("HTML canvas"), + PublishFormat::Gif => tr_noop!("Animated GIF"), + PublishFormat::Video => tr_noop!("Video"), + PublishFormat::Lottie => tr_noop!("Lottie"), + PublishFormat::SpriteSheet => tr_noop!("Sprite sheet"), + PublishFormat::PngSequence => tr_noop!("PNG sequence"), + PublishFormat::Png => tr_noop!("PNG image"), + PublishFormat::Svg => tr_noop!("SVG image"), + PublishFormat::Audio => tr_noop!("Audio"), + }) +} + +/// What the format makes, for its options' heading. +fn about(f: PublishFormat) -> &'static str { + crate::i18n::t(match f { + PublishFormat::Html => tr_noop!("One web page that plays the movie, buttons and actions included."), + PublishFormat::Gif => tr_noop!("An animated GIF, with exact frame timing."), + PublishFormat::Video => tr_noop!("WebM or MP4 video, made with your ffmpeg (ffmpeg.org)."), + PublishFormat::Lottie => tr_noop!("A Lottie animation (JSON) for web and apps."), + PublishFormat::SpriteSheet => tr_noop!("Frames in a grid on one PNG, with a JSON frame map beside it."), + PublishFormat::PngSequence => tr_noop!("One PNG per frame, in a folder."), + PublishFormat::Png => tr_noop!("One frame as a PNG image."), + PublishFormat::Svg => tr_noop!("One frame as an SVG drawing."), + PublishFormat::Audio => tr_noop!("The movie's soundtrack as a WAV file."), + }) +} + +/// File › Publish Settings (Ctrl+Shift+F12): opens the window. +pub fn open(app: &mut App) { + app.publish.open = true; +} + +/// File › Publish (Shift+F12), after any confirmation: starts publishing in the background. +pub fn start(app: &mut App, params: &Value) { + begin(app, params, true); +} + +/// Publishes the formats that are on, here and now, to the report (screenshots and tests). +pub fn publish_now(app: &mut App) { + begin(app, &json!({"confirm": true}), false); + if let Some(mut job) = app.publish.job.take() { + if let Runner::Here(p) = &mut job.runner { + while let Some(o) = p.step() { + job.done.push(o.clone()); + } + } + finish(app, job); + } +} + +fn begin(app: &mut App, params: &Value, threaded: bool) { + if app.publish.job.is_some() { + app.status_err(tr!("Publishing is already running")); + return; + } + let only = match publish::formats_param(params) { + Ok(o) => o, + Err(e) => return app.status_err(crate::i18n::t_dyn(&e.to_string()).into_owned()), + }; + let steps = match publish::plan(&app.s.doc, app.s.path.as_deref(), only.as_deref()) { + Ok(s) => s, + Err(e) => { + if app.s.path.is_none() && !crate::platform::WEB { + // Untitled: files go beside the document, so it needs a folder first. + app.status_err(tr!("Save the document first: Publish writes its files beside it.")); + app.invoke("file.save_as"); + } else { + app.status_err(crate::i18n::t_dyn(&e).into_owned()); + app.publish.open = true; + } + return; + } + }; + if steps.is_empty() { + app.status_err(tr!("No format is on in Publish Settings: turn one on first.")); + app.publish.open = true; + return; + } + app.playing = false; + let formats = steps.iter().map(|s| (s.format, s.outputs.first().and_then(|o| o.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())).collect(); + let control = Arc::new(Control::default()); + let (doc, path) = (app.s.doc.clone(), app.s.path.clone()); + let name = publish::base(path.as_deref()).map(|(_, n)| n).unwrap_or_default(); + let runner = threaded.then(|| spawn(doc.clone(), path.clone(), steps.clone(), control.clone())).flatten().unwrap_or_else(|| Runner::Here(Box::new(Publisher::new(doc, path, steps, control.clone())))); + app.publish.report = None; + app.publish.job = Some(Job { control, formats, running: None, done: Vec::new(), runner, name }); +} + +/// The worker thread, on the desktop; `None` where there are no threads (or none started). +fn spawn(doc: anicraft_engine::doc::Document, path: Option, steps: Vec, control: Arc) -> Option { + if crate::platform::WEB { + return None; + } + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .name("anicraft-publish".into()) + .spawn(move || { + let mut job = Publisher::new(doc, path, steps, control); + while let Some(f) = job.current() { + let _ = tx.send(Msg::Started(f)); + let Some(out) = job.step().cloned() else { break }; + let _ = tx.send(Msg::Done(Box::new(out))); + } + let _ = tx.send(Msg::Finished); + }) + .ok()?; + Some(Runner::Thread(rx)) +} + +/// Moves a running publish along (every frame): takes the worker's news, or runs the next +/// format here; and when it is done, reports. +pub fn tick(app: &mut App, ctx: &egui::Context) { + let Some(job) = app.publish.job.as_mut() else { return }; + let mut finished = false; + match &mut job.runner { + Runner::Thread(rx) => { + while let Ok(m) = rx.try_recv() { + match m { + Msg::Started(f) => job.running = Some(f), + Msg::Done(o) => { + job.running = None; + job.done.push(*o); + } + Msg::Finished => finished = true, + } + } + if !finished && matches!(rx.try_recv(), Err(std::sync::mpsc::TryRecvError::Disconnected)) { + finished = true; // the worker is gone: what it reported is the report + } + } + Runner::Here(p) => { + // A frame shows which format runs before it runs (it holds this thread). + match (job.running, p.current()) { + (None, Some(f)) => job.running = Some(f), + (Some(_), Some(_)) => { + if let Some(o) = p.step() { + job.done.push(o.clone()); + } + job.running = None; + } + (_, None) => finished = true, + } + } + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + if finished && let Some(job) = app.publish.job.take() { + finish(app, job); + } +} + +fn finish(app: &mut App, job: Job) { + let report = Report { outcomes: job.done }; + let files = report.files(); + app.s.published.extend(files.iter().cloned()); + if crate::platform::WEB { + // In a browser the files are in memory: they go to the downloads, in one ZIP when there + // are several (ADR 0060). + let written = anicraft_engine::vfs::take_written(); + if written.len() > 1 { + match publish::zip(&written) { + Ok(z) => crate::platform::deliver(vec![(std::path::PathBuf::from(format!("{}.zip", job.name)), z)]), + Err(e) => { + app.status_err(tr!("Could not make the archive: {e}", e = e)); + crate::platform::deliver(written); + } + } + } else { + crate::platform::deliver(written); + } + } + let (ok, failed, skipped) = (report.count(Status::Published), report.count(Status::Failed), report.count(Status::Skipped)); + if report.count(Status::Cancelled) > 0 { + app.status_ok(trn!("Publish cancelled after {n} format", "Publish cancelled after {n} formats", ok)); + } else if failed > 0 { + app.status_err(trn!("Published {n} format; {failed} failed. The report says why.", "Published {n} formats; {failed} failed. The report says why.", ok, failed = failed)); + } else if skipped > 0 { + app.status_ok(trn!("Published {n} format; {skipped} skipped (see the report)", "Published {n} formats; {skipped} skipped (see the report)", ok, skipped = skipped)); + } else { + app.status_ok(trn!("Published {n} format ({files} files)", "Published {n} formats ({files} files)", ok, files = files.len())); + } + app.publish.report = Some(report); +} + +/// Cancels the running publish: the format running stops at its next frame, the rest don't run. +pub fn cancel(app: &mut App) { + if let Some(j) = &app.publish.job { + j.control.cancel(); + } +} + +pub fn show(app: &mut App, ctx: &egui::Context) { + tick(app, ctx); + settings_window(app, ctx); + progress_window(app, ctx); +} + +// ----- Publish Settings ------------------------------------------------------------------------- + +fn settings_window(app: &mut App, ctx: &egui::Context) { + if !app.publish.open { + return; + } + let mut open = true; + let at = ctx.content_rect().center() - egui::vec2(330.0, 260.0); + let shown = egui::Window::new(tr!("Publish Settings")).id(egui::Id::new("publish_settings")).open(&mut open).default_pos(at).default_width(660.0).resizable(true).collapsible(false).show(ctx, |ui| settings(app, ui)); + crate::a11y::name_title_bar(&shown, tr!("Publish Settings")); + if !open { + app.publish.open = false; + app.publish.output_edit = None; + } +} + +fn settings(app: &mut App, ui: &mut egui::Ui) { + presets_row(app, ui); + ui.separator(); + ui.horizontal_top(|ui| { + // The formats, each with its switch; clicking a name shows its options. + ui.vertical(|ui| { + ui.set_width(190.0); + ui.label(text(Type::Heading, tr!("Formats"))); + for f in PublishFormat::ALL { + let mut on = app.s.doc.publish.target(f).0; + ui.horizontal(|ui| { + if crate::theme::checkbox(ui, &mut on, "").named(&tr!("Publish {format}", format = label(f))).changed() { + app.run("publish.settings_set", json!({"format": f.key(), "enabled": on})); + app.publish.selected = f; + } + let sel = app.publish.selected == f; + let (r, resp) = ui.allocate_exact_size(egui::vec2(140.0, TARGET - 4.0), egui::Sense::click()); + if sel || resp.hovered() { + ui.painter().rect_filled(r, T.rc(), if sel { T.accent_dim } else { T.hover }); + } + let font = crate::theme::font(Type::Body); + ui.painter().text(egui::pos2(r.left() + 8.0, r.center().y), egui::Align2::LEFT_CENTER, label(f), font, crate::theme::color(Type::Body)); + crate::a11y::control(ui, &resp, egui::WidgetType::SelectableLabel, label(f), Some(sel)); + if resp.on_hover_text(about(f)).clicked() { + app.publish.selected = f; + app.publish.output_edit = None; + } + }); + } + }); + ui.add_space(12.0); + ui.vertical(|ui| { + ui.set_min_height(360.0); + options(app, ui, app.publish.selected); + }); + }); + ui.separator(); + footer(app, ui); +} + +/// The output name field, checked as you type and kept when it is one. +fn output_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat) { + let saved = app.s.doc.publish.target(f).1.to_string(); + let mut value = match &app.publish.output_edit { + Some((g, v)) if *g == f => v.clone(), + _ => saved.clone(), + }; + let base = publish::base(app.s.path.as_deref()); + let name = base.as_ref().map_or_else(|_| tr!("Untitled").to_string(), |(_, n)| n.clone()); + let checked = publish::resolve(f, &value, &name); + let resp = form_row(ui, FORM_LABEL_DIALOG, tr!("Output"), |ui| { + let edit = egui::TextEdit::singleline(&mut value).font(crate::theme::font(Type::Path)).desired_width(300.0).char_limit(anicraft_engine::doc::publish::MAX_OUTPUT_CHARS).hint_text(f.default_output()); + let r = ui.add(edit).named(&tr!("{format} output name", format = label(f))); + if ui.button(tr!("Default")).on_hover_text(tr!("Use the format's usual name: {name}", name = f.default_output())).clicked() { + value = f.default_output().to_string(); + app.publish.output_edit = None; + app.run("publish.settings_set", json!({"format": f.key(), "output": value})); + } + r + }); + if resp.changed() { + app.publish.output_edit = Some((f, value.clone())); + } + // Kept when you leave the field (or press Enter) and it is a name Publish can use. + if resp.lost_focus() { + if checked.is_ok() && value.trim() != saved { + app.run("publish.settings_set", json!({"format": f.key(), "output": value.trim()})); + } + if checked.is_ok() { + app.publish.output_edit = None; + } + } + let note = match (&checked, &base) { + (Err(e), _) => text(Type::Caption, crate::i18n::t_dyn(e)).color(T.error), + (Ok(rel), Ok((dir, _))) => text(Type::Path, dir.join(rel).display().to_string()).color(T.text_dim), + (Ok(rel), Err(_)) => text(Type::Caption, tr!("{path}, beside the document once it is saved", path = rel.display().to_string())), + }; + form_note(ui, FORM_LABEL_DIALOG, note); +} + +/// A setting changed: kept in the document (drags coalesce into one undo step). +fn set(app: &mut App, f: PublishFormat, key: &str, v: Value, drag: bool) { + let p = json!({"format": f.key(), key: v}); + if drag { + crate::panels::live(app, tr_noop!("Publish Settings"), "publish.settings_set", p); + } else { + app.run("publish.settings_set", p); + } +} + +fn check(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, key: &str, mut on: bool, label: &str, tip: &str) { + ui.horizontal(|ui| { + ui.add_space(FORM_LABEL_DIALOG + ui.spacing().item_spacing.x); + if crate::theme::checkbox(ui, &mut on, label).on_hover_text(tip).changed() { + set(app, f, key, json!(on), false); + } + }); +} + +fn scale_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, scale: f32) { + let mut pct = (scale * 100.0).round(); + form_row(ui, FORM_LABEL_DIALOG, tr!("Scale"), |ui| { + let r = ui.add(egui::DragValue::new(&mut pct).range(1.0..=800.0).suffix(" %").speed(1.0)).named(tr!("Scale")); + if r.changed() { + set(app, f, "scale", json!(pct / 100.0), true); + } + let s = &app.s.doc.stage; + ui.label(text(Type::Data, format!("{} × {}", (s.width as f32 * pct / 100.0).ceil(), (s.height as f32 * pct / 100.0).ceil()))); + }); +} + +/// Which movie frames: all of them, or from one to another (shown 1-based, as the timeline). +fn range_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, r: FrameRange) { + let total = app.s.doc.frame_count(); + let mut all = r.from.is_none() && r.to.is_none(); + form_row(ui, FORM_LABEL_DIALOG, tr!("Frames"), |ui| { + if crate::theme::checkbox(ui, &mut all, tr!("All")).on_hover_text(tr!("Every frame of every scene, in order")).changed() { + if all { + app.run("publish.settings_set", json!({"format": f.key(), "from": null, "to": null})); + } else { + app.run("publish.settings_set", json!({"format": f.key(), "from": 0, "to": total.saturating_sub(1)})); + } + } + if all { + ui.label(text(Type::Data, format!("1–{total}"))); + return; + } + let mut from = r.from.unwrap_or(0) + 1; + let mut to = r.to.unwrap_or(total.saturating_sub(1)) + 1; + if ui.add(egui::DragValue::new(&mut from).range(1..=to.max(1)).speed(0.2)).named(tr!("First frame")).changed() { + set(app, f, "from", json!(from - 1), true); + } + ui.label(text(Type::Label, tr!("to"))); + if ui.add(egui::DragValue::new(&mut to).range(from..=total.max(from)).speed(0.2)).named(tr!("Last frame")).changed() { + set(app, f, "to", json!(to - 1), true); + } + }); +} + +fn frame_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, frame: u32) { + let total = app.s.doc.frame_count(); + let mut shown = frame.min(total.saturating_sub(1)) + 1; + form_row(ui, FORM_LABEL_DIALOG, tr!("Frame"), |ui| { + if ui.add(egui::DragValue::new(&mut shown).range(1..=total.max(1)).speed(0.2)).named(tr!("Frame to publish")).changed() { + set(app, f, "frame", json!(shown - 1), true); + } + if ui.button(tr!("Playhead")).on_hover_text(tr!("The frame the playhead is on")).clicked() { + let movie = app.s.doc.scene_start(app.s.scene).saturating_add(app.s.frame); + set(app, f, "frame", json!(movie), false); + } + }); +} + +fn options(app: &mut App, ui: &mut egui::Ui, f: PublishFormat) { + ui.label(text(Type::Heading, label(f))); + ui.label(text(Type::Caption, about(f))); + ui.add_space(4.0); + output_row(app, ui, f); + let p: PublishProfile = (*app.s.doc.publish).clone(); + match f { + PublishFormat::Html => { + let mut title = p.html.title.clone(); + form_row(ui, FORM_LABEL_DIALOG, tr!("Page title"), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut title).desired_width(300.0).char_limit(anicraft_engine::doc::publish::MAX_TITLE_CHARS).hint_text(tr!("The file's name"))).named(tr!("Page title")); + if r.changed() { + set(app, f, "title", json!(title), true); + } + }); + check(app, ui, f, "sound", p.html.sound, tr!("Include sounds"), tr!("The movie's sounds play in the page")); + check(app, ui, f, "fit", p.html.fit, tr!("Scale to the browser window"), tr!("Off: the movie shows at its stage size")); + } + PublishFormat::Gif => { + range_row(app, ui, f, p.gif.range); + scale_row(app, ui, f, p.gif.scale); + check(app, ui, f, "loop", p.gif.looping, tr!("Loop"), tr!("Off: it plays once and stops on the last frame")); + } + PublishFormat::Video => { + range_row(app, ui, f, p.video.range); + scale_row(app, ui, f, p.video.scale); + check(app, ui, f, "audio", p.video.audio, tr!("Include sound"), tr!("The movie's sounds: Opus in WebM, AAC in MP4")); + form_note(ui, FORM_LABEL_DIALOG, text(Type::Caption, tr!("End the name in .webm (VP9) or .mp4 (H.264). AniCraft uses the ffmpeg on this computer."))); + } + PublishFormat::Lottie => { + range_row(app, ui, f, p.lottie.range); + check(app, ui, f, "background", p.lottie.background, tr!("Stage colour as background"), tr!("Off: transparent")); + } + PublishFormat::SpriteSheet => { + let sh = &p.sprite_sheet; + range_row(app, ui, f, sh.range); + scale_row(app, ui, f, sh.scale); + let (mut cols, mut pad) = (sh.columns, sh.padding); + form_row(ui, FORM_LABEL_DIALOG, tr!("Columns"), |ui| { + let r = ui.add(egui::DragValue::new(&mut cols).range(0..=1000).speed(0.1).custom_formatter(|v, _| if v == 0.0 { tr!("Auto").to_string() } else { format!("{v}") })).named(tr!("Columns")); + if r.changed() { + set(app, f, "columns", json!(cols), true); + } + ui.label(text(Type::Label, tr!("Padding"))); + if ui.add(egui::DragValue::new(&mut pad).range(0..=256).suffix(" px").speed(0.2)).named(tr!("Padding")).changed() { + set(app, f, "padding", json!(pad), true); + } + }); + check(app, ui, f, "background", sh.background, tr!("Stage colour as background"), tr!("Off: transparent")); + } + PublishFormat::PngSequence => { + range_row(app, ui, f, p.png_sequence.range); + scale_row(app, ui, f, p.png_sequence.scale); + form_note(ui, FORM_LABEL_DIALOG, text(Type::Caption, tr!("The output is a folder; the frames in it are frame_00001.png and on."))); + } + PublishFormat::Png => { + frame_row(app, ui, f, p.png.frame); + scale_row(app, ui, f, p.png.scale); + } + PublishFormat::Svg => frame_row(app, ui, f, p.svg.frame), + PublishFormat::Audio => { + range_row(app, ui, f, p.audio.range); + let rates = [22_050u32, 44_100, 48_000, 96_000]; + form_row(ui, FORM_LABEL_DIALOG, tr!("Sample rate"), |ui| { + egui::ComboBox::from_id_salt("publish_rate").selected_text(text(Type::Data, format!("{} Hz", p.audio.rate))).show_ui(ui, |ui| { + for r in rates { + if ui.selectable_label(p.audio.rate == r, text(Type::Data, format!("{r} Hz"))).clicked() { + set(app, f, "rate", json!(r), false); + } + } + }) + .response + .set_name(tr!("Sample rate")); + }); + form_row(ui, FORM_LABEL_DIALOG, tr!("Bit depth"), |ui| { + let name = |b: u32| if b == 32 { tr!("32-bit float").to_string() } else { tr!("{bits}-bit", bits = b) }; + egui::ComboBox::from_id_salt("publish_bits").selected_text(name(p.audio.bits)).show_ui(ui, |ui| { + for b in [16u32, 24, 32] { + if ui.selectable_label(p.audio.bits == b, name(b)).clicked() { + set(app, f, "bits", json!(b), false); + } + } + }) + .response + .set_name(tr!("Bit depth")); + }); + if !anicraft_engine::doc::sound::has_sounds(&app.s.doc) { + form_note(ui, FORM_LABEL_DIALOG, text(Type::Caption, tr!("The movie has no sounds yet, so Publish skips the audio."))); + } + } + } +} + +/// Where the files go, and Publish. +fn footer(app: &mut App, ui: &mut egui::Ui) { + let on = app.s.doc.publish.enabled().len(); + ui.horizontal(|ui| { + let where_ = match publish::base(app.s.path.as_deref()) { + Ok((dir, _)) if crate::platform::WEB => { + let _ = dir; + tr!("Files go to your downloads (several as one ZIP).").to_string() + } + Ok((dir, _)) => tr!("Files go beside the document, in {folder}", folder = dir.display().to_string()), + Err(_) => tr!("Save the document first: files go beside it.").to_string(), + }; + ui.label(text(Type::Caption, where_)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let key = app.keymap.primary("file.publish").map(crate::platform::shortcut_label).unwrap_or_default(); + let busy = app.publish.running(); + let button = egui::Button::new(text(Type::Body, tr!("Publish")).strong().color(T.on_fill)).fill(T.accent).min_size(egui::vec2(110.0, TARGET + 4.0)); + let tip = crate::a11y::with_key(&trn!("Publish the {n} format that is on", "Publish the {n} formats that are on", on), Some(&key)); + if ui.add_enabled(on > 0 && !busy, button).on_hover_text(tip).on_disabled_hover_text(if busy { tr!("Publishing is running") } else { tr!("Turn a format on first") }).clicked() { + app.request("file.publish", json!({})); + } + ui.label(text(Type::Caption, trn!("{n} format on", "{n} formats on", on))); + }); + }); +} + +/// Presets (yours, kept in Preferences): apply one, save the settings as one, delete one. +fn presets_row(app: &mut App, ui: &mut egui::Ui) { + form_row(ui, FORM_LABEL_DIALOG, tr!("Preset"), |ui| { + let names: Vec = app.prefs.publish_presets.keys().cloned().collect(); + let shown = app.publish.preset.clone().filter(|p| names.contains(p)).unwrap_or_else(|| tr!("Choose a preset").to_string()); + let mut chosen = None; + egui::ComboBox::from_id_salt("publish_preset") + .width(170.0) + .selected_text(shown) + .show_ui(ui, |ui| { + if ui.selectable_label(false, tr!("Default")).on_hover_text(tr!("The HTML page on, every other format off")).clicked() { + chosen = Some((tr!("Default").to_string(), PublishProfile::default())); + } + for n in &names { + if ui.selectable_label(app.publish.preset.as_deref() == Some(n.as_str()), n.as_str()).clicked() { + chosen = app.prefs.publish_presets.get(n).map(|p| (n.clone(), p.clone())); + } + } + }) + .response + .set_name(tr!("Apply a preset")); + if let Some((n, p)) = chosen { + if app.run("publish.settings_set", json!({"profile": p})).is_some() { + app.status_ok(tr!("Applied the preset “{name}” — {undo} to undo", name = n, undo = app.undo_key())); + } + app.publish.preset = Some(n); + app.publish.output_edit = None; + app.publish.confirm_delete = false; + } + let name_ok = !app.publish.preset_name.trim().is_empty(); + ui.add(egui::TextEdit::singleline(&mut app.publish.preset_name).desired_width(130.0).char_limit(crate::prefs::MAX_PRESET_NAME).hint_text(tr!("New preset name"))).set_name(tr!("New preset name")); + if ui.add_enabled(name_ok, egui::Button::new(tr!("Save Preset"))).on_hover_text(tr!("Keep these settings as a preset you can apply to any document")).clicked() { + save_preset(app); + } + let current = app.publish.preset.clone().filter(|p| app.prefs.publish_presets.contains_key(p)); + if let Some(n) = current { + if app.publish.confirm_delete { + if ui.add(egui::Button::new(text(Type::Body, tr!("Delete “{name}”", name = n)).color(T.on_fill)).fill(T.danger)).on_hover_text(tr!("Deleting a preset can't be undone")).clicked() { + delete_preset(app, &n); + } + if ui.button(tr!("Keep")).clicked() { + app.publish.confirm_delete = false; + } + } else if ui.button(tr!("Delete Preset")).on_hover_text(tr!("Delete the preset “{name}” (asks once more)", name = n)).clicked() { + app.publish.confirm_delete = true; + } + } + }); +} + +fn save_presets(app: &mut App) { + if app.shot.is_none() + && let Err(e) = app.prefs.save() + { + app.status_err(tr!("Could not save preferences: {e}", e = e)); + } +} + +/// Keeps the document's settings as the preset named in the field (replacing one of that name). +pub fn save_preset(app: &mut App) { + let name: String = app.publish.preset_name.trim().chars().take(crate::prefs::MAX_PRESET_NAME).collect(); + if name.is_empty() { + return; + } + let presets = &mut app.prefs.publish_presets; + if !presets.contains_key(&name) && presets.len() >= crate::prefs::MAX_PUBLISH_PRESETS { + app.status_err(tr!("You have {n} presets, the most there can be: delete one first", n = crate::prefs::MAX_PUBLISH_PRESETS)); + return; + } + let replaced = presets.insert(name.clone(), (*app.s.doc.publish).clone()).is_some(); + save_presets(app); + app.status_ok(if replaced { tr!("Updated the preset “{name}”", name = name) } else { tr!("Saved the preset “{name}”", name = name) }); + app.publish.preset = Some(name); + app.publish.preset_name.clear(); + app.publish.confirm_delete = false; +} + +fn delete_preset(app: &mut App, name: &str) { + app.prefs.publish_presets.remove(name); + save_presets(app); + app.publish.preset = None; + app.publish.confirm_delete = false; + app.status_ok(tr!("Deleted the preset “{name}”", name = name)); +} + +// ----- progress and report ---------------------------------------------------------------------- + +fn status_text(s: Status) -> (&'static str, egui::Color32) { + match s { + Status::Published => (tr!("Published"), T.ok), + Status::Skipped => (tr!("Skipped"), T.text_dim), + Status::Failed => (tr!("Failed"), T.error), + Status::Cancelled => (tr!("Cancelled"), T.text_dim), + } +} + +fn progress_window(app: &mut App, ctx: &egui::Context) { + if app.publish.job.is_none() && app.publish.report.is_none() { + return; + } + let running = app.publish.job.is_some(); + let mut open = true; + let title = if running { tr!("Publishing") } else { tr!("Publish report") }; + let at = ctx.content_rect().center() - egui::vec2(220.0, 160.0); + let shown = egui::Window::new(title).id(egui::Id::new("publish_progress")).open(&mut open).default_pos(at).default_width(460.0).resizable(true).collapsible(false).show(ctx, |ui| { + if let Some(job) = &app.publish.job { + job_rows(ui, job); + } else if let Some(r) = &app.publish.report { + report_rows(ui, r); + } + ui.add_space(6.0); + ui.horizontal(|ui| { + if running { + let cancelling = app.publish.job.as_ref().is_some_and(|j| j.control.cancelled()); + if ui.add_enabled(!cancelling, egui::Button::new(tr!("Cancel")).min_size(egui::vec2(96.0, TARGET))).on_hover_text(tr!("Stop after the frame being made; formats not started don't run")).clicked() { + cancel(app); + } + if cancelling { + ui.label(text(Type::Caption, tr!("Stopping…"))); + } + } else { + if ui.add(egui::Button::new(tr!("Close")).min_size(egui::vec2(96.0, TARGET))).clicked() { + app.publish.report = None; + } + if ui.button(tr!("Publish Settings…")).clicked() { + open_settings_from_report(app); + } + } + }); + }); + crate::a11y::name_title_bar(&shown, title); + if !open { + if running { + cancel(app); + } else { + app.publish.report = None; + } + } +} + +fn open_settings_from_report(app: &mut App) { + app.publish.open = true; + if let Some(f) = app.publish.report.as_ref().and_then(|r| r.outcomes.iter().find(|o| o.status == Status::Failed)).map(|o| o.format) { + app.publish.selected = f; + } +} + +/// A format's name at the start of its row, in a column of its own. +fn name_cell(ui: &mut egui::Ui, name: &str) { + ui.allocate_ui_with_layout(egui::vec2(120.0, TARGET), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_size(egui::vec2(120.0, TARGET)); + ui.label(text(Type::Body, name)); + }); +} + +/// A message as a sentence: capital first, full stop at the end. +fn sentence(m: &str) -> String { + let mut c = m.trim().chars(); + let mut s: String = c.next().map(|f| f.to_uppercase().chain(c).collect()).unwrap_or_default(); + if !s.is_empty() && !s.ends_with(['.', ')', '!', '?']) { + s.push('.'); + } + s +} + +/// One row per format: done, running (with its frames), or waiting. +fn job_rows(ui: &mut egui::Ui, job: &Job) { + let (done, total) = job.control.progress(); + for (f, file) in &job.formats { + ui.horizontal(|ui| { + ui.set_min_height(TARGET); + name_cell(ui, label(*f)); + if let Some(o) = job.done.iter().find(|o| o.format == *f) { + let (s, c) = status_text(o.status); + ui.label(text(Type::Label, s).color(c)); + } else if job.running == Some(*f) { + if total > 0 { + let frac = (done as f32 / total as f32).clamp(0.0, 1.0); + ui.add(egui::ProgressBar::new(frac).desired_width(160.0).text(text(Type::DataSmall, format!("{done} / {total}")))); + } else { + ui.add(egui::Spinner::new()); + ui.label(text(Type::Label, tr!("Working…"))); + } + } else { + ui.label(text(Type::Label, tr!("Waiting"))); + } + ui.label(text(Type::Path, file.as_str()).color(T.text_dim)); + }); + } +} + +/// The report: each format's outcome, and what its exporter left out, skipped or why it failed. +fn report_rows(ui: &mut egui::Ui, r: &Report) { + egui::ScrollArea::vertical().max_height(320.0).auto_shrink([false, true]).show(ui, |ui| { + for o in &r.outcomes { + ui.horizontal(|ui| { + ui.set_min_height(TARGET); + name_cell(ui, label(o.format)); + let (s, c) = status_text(o.status); + ui.label(text(Type::Label, s).color(c)); + let files: Vec = o.files.iter().filter_map(|f| f.file_name()).map(|n| n.to_string_lossy().into_owned()).collect(); + if !files.is_empty() { + ui.label(text(Type::Path, files.join(", ")).color(T.text_dim)); + } + }); + if !o.message.is_empty() { + // The exporter's English, translated when a catalog has it. + ui.horizontal(|ui| { + ui.add_space(128.0); + ui.add(egui::Label::new(text(Type::Caption, sentence(&crate::i18n::t_dyn(&o.message)))).wrap()); + }); + } + } + }); + if let Some(dir) = r.files().first().and_then(|f| f.parent()).filter(|d| !d.as_os_str().is_empty()) { + ui.label(text(Type::Caption, tr!("In {folder}", folder = dir.display().to_string()))); + } +} From fb3d7597a0e86b288747bb38a47fe6ded0dc5035 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 15:21:26 -0700 Subject: [PATCH 047/192] test(engine): published ZIP read back by the hardened reader; reuse its CRC-32 (M8) --- crates/engine/src/publish.rs | 34 +++++------------------------- crates/engine/src/publish_tests.rs | 12 ++++++----- 2 files changed, 12 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/publish.rs b/crates/engine/src/publish.rs index 2ff78c45..857f232b 100644 --- a/crates/engine/src/publish.rs +++ b/crates/engine/src/publish.rs @@ -304,7 +304,7 @@ pub fn existing(s: &Session, steps: &[Step]) -> Vec { } /// The formats `file.publish` params name, if they name any. -fn only(p: &Value) -> Result>> { +pub fn formats_param(p: &Value) -> Result>> { match p.get("formats") { None | Some(Value::Null) => Ok(None), Some(Value::Array(list)) => list @@ -319,7 +319,7 @@ fn only(p: &Value) -> Result>> { /// The plan `file.publish` with `p` would run, for the confirmation (ADR 0004). pub(crate) fn planned(s: &Session, p: &Value) -> Option> { - plan(&s.doc, s.path.as_deref(), only(p).ok()?.as_deref()).ok() + plan(&s.doc, s.path.as_deref(), formats_param(p).ok()?.as_deref()).ok() } // ----- running --------------------------------------------------------------------------------- @@ -503,7 +503,7 @@ impl Publisher { } fn publish_cmd(s: &mut Session, p: &Value) -> Result { - let steps = plan(&s.doc, s.path.as_deref(), only(p)?.as_deref()).map_err(EngineError::State)?; + let steps = plan(&s.doc, s.path.as_deref(), formats_param(p)?.as_deref()).map_err(EngineError::State)?; if steps.is_empty() { return Err(EngineError::State("no format is on in Publish Settings: turn one on first".into())); } @@ -718,7 +718,7 @@ fn settings_set(s: &mut Session, p: &Value) -> Result { Ok(settings_json(&s.doc, s.path.as_deref())) } -/// Writes `files` (path, bytes) as one uncompressed ZIP archive (what the browser downloads +/// Writes `files` (path, bytes) as one uncompressed ZIP archive, per PKWARE's APPNOTE (what the browser downloads /// when Publish writes more than one file). Paths keep their folders, with `/` between them. pub fn zip(files: &[(PathBuf, Vec)]) -> std::result::Result, String> { let mut out: Vec = Vec::new(); @@ -731,7 +731,7 @@ pub fn zip(files: &[(PathBuf, Vec)]) -> std::result::Result, String> let name_len = u16::try_from(name.len()).map_err(|_| "a file name is too long".to_string())?; let size = u32::try_from(data.len()).map_err(|_| format!("{name} is too large for a ZIP archive (4 GB)"))?; let offset = u32::try_from(out.len()).map_err(|_| "the archive is too large (4 GB)".to_string())?; - let crc = crc32(data); + let crc = anicraft_xfl::zip::crc32(data); // Local file header: version 2.0, UTF-8 names (bit 11), stored. le32(&mut out, 0x0403_4b50); for x in [20u16, 0x0800, 0, 0, 0x21] { @@ -772,30 +772,6 @@ pub fn zip(files: &[(PathBuf, Vec)]) -> std::result::Result, String> Ok(out) } -/// CRC-32 (IEEE 802.3, reflected, as ZIP uses), a byte at a time from a table. -fn crc32(data: &[u8]) -> u32 { - const TABLE: [u32; 256] = { - let mut t = [0u32; 256]; - let mut i = 0; - while i < 256 { - let mut c = i as u32; - let mut k = 0; - while k < 8 { - c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; - k += 1; - } - t[i] = c; - i += 1; - } - t - }; - let mut c = !0u32; - for &b in data { - c = TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8); - } - !c -} - #[cfg(test)] #[path = "publish_tests.rs"] mod tests; diff --git a/crates/engine/src/publish_tests.rs b/crates/engine/src/publish_tests.rs index e8522153..c30ac16b 100644 --- a/crates/engine/src/publish_tests.rs +++ b/crates/engine/src/publish_tests.rs @@ -283,6 +283,13 @@ fn in_a_browser_every_file_comes_back_and_several_make_one_zip() { assert_eq!(&z[end..end + 4], &[0x50, 0x4b, 0x05, 0x06]); assert_eq!(u16::from_le_bytes([z[end + 10], z[end + 11]]), 3); assert!(z.windows(16).any(|w| w == b"img/Untitled.svg")); + // AniCraft's hardened ZIP reader (the .fla one) opens it, checks every CRC, and gets + // each file back exactly. + let archive = anicraft_xfl::zip::Archive::open(&z).unwrap(); + for (p, data) in &files { + let name = p.to_string_lossy().replace('\\', "/"); + assert_eq!(archive.read(&name).unwrap().as_ref(), Some(data), "{name}"); + } let total: usize = files.iter().map(|(_, d)| d.len()).sum(); assert!(z.len() > total && z.len() < total + 400, "stored, not compressed: {} for {total}", z.len()); }) @@ -290,11 +297,6 @@ fn in_a_browser_every_file_comes_back_and_several_make_one_zip() { .unwrap(); } -#[test] -fn crc32_matches_the_standard_check_value() { - assert_eq!(crc32(b"123456789"), 0xCBF4_3926); - assert_eq!(crc32(b""), 0); -} #[test] fn plugins_may_read_but_not_change_or_run_publishing() { From 670678a2113f1ac2d558aa543949cea784c455b3 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 15:23:50 -0700 Subject: [PATCH 048/192] docs: ADR 0060, roadmap, changelog and attribution for Publish Settings and Publish (M8) --- ATTRIBUTION.md | 1 + CHANGELOG.md | 23 +++ docs/adr/0060-publish-settings-and-publish.md | 133 ++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 6 +- 5 files changed, 160 insertions(+), 4 deletions(-) create mode 100644 docs/adr/0060-publish-settings-and-publish.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a10cf764..6f7a6ea5 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -99,6 +99,7 @@ OR Apache-2.0) is noted in the table. | Marching-squares contour tracing (Paint Bucket regions, Brush outlines) | `crates/geom/src/trace.rs` | Lorensen & Cline (1987); public algorithm | Ported from PhotoCraft's mask tracer (same project family and licence) and reviewed. | | Chamfer distance transform (3-4) and flood fill | `crates/engine/src/cmds_paint.rs` | G. Borgefors, *Distance transformations in digital images* (1986); public algorithms | Gap closing, and growing fills under their outlines. | | ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs`, `crates/xfl/tests/support/fla.rs` | PKWARE APPNOTE.TXT 6.3 (published ZIP specification), the Info-ZIP Unicode path extra field (0x7075, Info-ZIP `proginfo/extrafld.txt`); CRC-32 by slicing by 8 (M. Kounavis and F. Berry, "A Systematic Approach to Building High Performance Software-based CRC Generators", IEEE ISCC 2005); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries, ZIP64, data descriptors, CP437 and UTF-8 names; no encryption (ADR 0054). | +| ZIP archive writing (web Publish) | `crates/engine/src/publish.rs` (`zip`) | PKWARE APPNOTE.TXT 6.3; the CRC-32 above | Stored entries with UTF-8 names, read back by the reader above in the tests (ADR 0060). | | JPEG decoding (imported images) | `crates/engine/src/cmds_file.rs` | `zune-jpeg` (MIT OR Apache-2.0 OR Zlib), already in the dependency tree | Decoded to RGBA, kept as PNG. | | XFL document structure and shape edges | `crates/xfl/src/` | The publicly documented XFL package structure (`DOMDocument.xml`, `LIBRARY/*.xml`, edge strings) | Clean room: no Animate or third-party converter code (ADR 0009). | | Full SVG path data and elliptical-arc to Bézier conversion | `crates/geom/src/svg.rs` | W3C SVG 1.1 §8.3 and Appendix F.6 (implementation notes) | W3C Royalty-Free Patent Policy. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 59ef9bf0..72202428 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,29 @@ ## Unreleased +* **Publish Settings and Publish** (ADR 0060, M8). + * **File › Publish Settings** (Ctrl+Shift+F12) is a window that stays open while you work. + It lists every format AniCraft exports (HTML canvas, animated GIF, video, Lottie, sprite + sheet, PNG sequence, PNG, SVG, audio), each with a checkbox. The selected format shows + its output name and the same options its File › Export command has. The settings are + saved **in the document** and every change can be undone. Older files open with the HTML + page on. + * Output names are relative to the document's folder, and `{name}` stands for the + document's name (`web/{name}.html`). Each name is checked as you type and the full path + is shown below it. A name can't point outside the document's folder, and two formats + can't write the same file. + * **File › Publish** (Shift+F12) writes every format that is on, in the background. A + window shows each format's progress and has a Cancel button. A single report then lists + what each format wrote, skipped (video in a browser, audio with no sounds), left out + (Lottie's and the HTML page's notes) or why it failed. One failing format doesn't stop + the others. + * Publishing over files that are already there asks once. After that, the files this + session published are replaced without asking. + * **Presets**: save the settings under a name, apply them to any document, or delete them. + Presets are kept in your preferences. + * In a browser, the files go to your downloads, as one ZIP when there are several. + * Headless: `publish.settings_get`, `publish.settings_set` and `file.publish`, which returns + the report. Publishing the sample in six formats takes 0.64 s. * **Find and Replace, and the Movie Explorer** (ADR 0058, M8). * **Edit › Find and Replace** (Ctrl+F) is a window that stays open while you work. It finds text in text fields, frame labels, layer names, instance names and frame scripts, with diff --git a/docs/adr/0060-publish-settings-and-publish.md b/docs/adr/0060-publish-settings-and-publish.md new file mode 100644 index 00000000..6910405d --- /dev/null +++ b/docs/adr/0060-publish-settings-and-publish.md @@ -0,0 +1,133 @@ +# ADR 0060: Publish Settings and Publish + +* Status: accepted (2026-11-11) +* Relates to: ADR 0003 (file format), ADR 0004 (destructive actions), ADR 0017 (plug-in + policy), ADR 0028 (HTML canvas export), ADR 0036 (web build), ADR 0040 (interface languages) + +## Context + +AniCraft can export a PNG frame or sequence, an animated GIF, an SVG frame, a sprite sheet and +its JSON map, video through the user's ffmpeg, Lottie, an HTML canvas page and the soundtrack, +each as its own command with its own prompt. Animate collects these in **File › Publish +Settings** (Ctrl+Shift+F12): you tick formats, set each one's options and output name, and +the settings are saved **in the document**. **File › Publish** (Shift+F12) then writes every +ticked format at once. Profiles can be saved and reused. Artists publish many times a day, so +publishing has to be one key, not a run of dialogs, and must not freeze the editor while a +long video renders. + +Behaviour was learned from Adobe's public help pages and from using the feature. No Adobe +code, SDK or asset was used. + +## Decision + +1. **The profile is part of the document** (`anicraft_doc::publish::PublishProfile`, the + document's `publish` field). Every format is always there, in a fixed order (HTML canvas, + GIF, video, Lottie, sprite sheet, PNG sequence, PNG, SVG, audio), and each one is on or off. + Each has an output template and a **typed** settings struct holding the same options its + export command takes: frame range, scale, loop, background, columns, padding, title, + sound, fit, sample rate, bits. Typed settings let the file format check the values + (`sanitize` brings anything a file holds into range). A free-form JSON blob would let + values drift away from what the exporters accept. + * `#[serde(default)]` everywhere. A file from before this ADR, or one missing some fields, + opens with the defaults: **the HTML page is on and the rest are off**, matching Animate + for an HTML5 Canvas document. A profile still at its defaults is not written, so the + files of people who never open Publish Settings don't change. The file format version + stays at 3. + * Changing the settings changes the document: it is undoable and marks the file unsaved, + as in Animate. Drags and typing are grouped into one undo step. + * The ffmpeg path is not in the profile. It belongs to the computer (the `ffmpeg` param, + `ANICRAFT_FFMPEG`, or the PATH), not to the document. +2. **Outputs are relative to the document's folder.** `{name}` is the document's file name + without its extension, and is the only placeholder. An output can go into subfolders + (`web/{name}.html`), which are created as needed. It **can't be absolute, contain `..`, or + name a drive**. A document opened from someone else must never be able to write elsewhere + on this computer. Users who want files elsewhere can save the document there, which keeps + publishing predictable. If an output has no extension, the format's extension is added. A + wrong extension is an error (for example `.png` for the GIF). If two formats would write + the same file (compared case-insensitively, as Windows and macOS do), the plan is refused + and the message names both formats. An untitled document can't publish on the desktop: + the shell asks for Save As first. In the browser, files go to the downloads, so an + untitled document publishes as "Untitled". +3. **Publishing reuses the export commands.** `engine::publish::plan` turns each format that + is on into a `Step`: the export command id and its params. `Publisher` then runs the steps + in order on a **session of its own**, built from a copy of the document taken when Publish + started, through the same `RunFn` that File › Export uses. Nothing about an export is + implemented twice, and later edits never change a publish already running. If one format + fails (no ffmpeg, a GIF that would be too large), the others still publish. Some formats + are **skipped with a reason**: video in a browser (no ffmpeg), and audio when the movie + has no sounds. +4. **Cancel and progress** go through a shared `publish::Control` (an atomic cancel flag and + a frames-done/frames-total counter) set on the session (`Session::job`). The frame-based + exporters (GIF, sprite sheet, PNG sequence, video) call `publish::tick` after each frame + or batch. When the run is cancelled they stop with `EngineError::Cancelled`: + * GIF and sprite sheet write nothing, because their file is written only at the end. + * Video kills ffmpeg and deletes its unfinished file. + * The PNG sequence keeps the frames it has written, and the report says so. + * Formats that haven't started don't run. + * HTML, Lottie, SVG, PNG and audio are quick single passes and finish the one they are + on. Outside a publish, `job` is `None` and the exporters behave exactly as before. +5. **One report.** Each format gets an `Outcome`: published, skipped, failed or cancelled, + plus its files and a message (the exporter's "approximated or left out" note for HTML and + Lottie, or why it was skipped or failed). `Report::summary` joins these into one sentence + per format, in order. `file.publish` returns the whole report as JSON. The shell shows it + in a window, one row per format. +6. **Commands**, so all of this works headless, over the CLI and over MCP: + * `publish.settings_get` (File › Publish Settings…, Ctrl+Shift+F12; the shell opens the + window) returns the profile and, for each format, where it would go now. + * `publish.settings_set` changes one `format` (switch, output, options; unknown options + and out-of-range values are refused, with nothing changed) or sets a whole `profile`. + * `file.publish {formats?, confirm?}` (Shift+F12) runs the publish on the caller's thread + and returns the report. The CLI and MCP wait for it, which is what a script wants. +7. **Overwriting follows ADR 0004.** Replacing files on disk can't be undone, so + `file.publish` needs confirmation when outputs already exist (for a PNG sequence, a folder + that already holds exported frames). The single confirmation lists the files. To keep + publishing a one-key action, **files this session's own publishes wrote are replaced + without asking again** (`Session::published`, which is not stored in the document). So the + first Publish over existing files in a session asks once, and the next ones don't. The + desktop export commands keep their own confirmations, but Publish's confirmation covers + them (its steps carry `confirm`). +8. **The desktop runs a publish on a worker thread**, `anicraft-publish`. The UI only reads a + channel and the atomic counters each frame, so the editor never waits. The **Publish** + window shows each format as waiting, running (a frame progress bar, or a spinner for + formats without a frame count) or done, with a **Cancel** button. Closing the window also + cancels. When the run finishes, the window becomes the report. **The web build** has no + threads, so the same `Publisher` runs one format per frame on the UI thread, and the + window still shows which format is running. The files come back as downloads, and + **several files come back as one ZIP** (`publish::zip`: stored entries, UTF-8 names, + folders kept, CRC-32 from the hardened `.fla` reader's module; the tests read every + archive back with that reader). If the thread can't be started, the desktop falls back to + the same stepping. +9. **Presets belong to the user, not the document.** They are kept in Preferences + (`publish_presets`, a name → profile map, at most 100 presets, names up to 64 + characters, each one sanitized on load). Publish Settings can apply one (one undo step on + the document), save the current settings as one (replacing a preset of the same name), or + delete one. A preset is gone for good once deleted, so Delete takes two clicks in place + (Delete, then "Delete “name”") rather than opening a modal dialog. Headless users already + have presets as data: `publish.settings_get`'s profile can go into another document's + `publish.settings_set {profile}`. +10. **Plug-ins** may read the settings (`publish.settings_get`) but not change them, and + can't publish. `file.*` is already refused, and `publish.settings_set` would change what + a later Publish writes and where. + +## Consequences + +* One new document field, which defaults for older files, and no change to the file format + version. +* Publishing is one key after the first setup. It never blocks the editor, and what it does + is reported once. +* A publish uses the document as it was when Publish started. Edits made while it runs go + into the next publish. +* Only `{name}` is supported as a placeholder, and outputs stay below the document's folder. + Both can be loosened later without changing the file format. Loosening them would need a + new rule for files from other people. + +## Not yet + +* Importing Animate's own publish settings (`PublishSettings.xml` in XFL). +* More placeholders (`{scene}`, `{date}`), outputs outside the document's folder, and a + per-format "open when done". +* Progress for HTML, Lottie and audio, and cancel inside those formats (they are single + passes). +* Exporting and importing presets as files (headless, the profile JSON already does this). +* Publishing in a browser that keeps running while the tab is in the background (one format + per frame stops when the browser stops drawing the page). diff --git a/docs/adr/README.md b/docs/adr/README.md index 8f01bf2e..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0060 | m8/publish-settings | Publish Settings and Publish | diff --git a/docs/roadmap.md b/docs/roadmap.md index 49a95444..c01562a4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,7 +16,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported. Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | @@ -40,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | -| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); documentation book. | +| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. | ## Releases @@ -61,7 +61,7 @@ titled with its milestone. | M5 | Audio layers: import, waveform, playback sync | timeline, layers | | M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | -| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | +| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and ActionScript (on M6's plug-in host). From c90ce112bb77c3512c9ec711c6092dad126b9840 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 15:42:58 -0700 Subject: [PATCH 049/192] test(shell): Publish on the worker and here, cancel, presets, every format's options drawn (M8) --- src/publish_panel.rs | 135 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) diff --git a/src/publish_panel.rs b/src/publish_panel.rs index 48a76f1e..ebb86db3 100644 --- a/src/publish_panel.rs +++ b/src/publish_panel.rs @@ -781,3 +781,138 @@ fn report_rows(ui: &mut egui::Ui, r: &Report) { ui.label(text(Type::Caption, tr!("In {folder}", folder = dir.display().to_string()))); } } + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::sample; + + fn app(name: &str) -> (App, egui::Context, std::path::PathBuf) { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + let dir = std::env::temp_dir().join(format!("anicraft-publish-ui-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + app.run("file.save", json!({"path": dir.join("walk.anicraft").display().to_string()})); + (app, ctx, dir) + } + + /// Draws the windows and moves the publish along until it is done (or `frames` run out). + fn frames(app: &mut App, ctx: &egui::Context, n: usize) { + for _ in 0..n { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, &ui.ctx().clone())); + out.textures_delta.clear(); + if !app.publish.running() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + + #[test] + fn publish_runs_on_a_worker_and_reports_once() { + let (mut app, ctx, dir) = app("worker"); + app.run("publish.settings_set", json!({"format": "gif", "enabled": true, "scale": 0.1, "to": 5})); + app.run("publish.settings_set", json!({"format": "audio", "enabled": true})); + app.publish.open = true; + app.request("file.publish", json!({})); + assert!(app.publish.running(), "it starts in the background"); + app.request("file.publish", json!({})); + frames(&mut app, &ctx, 2000); + assert!(!app.publish.running()); + let r = app.publish.report.clone().expect("a report"); + assert_eq!((r.count(Status::Published), r.count(Status::Skipped)), (2, 1)); + assert!(dir.join("walk.gif").is_file() && dir.join("walk.html").is_file()); + assert!(app.s.published.contains(&dir.join("walk.gif")), "the session knows what it published"); + // Published again: no question, this session wrote them. + assert!(app.s.confirmation("file.publish", &json!({})).is_none()); + frames(&mut app, &ctx, 1); + open_settings_from_report(&mut app); + assert!(app.publish.open); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn cancel_stops_the_worker() { + let (mut app, ctx, dir) = app("cancel"); + app.run("publish.settings_set", json!({"format": "png_sequence", "enabled": true, "scale": 0.2})); + app.run("publish.settings_set", json!({"format": "svg", "enabled": true})); + start(&mut app, &json!({})); + cancel(&mut app); + frames(&mut app, &ctx, 2000); + let r = app.publish.report.clone().expect("a report"); + assert!(r.count(Status::Cancelled) >= 1, "{:?}", r.to_json()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn publishing_here_steps_one_format_per_frame() { + let (mut app, ctx, dir) = app("here"); + app.run("publish.settings_set", json!({"format": "svg", "enabled": true})); + begin(&mut app, &json!({}), false); + let mut seen_running = false; + for _ in 0..20 { + seen_running |= app.publish.job.as_ref().is_some_and(|j| j.running.is_some()); + frames(&mut app, &ctx, 1); + } + assert!(seen_running && !app.publish.running()); + assert_eq!(app.publish.report.as_ref().map(|r| r.count(Status::Published)), Some(2)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn what_publish_cant_run_says_why() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + start(&mut app, &json!({})); + assert!(!app.publish.running(), "untitled: saves first"); + start(&mut app, &json!({"formats": 5})); + assert!(!app.publish.running()); + let (mut app, _, dir) = self::app("none"); + app.run("publish.settings_set", json!({"format": "html", "enabled": false})); + start(&mut app, &json!({})); + assert!(!app.publish.running() && app.publish.open, "nothing on: the settings open"); + app.run("publish.settings_set", json!({"format": "sprite_sheet", "enabled": true})); + app.run("publish.settings_set", json!({"format": "png", "enabled": true, "output": "{name}_sheet.png"})); + start(&mut app, &json!({})); + assert!(!app.publish.running(), "two formats on one file"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn presets_save_apply_and_delete() { + let (mut app, ctx, dir) = app("presets"); + app.run("publish.settings_set", json!({"format": "gif", "enabled": true, "scale": 0.5})); + app.publish.preset_name = " Small GIF ".into(); + save_preset(&mut app); + assert!(app.prefs.publish_presets.get("Small GIF").is_some_and(|p| p.gif.enabled && p.gif.scale == 0.5)); + app.publish.preset_name = "Small GIF".into(); + save_preset(&mut app); + assert_eq!(app.prefs.publish_presets.len(), 1, "the same name replaces it"); + app.publish.preset_name = " ".into(); + save_preset(&mut app); + assert_eq!(app.prefs.publish_presets.len(), 1); + for i in 0..crate::prefs::MAX_PUBLISH_PRESETS { + app.prefs.publish_presets.insert(format!("p{i}"), PublishProfile::default()); + } + app.publish.preset_name = "one too many".into(); + save_preset(&mut app); + assert!(!app.prefs.publish_presets.contains_key("one too many")); + delete_preset(&mut app, "Small GIF"); + assert!(!app.prefs.publish_presets.contains_key("Small GIF") && app.publish.preset.is_none()); + // Every format's options draw. + app.publish.open = true; + for f in PublishFormat::ALL { + app.publish.selected = f; + app.publish.output_edit = Some((f, "../nope".into())); + frames(&mut app, &ctx, 1); + } + app.publish.preset = Some("p1".into()); + app.publish.confirm_delete = true; + frames(&mut app, &ctx, 1); + assert_eq!(sentence("the movie has no sounds"), "The movie has no sounds."); + assert_eq!(sentence(""), ""); + let _ = std::fs::remove_dir_all(&dir); + } +} From 00e848cc71ed239d459ff638fc432293958e0628 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 16:04:30 -0700 Subject: [PATCH 050/192] fix(test): Find's test library symbols set scale_grid_kept (M5) --- crates/engine/src/find_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/find_tests.rs b/crates/engine/src/find_tests.rs index c603f6c4..efa675f3 100644 --- a/crates/engine/src/find_tests.rs +++ b/crates/engine/src/find_tests.rs @@ -78,7 +78,7 @@ impl Build { } pub fn symbol(&mut self, name: &str, kind: SymbolKind) -> SymbolId { let id = SymbolId(self.id()); - self.doc.library.push(Arc::new(Symbol { id, name: name.into(), kind, linkage: None, scale_grid: None, timeline: Timeline::default() })); + self.doc.library.push(Arc::new(Symbol { id, name: name.into(), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline::default() })); id } pub fn fill(&mut self, id: SymbolId, layers: Vec) { From ba16bf5817257f3f8eb45230fb4c7a0a6fa863ea Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 16:23:46 -0700 Subject: [PATCH 051/192] docs(adr): reserve ADR 0061 for timeline polish (M1) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..4806482d 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0061 | m1/timeline-polish (M1) | Timeline polish: per-layer onion, outline mode, layer height, Layer Properties, frame view | From cbc07f8fa656e12e686520c4182d3952d12e4159 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 16:31:16 -0700 Subject: [PATCH 052/192] feat(engine): per-layer onion, layer colour and height, Layer Properties, outlines on the stage only, parent onion in symbols (M1) --- crates/doc/src/eval.rs | 11 +- crates/doc/src/lib.rs | 30 +++ crates/engine/src/cmds_layer.rs | 161 +++++++++++++++ crates/engine/src/cmds_layer_tests.rs | 277 ++++++++++++++++++++++++++ crates/engine/src/cmds_plugin.rs | 2 +- crates/engine/src/cmds_timeline.rs | 4 +- crates/engine/src/editing.rs | 25 ++- crates/engine/src/lib.rs | 2 + crates/engine/src/onion.rs | 13 +- crates/engine/src/render_service.rs | 44 +++- crates/xfl/src/import.rs | 2 + crates/xfl/src/tests.rs | 3 +- 12 files changed, 557 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/cmds_layer.rs create mode 100644 crates/engine/src/cmds_layer_tests.rs diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 96ce1679..c1b35195 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -178,6 +178,7 @@ pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Aff let mut out = DisplayList::default(); let mut cx = Ctx::top(xf); cx.depth = 1; + cx.stage = false; eval_timeline(doc, tl, frame, &cx, &mut out, play); out } @@ -300,6 +301,9 @@ struct Ctx { /// The top-level layer and element everything inside belongs to (for picking). root: Option<(LayerId, ElementId)>, outline: Option, + /// The stage as edited (ADR 0061): layers in outline mode are drawn as outlines. Off for + /// the movie (every export, the player): View as Outlines is an editing aid. + stage: bool, /// The clip everything inside is drawn within. clip: Option, /// Set while evaluating mask artwork: everything inside forms this clip. @@ -318,12 +322,13 @@ struct Ctx { impl Ctx { fn top(xf: Affine) -> Ctx { - Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } + Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } } /// A main timeline seen through `camera`: its tint colours everything. fn through(camera: Option) -> Ctx { let mut cx = Ctx::top(Affine::IDENTITY); + cx.stage = false; if let Some(c) = camera { cx.color = c.color(); cx.camera = Some(c); @@ -418,7 +423,7 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut // A layer guided by a guide layer: its tweens follow the guide's first path. let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame)); let Some((kf_start, elements)) = evaluate_guided(layer, frame, walk.as_ref()) else { continue }; - let layer_outline = cx.outline.or(if layer.outline { Some(layer.color) } else { None }); + let layer_outline = cx.outline.or(if layer.outline && cx.stage { Some(layer.color) } else { None }); // Through a camera, each layer is placed by the camera and its own depth. let layer_xf = cx.camera.map_or(cx.xf, |c| c.view(&doc.stage, layer.depth)); for el in elements.iter() { @@ -523,7 +528,7 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut }; // A symbol with 9-slice guides, scaled: its shapes are sliced (ADR 0055). let slice = crate::nine_slice::slicing(doc, sym, &el.transform).map(|s| Slicing { post: layer_xf.mul(&s.post), ..s }); - let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, clip, masks, guide, group, camera: None, slice }; + let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, stage: cx.stage, clip, masks, guide, group, camera: None, slice }; eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref()); } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index f877eb6b..60315027 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -645,10 +645,20 @@ pub struct Layer { pub visible: bool, #[serde(default)] pub locked: bool, + /// View as Outlines (ADR 0061): the stage draws the layer's artwork as hairlines in + /// [`Layer::color`]. Never in the movie or an export. #[serde(default)] pub outline: bool, #[serde(default = "default_layer_color")] pub color: Rgba, + /// Onion skin draws this layer's frames around the playhead (ADR 0061); off, only its + /// playhead frame shows. + #[serde(default = "yes", skip_serializing_if = "is_true")] + pub onion: bool, + /// Row height on the timeline as a multiple of a normal row (ADR 0061): 1, 2 or 3 (100, + /// 200 or 300 %), as Animate's Layer Properties offer. Read through [`Layer::height`]. + #[serde(default = "one", skip_serializing_if = "is_one", rename = "height")] + pub height_rows: u8, #[serde(default)] pub keyframes: Vec>, /// Layer depth (ADR 0027), pixels behind the stage (negative: in front): the camera's pans @@ -675,6 +685,18 @@ fn full() -> f32 { fn is_full(v: &f32) -> bool { *v == 1.0 } +fn is_true(v: &bool) -> bool { + *v +} +fn one() -> u8 { + 1 +} +fn is_one(v: &u8) -> bool { + *v == 1 +} + +/// Tallest a layer's timeline row gets, in normal rows (300 %). +pub const MAX_LAYER_HEIGHT: u8 = 3; impl PartialEq for Layer { fn eq(&self, o: &Layer) -> bool { @@ -686,6 +708,8 @@ impl PartialEq for Layer { && self.locked == o.locked && self.outline == o.outline && self.color == o.color + && self.onion == o.onion + && self.height_rows == o.height_rows && self.depth.to_bits() == o.depth.to_bits() && self.volume.to_bits() == o.volume.to_bits() && self.muted == o.muted @@ -715,6 +739,8 @@ impl Layer { locked: false, outline: false, color: default_layer_color(), + onion: true, + height_rows: 1, keyframes: vec![Arc::new(Keyframe::new(0, 1))], depth: 0.0, volume: 1.0, @@ -722,6 +748,10 @@ impl Layer { armature: None, } } + /// The row height in normal rows, `1..=MAX_LAYER_HEIGHT` whatever a file says. + pub fn height(&self) -> u8 { + self.height_rows.clamp(1, MAX_LAYER_HEIGHT) + } /// The gain this layer gives its sounds: its volume, or silence when muted. pub fn sound_gain(&self) -> f32 { if self.muted { diff --git a/crates/engine/src/cmds_layer.rs b/crates/engine/src/cmds_layer.rs new file mode 100644 index 00000000..3289e0a6 --- /dev/null +++ b/crates/engine/src/cmds_layer.rs @@ -0,0 +1,161 @@ +//! Layer view properties saved in the document (ADR 0061): each layer's onion skin toggle, its +//! colour (outlines and the timeline bar), View as Outlines, its row height, and Layer +//! Properties, which sets several of them (and the name, type, show and lock) as one step. +//! +//! Behaviour learned from Adobe's public help pages on layers and onion skinning and from +//! watching the program; nothing was copied. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Layer, LayerId, LayerKind, MAX_LAYER_HEIGHT}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "layer.set_onion", + "Onion Skin Layer", + "", + None, + "{onion?: bool (default: the other way), solo?: bool, layer?} whether onion skin draws the layer's frames around the playhead. solo: only this layer is onion-skinned (every other layer off); solo again on the only layer on turns them all back on (Alt-click)", + true, + set_onion as crate::RunFn, + ), + c("layer.set_color", "Layer Colour", "", None, "{color: \"#rrggbb\", layer?} the layer's colour: its outlines in outline mode and its bar on the timeline", true, set_color), + c("layer.set_height", "Layer Height", "", None, "{height: 100 | 200 | 300 (percent of a normal row), layer?} the layer's row height on the timeline", true, set_height), + c( + "layer.set_properties", + "Layer Properties", + "Modify/Timeline", + None, + "{layer?, name?, type?: normal|mask|masked|guide|guided, color?, outline?: bool (view as outlines), height?: 100|200|300, visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties", + true, + set_properties, + ), + c("layer.properties", "Get Layer Properties", "", None, "{layer?} the layer's name, type, colour, outline, height (percent), visible, locked and onion", false, |s, p| properties(s, layer_id(s, p)?)), + ] +} + +fn layer_id(s: &Session, p: &Value) -> Result { + let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); + s.timeline().layer(id).map(|_| id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) +} + +/// Whether a layer of this kind has frames onion skin can show (folders and the camera don't). +fn onion_able(l: &Layer) -> bool { + !matches!(l.kind, LayerKind::Folder | LayerKind::Camera) +} + +fn set_onion(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + let solo = opt_bool(p, "solo")?.unwrap_or(false); + let on = opt_bool(p, "onion")?; + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + if solo { + // Animate's Alt-click: this layer alone; again on the only one left on, every layer. + let alone = tl.layers.iter().filter(|l| onion_able(l)).all(|l| l.onion == (l.id == id)); + for l in tl.layers.iter_mut().filter(|l| onion_able(l)) { + let want = alone || l.id == id; + if l.onion != want { + Arc::make_mut(l).onion = want; + } + } + } else { + let l = tl.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + l.onion = on.unwrap_or(!l.onion); + } + let on: Vec = tl.layers.iter().filter(|l| onion_able(l) && l.onion).map(|l| l.id.0).collect(); + let onion = tl.layer(id).is_some_and(|l| l.onion); + Ok(json!({"layer": id.0, "onion": onion, "onion_layers": on})) +} + +fn set_color(s: &mut Session, p: &Value) -> Result { + let color = opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' (like \"#ff8800\") is required".into()))?; + let lid = opt_u64(p, "layer")?.map(LayerId); + let l = s.layer_mut(lid)?; + // A layer colour is opaque: it draws hairlines and a bar. + l.color = color.with_alpha(1.0); + Ok(json!({"color": l.color.to_hex()})) +} + +/// `height` in percent (100, 200 or 300) as rows. +fn height_param(p: &Value) -> Result> { + match opt_u32(p, "height")? { + None => Ok(None), + Some(h) if h > 0 && h % 100 == 0 && h / 100 <= u32::from(MAX_LAYER_HEIGHT) => Ok(u8::try_from(h / 100).ok()), + Some(_) => Err(EngineError::Param("param 'height' must be 100, 200 or 300 (percent)".into())), + } +} + +fn set_height(s: &mut Session, p: &Value) -> Result { + let rows = height_param(p)?.ok_or_else(|| EngineError::Param("param 'height' (100, 200 or 300) is required".into()))?; + let lid = opt_u64(p, "layer")?.map(LayerId); + let l = s.layer_mut(lid)?; + l.height_rows = rows; + Ok(json!({"height": u32::from(l.height()) * 100})) +} + +fn set_properties(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + // Every param is read (and checked) before anything changes. + let name: Option = opt_str(p, "name")?.map(|n| n.chars().take(128).collect()); + if name.as_ref().is_some_and(|n| n.trim().is_empty()) { + return Err(EngineError::Param("layer name must not be empty".into())); + } + let ty = opt_str(p, "type")?; + let color = opt_color(p, "color")?; + let outline = opt_bool(p, "outline")?; + let height = height_param(p)?; + let (visible, locked, onion) = (opt_bool(p, "visible")?, opt_bool(p, "locked")?, opt_bool(p, "onion")?); + if let Some(ty) = ty { + let now = crate::cmds_timeline::layer_type_json(s, id); + if now.get("type").and_then(Value::as_str) != Some(ty) { + crate::cmds_timeline::set_type(s, id, ty)?; + } + } + let l = s.layer_mut(Some(id))?; + if let Some(n) = name { + l.name = n; + } + if let Some(c) = color { + l.color = c.with_alpha(1.0); + } + if let Some(o) = outline { + l.outline = o; + } + if let Some(h) = height { + l.height_rows = h; + } + if let Some(v) = visible { + l.visible = v; + } + if let Some(v) = locked { + l.locked = v; + } + if let Some(v) = onion { + l.onion = v; + } + properties(s, id) +} + +fn properties(s: &Session, id: LayerId) -> Result { + let l = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let ty = crate::cmds_timeline::layer_type_json(s, id).get("type").cloned().unwrap_or(Value::Null); + Ok(json!({ + "layer": id.0, + "name": l.name, + "type": ty, + "color": l.color.to_hex(), + "outline": l.outline, + "height": u32::from(l.height()) * 100, + "visible": l.visible, + "locked": l.locked, + "onion": l.onion, + })) +} + +#[cfg(test)] +#[path = "cmds_layer_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmds_layer_tests.rs b/crates/engine/src/cmds_layer_tests.rs new file mode 100644 index 00000000..b7af3b2a --- /dev/null +++ b/crates/engine/src/cmds_layer_tests.rs @@ -0,0 +1,277 @@ +//! Layer view properties (ADR 0061): onion toggles and solo, colour, View as Outlines (on the +//! stage only), row height, Layer Properties as one step, the file, and onion skin of the +//! timeline around a symbol open in place. + +use crate::Session; +use crate::onion::{Markers, OnionSkin}; +use anicraft_doc::{ElementId, LayerId, Rgba}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn rect(s: &mut Session, x: f32) -> ElementId { + ElementId(run(s, "draw.rect", json!({"x": x, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()) +} + +/// Two layers, each a square that moves 40 px right on frames 0, 2 and 4: `top` starts at x 0, +/// `bottom` at x 200. The playhead is on frame 2. +fn two_walks() -> (Session, LayerId, LayerId) { + let mut s = Session::default(); + let bottom = s.layer; + let b = rect(&mut s, 200.0); + let top = LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let t = rect(&mut s, 0.0); + for f in [2, 4] { + run(&mut s, "timeline.goto", json!({"frame": f})); + for (l, e) in [(bottom, b), (top, t)] { + run(&mut s, "layer.select", json!({"layer": l.0})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [e.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + } + run(&mut s, "timeline.goto", json!({"frame": 2})); + (s, top, bottom) +} + +fn layer(s: &Session, id: LayerId) -> &anicraft_doc::Layer { + s.timeline().layer(id).unwrap() +} + +/// What the stage shows with `skin`: the layers and left edges of the onion frames (tinted items). +fn ghosts(s: &Session, skin: &OnionSkin) -> Vec<(LayerId, f32)> { + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(skin)); + dl.items.iter().filter(|i| !i.color.is_identity()).map(|i| (i.layer, i.path.bounds().transformed(&i.transform).min.x)).collect() +} + +#[test] +fn a_layer_with_onion_off_is_not_onion_skinned() { + let (mut s, top, bottom) = two_walks(); + let skin = OnionSkin { keyframes_only: true, ..OnionSkin::default() }; + let mut both = ghosts(&s, &skin); + both.sort_by(|a, b| a.1.total_cmp(&b.1)); + assert_eq!(both, vec![(top, 0.0), (top, 80.0), (bottom, 200.0), (bottom, 280.0)], "frames 0 and 4 on both layers"); + let r = run(&mut s, "layer.set_onion", json!({"layer": bottom.0})); + assert_eq!(r["onion"], false, "toggles"); + assert!(!layer(&s, bottom).onion && layer(&s, top).onion); + assert!(ghosts(&s, &skin).iter().all(|(l, _)| *l == top), "only the top layer's frames show"); + // Its playhead frame still shows, at full strength. + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(&skin)); + assert!(dl.items.iter().any(|i| i.layer == bottom && i.color.is_identity())); + // Edit Multiple Frames isn't onion skin: it still shows and edits the layer's keyframes. + let multi = OnionSkin { edit_multiple: true, ..skin }; + assert!(s.multi_frame_items(0, 4).iter().any(|(it, _)| it.layer == bottom && it.frame == 0)); + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(&multi)); + assert_eq!(dl.items.iter().filter(|i| i.layer == bottom).count(), 3); + // Undo brings it back. + run(&mut s, "edit.undo", json!({})); + assert!(layer(&s, bottom).onion); + assert!(s.execute("layer.set_onion", &json!({"layer": 999_999})).is_err()); + assert!(s.execute("layer.set_onion", &json!({"onion": "yes"})).is_err()); +} + +#[test] +fn solo_onion_keeps_one_layer_and_again_brings_back_all() { + let (mut s, top, bottom) = two_walks(); + let folder = LayerId(run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap()); + let r = run(&mut s, "layer.set_onion", json!({"layer": top.0, "solo": true})); + assert_eq!(r["onion_layers"], json!([top.0])); + assert!(layer(&s, top).onion && !layer(&s, bottom).onion); + assert!(layer(&s, folder).onion, "a folder has no frames to onion-skin; solo leaves it"); + // Solo on another layer moves the solo there. + run(&mut s, "layer.set_onion", json!({"layer": bottom.0, "solo": true})); + assert!(!layer(&s, top).onion && layer(&s, bottom).onion); + // Again on the only layer left on: every layer is on again. + run(&mut s, "layer.set_onion", json!({"layer": bottom.0, "solo": true})); + assert!(layer(&s, top).onion && layer(&s, bottom).onion); + // Setting it outright. + run(&mut s, "layer.set_onion", json!({"layer": top.0, "onion": false})); + run(&mut s, "layer.set_onion", json!({"layer": top.0, "onion": false})); + assert!(!layer(&s, top).onion); +} + +#[test] +fn outlines_use_the_layer_colour_on_the_stage_only() { + let mut s = Session::default(); + let l = s.layer; + rect(&mut s, 10.0); + run(&mut s, "layer.set_color", json!({"color": "#ff8800"})); + run(&mut s, "layer.toggle_outline", json!({})); + let orange = Rgba::hex(0xff8800); + assert_eq!(layer(&s, l).color, orange); + // The stage: hairlines in the layer's colour. + let stage = anicraft_doc::evaluate_scene(&s.doc, 0, 0); + assert!(stage.items.iter().all(|i| i.outline == Some(orange))); + assert!(s.display_list().items.iter().all(|i| i.outline == Some(orange))); + // The movie (every export), and the player, draw the artwork as it is. + let movie = anicraft_doc::evaluate(&s.doc, 0); + assert!(!movie.items.is_empty() && movie.items.iter().all(|i| i.outline.is_none())); + let player = anicraft_doc::evaluate_player(&s.doc, &anicraft_doc::player::PlayerState::default()); + assert!(player.items.iter().all(|i| i.outline.is_none())); + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + assert!(!svg.to_ascii_lowercase().contains("ff8800"), "no outline colour in an SVG export"); + let png = |s: &Session| { + let view = anicraft_render::View { transform: anicraft_geom::Affine::IDENTITY, width: 40, height: 40, background: Some(Rgba::WHITE) }; + anicraft_render::render(&anicraft_doc::evaluate(&s.doc, 0), &view).unwrap().0.to_rgba8() + }; + let outlined = png(&s); + run(&mut s, "layer.toggle_outline", json!({})); + assert_eq!(outlined, png(&s), "an export looks the same with or without outline mode"); + // Inside a symbol on an outlined layer, the stage outlines everything in the layer's colour. + run(&mut s, "layer.toggle_outline", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let stage = anicraft_doc::evaluate_scene(&s.doc, 0, 0); + assert!(!stage.items.is_empty() && stage.items.iter().all(|i| i.outline == Some(orange))); + assert!(anicraft_doc::evaluate(&s.doc, 0).items.iter().all(|i| i.outline.is_none())); + // A colour is opaque, and a bad one is refused. + run(&mut s, "layer.set_color", json!({"color": "#00ff0080"})); + assert_eq!(layer(&s, l).color.a, 1.0); + assert!(s.execute("layer.set_color", &json!({"color": "green"})).is_err()); + assert!(s.execute("layer.set_color", &json!({})).is_err()); +} + +#[test] +fn layer_height_is_100_200_or_300_percent() { + let mut s = Session::default(); + let l = s.layer; + assert_eq!(layer(&s, l).height(), 1); + assert_eq!(run(&mut s, "layer.set_height", json!({"height": 300}))["height"], 300); + assert_eq!(layer(&s, l).height(), 3); + for bad in [json!(0), json!(150), json!(400), json!(-100), json!("tall")] { + assert!(s.execute("layer.set_height", &json!({"height": bad})).is_err(), "{bad}"); + } + assert!(s.execute("layer.set_height", &json!({})).is_err()); + assert_eq!(layer(&s, l).height(), 3); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layer(&s, l).height(), 1); +} + +#[test] +fn layer_properties_set_everything_as_one_step_or_nothing() { + let (mut s, top, bottom) = two_walks(); + let undo = s.history.undo_len(); + let r = run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "name": "Sky", "color": "#123456", "outline": true, "height": 200, "locked": true, "visible": false, "onion": false, "type": "guide"})); + assert_eq!(r, json!({"layer": bottom.0, "name": "Sky", "type": "guide", "color": "#123456", "outline": true, "height": 200, "visible": false, "locked": true, "onion": false})); + assert_eq!(s.history.undo_len(), undo + 1, "one undo step"); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0})), r); + // The same type again changes nothing (a masked layer stays masked by the same mask). + run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "type": "guide"})); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0}))["type"], "guide"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + let back = run(&mut s, "layer.properties", json!({"layer": bottom.0})); + assert_eq!((back["name"].as_str(), back["type"].as_str(), back["height"].as_u64()), (Some("Layer 1"), Some("normal"), Some(100))); + // A bad value anywhere changes nothing. + for bad in [json!({"name": " "}), json!({"name": "X", "height": 250}), json!({"name": "X", "color": "red"}), json!({"name": "X", "type": "masked"}), json!({"name": "X", "type": "banana"}), json!({"name": "X", "locked": 1})] { + let mut p = bad.clone(); + p["layer"] = json!(top.0); + assert!(s.execute("layer.set_properties", &p).is_err(), "{bad}"); + assert_eq!(layer(&s, top).name, "Layer 2", "{bad}"); + } + assert!(s.execute("layer.properties", &json!({"layer": 999_999})).is_err()); +} + +#[test] +fn onion_and_height_are_saved_and_older_files_open_with_the_defaults() { + let (mut s, top, bottom) = two_walks(); + run(&mut s, "layer.set_onion", json!({"layer": top.0})); + run(&mut s, "layer.set_height", json!({"layer": bottom.0, "height": 200})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + let tl = back.timeline(0); + assert!(!tl.layer(top).unwrap().onion && tl.layer(bottom).unwrap().onion); + assert_eq!((tl.layer(top).unwrap().height(), tl.layer(bottom).unwrap().height()), (1, 2)); + // Defaults are left out of the file, so older files and files without them read the same. + let v: Value = serde_json::from_str(&text).unwrap(); + fn find(v: &Value, id: u64) -> Option { + match v { + Value::Object(m) if m.get("id") == Some(&json!(id)) && m.contains_key("keyframes") => Some(v.clone()), + Value::Object(m) => m.values().find_map(|x| find(x, id)), + Value::Array(a) => a.iter().find_map(|x| find(x, id)), + _ => None, + } + } + let by_id = |id: LayerId| find(&v, id.0).unwrap_or_default(); + assert!(by_id(top).get("name").is_some()); + assert_eq!((by_id(top).get("onion"), by_id(top).get("height")), (Some(&json!(false)), None)); + assert_eq!((by_id(bottom).get("onion"), by_id(bottom).get("height")), (None, Some(&json!(2)))); + let old: anicraft_doc::Layer = serde_json::from_value(json!({"id": 7, "name": "Old"})).unwrap(); + assert!(old.onion && old.height() == 1); + // A height out of range in a file reads as the nearest one. + let tall: anicraft_doc::Layer = serde_json::from_value(json!({"id": 7, "name": "Tall", "height": 200})).unwrap(); + assert_eq!(tall.height(), 3); +} + +/// A scene with a square walking on a second layer (x 0, 40, 80 on frames 0, 2, 4), and an +/// instance of a symbol on the first, open in place on frame 2 of the scene. +fn parent_walk() -> (Session, LayerId) { + let mut s = Session::default(); + let host = s.layer; + rect(&mut s, 300.0); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let inst = s.selection.ids().next().unwrap(); + let walker = LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let w = rect(&mut s, 0.0); + run(&mut s, "timeline.insert_frame", json!({"layer": host.0, "frame": 0, "count": 4})); + for f in [2, 4] { + run(&mut s, "timeline.goto", json!({"frame": f})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [w.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + run(&mut s, "layer.select", json!({"layer": host.0})); + run(&mut s, "timeline.goto", json!({"frame": 2})); + run(&mut s, "symbol.edit", json!({"id": inst.0})); + assert_eq!(s.editing.len(), 1); + (s, walker) +} + +#[test] +fn onion_skin_inside_a_symbol_shows_the_parent_timeline_frames_dimmed() { + let (s, walker) = parent_walk(); + let pic = s.stage_picture(); + let front = pic.front.clone().unwrap(); + let parent = front.parent.clone().expect("the scene shows around the symbol"); + assert_eq!(parent.frame, 2); + let skin = OnionSkin { markers: Markers::Relative { before: 2, after: 2 }, keyframes_only: true, ..OnionSkin::default() }; + let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &skin); + let left = |i: &anicraft_doc::DisplayItem| i.path.bounds().transformed(&i.transform).min.x; + // The walker on the scene: frame 2 (x 40) dimmed, frames 0 and 4 (x 0, 80) tinted and fainter. + let mut walk: Vec<(f32, f32, bool)> = dl.items.iter().filter(|i| left(i) < 150.0).map(|i| (left(i), dl.effective_alpha(i), i.color.changes_colour())).collect(); + walk.sort_by(|a, b| a.0.total_cmp(&b.0)); + assert_eq!(walk.iter().map(|w| w.0).collect::>(), vec![0.0, 40.0, 80.0], "the parent's onion frames around its frame 2"); + let dim = parent.dim; + assert!((walk[1].1 - dim).abs() < 1e-4 && !walk[1].2, "the parent's own frame as dim as without onion skin"); + assert!(walk[0].2 && walk[2].2 && walk[0].1 < dim && walk[2].1 < dim, "its onion frames tinted, dimmer still"); + // The open symbol is in front at full strength. + let box_item = dl.items.iter().find(|i| left(i) >= 290.0).unwrap(); + assert!((dl.effective_alpha(box_item) - 1.0).abs() < 1e-4); + assert!(dl.items.last().is_some_and(|i| left(i) >= 290.0), "drawn over everything around it"); + // Without onion skin the picture is as before; the parent's layer toggle and Edit Multiple + // Frames (the open symbol's frames only) leave its onion frames out. + let plain = crate::render_service::display_list_with_onion(&pic.doc, pic.frame, None); + assert_eq!(plain.items.len(), 2); + let multi = OnionSkin { edit_multiple: true, ..skin }; + assert_eq!(crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi).items.len(), 2); + let mut off = s; + run(&mut off, "symbol.exit", json!({})); + let inst = off.selection.ids().next().unwrap(); + run(&mut off, "layer.set_onion", json!({"layer": walker.0})); + run(&mut off, "symbol.edit", json!({"id": inst.0})); + let pic = off.stage_picture(); + let front = pic.front.clone().unwrap(); + assert_eq!(crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &skin).items.len(), 2); +} + +#[test] +fn plug_ins_may_set_layer_properties() { + for id in ["layer.set_onion", "layer.set_color", "layer.set_height", "layer.set_properties", "layer.properties"] { + assert!(crate::find_command(id).is_some(), "{id}"); + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 80cb336d..98281a92 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -79,7 +79,7 @@ fn document_view(s: &Session) -> Value { .timeline() .layers .iter() - .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "parent": l.parent.map(|p| p.0)})) + .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "outline": l.outline, "onion": l.onion, "height": u32::from(l.height()) * 100, "parent": l.parent.map(|p| p.0)})) .collect(); json!({ "abi": anicraft_plugins::ABI_VERSION, diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index e173b55d..eb57c705 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -126,7 +126,7 @@ fn set_layer_type(s: &mut Session, p: &Value) -> Result { Ok(layer_type_json(s, id)) } -fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { +pub(crate) fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder) { @@ -161,7 +161,7 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { Ok(()) } -fn layer_type_json(s: &Session, id: LayerId) -> Value { +pub(crate) fn layer_type_json(s: &Session, id: LayerId) -> Value { let Some(l) = s.timeline().layer(id) else { return json!({}) }; let tl = s.timeline(); let parent_kind = l.parent.and_then(|p| tl.layer(p)).map(|x| x.kind); diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index 037f29ad..46747f03 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -103,6 +103,20 @@ pub struct Front { pub timeline: Timeline, pub frame: u32, pub at: Affine, + /// The timeline the symbol was opened from, when it shows around it (in place): with onion + /// skin on, its frames around its own playhead show dimmed too (ADR 0061). + pub parent: Option, +} + +/// A timeline drawn dimmed around an open symbol: the picture's layer `layer` shows `timeline` +/// (without the instance that was opened) at its `frame`, placed by `at`, at opacity `dim`. +#[derive(Clone, Debug)] +pub struct Around { + pub layer: LayerId, + pub timeline: Timeline, + pub frame: u32, + pub at: Affine, + pub dim: f32, } impl Session { @@ -196,7 +210,7 @@ impl Session { tl.layers.push(placed(&mut doc, hit_timeline(&open), at, frame, ColorEffect::Advanced(hit_tint(tint, alpha)))); } let layer = placed(&mut doc, open.clone(), at, self.frame, ColorEffect::default()); - let front = Arc::new(Front { layer: layer.id, timeline: open, frame: self.frame, at }); + let mut front = Front { layer: layer.id, timeline: open, frame: self.frame, at, parent: None }; tl.layers.push(layer); // Around it, dimmed: each timeline below, without the instance opened from it. if view.in_place { @@ -207,9 +221,16 @@ impl Session { Some(p) => self.doc.symbol(p.symbol).map(|s| s.timeline.clone()).unwrap_or_default(), }; let xf = parent.map_or(Affine::IDENTITY, |p| p.transform); - tl.layers.push(placed(&mut doc, without(below, l.instance), xf, l.frame, ColorEffect::opacity(DIM))); + let around = without(below, l.instance); + let layer = placed(&mut doc, around.clone(), xf, l.frame, ColorEffect::opacity(DIM)); + // The timeline right under the open symbol is the one onion skin shows around it. + if front.parent.is_none() { + front.parent = Some(Around { layer: layer.id, timeline: around, frame: l.frame, at: xf, dim: DIM }); + } + tl.layers.push(layer); } } + let front = Arc::new(front); *doc.timeline_mut(self.scene) = tl; // Apart from document states (counted up from 1), and the same for the same picture. let pic = Arc::new(StagePicture { frame: doc.scene_start(self.scene), doc, state: key | 1 << 63, front: Some(front) }); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index db1a6012..9239be2f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,6 +17,7 @@ mod cmds_frames; mod cmds_modify; mod cmds_motion; mod cmds_hints; +mod cmds_layer; pub mod cmds_library; mod cmds_paint; mod cmds_path; @@ -116,6 +117,7 @@ pub fn commands() -> Vec { v.extend(cmds_drop::specs()); v.extend(cmds_recovery::specs()); v.extend(cmds_timeline::specs()); + v.extend(cmds_layer::specs()); v.extend(cmds_camera::specs()); v.extend(cmds_bone::specs()); v.extend(cmds_motion::specs()); diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs index 594f98da..156dd8a8 100644 --- a/crates/engine/src/onion.rs +++ b/crates/engine/src/onion.rs @@ -199,15 +199,22 @@ pub struct Extra { pub distance: u32, } -/// Whether onion skin draws `layer` (Animate doesn't onion-skin locked layers). -fn ghosted(tl: &Timeline, i: usize) -> bool { +/// Whether `layer` is shown and unlocked artwork (not a folder), itself and through its folders. +fn open_artwork(tl: &Timeline, i: usize) -> bool { tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder && !tl.locked_by_folder(l.id) && !tl.hidden_by_folder(i)) } +/// Whether onion skin draws `layer`: shown and unlocked (Animate doesn't onion-skin locked +/// layers), with its own onion toggle on (ADR 0061). +pub fn ghosted(tl: &Timeline, i: usize) -> bool { + open_artwork(tl, i) && tl.layers.get(i).is_some_and(|l| l.onion) +} + /// Whether Edit Multiple Frames shows and edits `layer`'s other keyframes: it is shown and /// unlocked, and holds artwork (not a folder, the camera or an armature posed by its bones). +/// A layer's onion toggle doesn't apply: it is about the faded frames, not editing. pub fn multi_editable(tl: &Timeline, i: usize) -> bool { - ghosted(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature)) + open_artwork(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature)) } /// The onion frames to draw for the playhead on `playhead`, farthest first (nearest on top), diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs index c28e4ecf..01014d59 100644 --- a/crates/engine/src/render_service.rs +++ b/crates/engine/src/render_service.rs @@ -94,14 +94,48 @@ impl FrameJob { } /// A stage picture's frame with the open symbol in front composed by `skin`: the timelines around -/// it as they are, then the symbol's frames, each layer's onion frames under its artwork. +/// it as they are, then the symbol's frames, each layer's onion frames under its artwork. With +/// onion skin on (not Edit Multiple Frames), the timeline the symbol was opened from shows its +/// own onion frames too, dimmed with it (ADR 0061). pub fn display_list_inside(doc: &Document, frame: u32, front: &Front, skin: &OnionSkin) -> DisplayList { let (scene, local) = doc.locate(frame); - let mut around = doc.timeline(scene).clone(); - around.layers.retain(|l| l.id != front.layer); - let mut dl = anicraft_doc::evaluate_timeline(doc, &around, local); let tl = &front.timeline; - dl.append(crate::onion::compose_timeline(tl, front.frame, Some(skin), |f| anicraft_doc::evaluate_timeline_at(doc, tl, f, front.at))); + let parent = front.parent.as_ref().filter(|_| skin.ghosts && !skin.edit_multiple); + let mut dl = DisplayList::default(); + // Back to front: the picture's layers from the bottom up, each its own timeline. + for l in doc.timeline(scene).layers.iter().rev() { + if l.id == front.layer { + dl.append(crate::onion::compose_timeline(tl, front.frame, Some(skin), |f| anicraft_doc::evaluate_timeline_at(doc, tl, f, front.at))); + } else if let Some(p) = parent.filter(|p| p.layer == l.id) { + dl.append(parent_onion(doc, p, front, skin)); + } else { + dl.append(anicraft_doc::evaluate_timeline(doc, &anicraft_doc::Timeline { layers: vec![l.clone()] }, local)); + } + } + dl +} + +/// The timeline around an open symbol with its onion frames, all at its dim opacity. Markers that +/// follow the playhead reach as many frames from the parent's frame; anchored ones (which name +/// the symbol's frames) as far as they reach from the symbol's playhead. +fn parent_onion(doc: &Document, p: &crate::editing::Around, front: &Front, skin: &OnionSkin) -> DisplayList { + let mut own = *skin; + if skin.anchored() { + let (first, last) = skin.range(front.frame, front.timeline.frame_count()); + own.markers = crate::onion::Markers::Relative { before: front.frame.saturating_sub(first), after: last.saturating_sub(front.frame) }; + } + let composed = crate::onion::compose_timeline(&p.timeline, p.frame, Some(&own), |f| anicraft_doc::evaluate_timeline_at(doc, &p.timeline, f, p.at)); + // It fades as one, as the dimmed instance it replaces does: everything in a group at `dim`. + let alpha = if p.dim.is_finite() { p.dim.clamp(0.0, 1.0) } else { 1.0 }; + let mut dl = DisplayList::default(); + dl.groups.push(anicraft_doc::Group { parent: None, alpha, blend: Default::default(), filters: Arc::from(Vec::new()), clip: None }); + dl.append(composed); + for g in dl.groups.iter_mut().skip(1) { + g.parent = Some(g.parent.unwrap_or(0)); + } + for it in dl.items.iter_mut().filter(|i| i.masks.is_none()) { + it.group = Some(it.group.unwrap_or(0)); + } dl } diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 60a333da..6954a59c 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -531,6 +531,8 @@ impl<'a> Builder<'a> { layer.locked = l.bool("locked").unwrap_or(false); layer.outline = l.bool("outline").unwrap_or(false); layer.color = color(l, "color", "__none"); + // Layer Properties' height, 100 / 200 / 300 % (ADR 0061), as a multiple of a row. + layer.height_rows = l.u32("heightMultiplier").map_or(1, |h| h.clamp(1, u32::from(anicraft_doc::MAX_LAYER_HEIGHT)) as u8); let mut keys = Vec::new(); let mut raw_hints: HashMap> = HashMap::new(); for f in l.list("frames").iter().filter(|f| f.name == "DOMFrame") { diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 648130f9..362ef090 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -32,7 +32,7 @@ const DOC: &str = r##" + @@ -90,6 +90,7 @@ fn stage_layers_frames_and_tweens() { assert_eq!(ball.keyframes[0].label, "start"); assert!(matches!(ball.keyframes[0].tween.map(|t| t.easing), Some(anicraft_doc::Easing::Classic(e)) if e == -50.0)); assert!(doc.timeline(0).layers[1].locked); + assert_eq!((doc.timeline(0).layers[0].height(), doc.timeline(0).layers[1].height()), (1, 2), "Layer Properties height"); assert_eq!(doc.timeline(0).layers[2].kind, LayerKind::Guide); assert_eq!(doc.timeline(0).frame_count(), 15); assert_eq!(doc.frame_count(), 16, "the movie: scene 1, then the one-frame scene 2"); From 0bc3569c0c5eb9a41352088e613e48291801ccce Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 16:40:54 -0700 Subject: [PATCH 053/192] feat(timeline): onion column, colour chip, layer height, Layer Properties, frame view (M1) --- ATTRIBUTION.md | 2 +- assets/icons/anicraft-layer.svg | 5 + crates/engine/src/cmds_layer.rs | 4 + crates/engine/src/cmds_timeline.rs | 5 +- crates/engine/src/lib.rs | 1 + src/a11y.rs | 2 +- src/app.rs | 35 +++ src/icons.rs | 7 +- src/layer_props.rs | 239 ++++++++++++++++++ src/main.rs | 3 +- src/prefs.rs | 3 + src/timeline.rs | 387 ++++++++++++++++++++++++----- 12 files changed, 624 insertions(+), 69 deletions(-) create mode 100644 assets/icons/anicraft-layer.svg create mode 100644 src/layer_props.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7d4a1a68..81b08496 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -19,7 +19,7 @@ shaders or SDK code). | Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) | | Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) | | emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) | -| `assets/icons/anicraft-*.svg` (19 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | +| `assets/icons/anicraft-*.svg` (20 files: align, distribute, layer, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | | `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | (`icons/.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) | | `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) | diff --git a/assets/icons/anicraft-layer.svg b/assets/icons/anicraft-layer.svg new file mode 100644 index 00000000..6a8eda2f --- /dev/null +++ b/assets/icons/anicraft-layer.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/crates/engine/src/cmds_layer.rs b/crates/engine/src/cmds_layer.rs index 3289e0a6..23b03ca3 100644 --- a/crates/engine/src/cmds_layer.rs +++ b/crates/engine/src/cmds_layer.rs @@ -11,6 +11,10 @@ use anicraft_doc::{Layer, LayerId, LayerKind, MAX_LAYER_HEIGHT}; use serde_json::{Value, json}; use std::sync::Arc; +/// Layer colours offered next to the colour picker (sRGB): those new layers take in turn, +/// then a few more, all bright enough to read as outlines on a dark or a light stage. +pub const LAYER_COLORS: [u32; 12] = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65, 0xf06292, 0xaed581, 0x9575cd, 0xe0e0e0, 0x8d6e63]; + pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index eb57c705..8cb53625 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -656,8 +656,9 @@ fn new_folder(s: &mut Session, p: &Value) -> Result { /// The colour the `n`th layer gets (its outline and timeline bar). pub(crate) fn layer_color(n: usize) -> anicraft_doc::Rgba { - const PALETTE: [u32; 7] = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; - anicraft_doc::Rgba::hex(PALETTE.get(n % PALETTE.len()).copied().unwrap_or(0x4fa3ff)) + // The first seven of the layer colours, in turn. + const TURN: usize = 7; + anicraft_doc::Rgba::hex(crate::LAYER_COLORS.get(n % TURN).copied().unwrap_or(0x4fa3ff)) } fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9239be2f..86255977 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -167,6 +167,7 @@ pub fn find_command(id: &str) -> Option { pub use history::{Snapshot, StateId}; pub use selection::Selection; +pub use cmds_layer::LAYER_COLORS; /// Last addressable frame (0-based); about 70 minutes at 24 fps. pub const MAX_FRAME: u32 = 100_000; diff --git a/src/a11y.rs b/src/a11y.rs index 3f9636da..9fcff754 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -352,7 +352,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer"] { + for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index e610aca4..01443224 100644 --- a/src/app.rs +++ b/src/app.rs @@ -298,6 +298,12 @@ pub struct App { pub prompt: Option, /// The Convert to Symbol dialog, and what it chose last (ADR 0053). pub convert: Option, + /// The Layer Properties dialog while it is open (ADR 0061). + pub layer_props: Option, + /// Open the timeline's Frame View menu on the next frame (screenshots, the audit). + pub tl_frame_view_open: bool, + /// Open this layer's colour popup on the next frame (screenshots, the audit). + pub tl_color_open: Option, pub convert_last: crate::convert_symbol::Last, pub show_about: bool, pub show_files: bool, @@ -509,6 +515,9 @@ impl App { status: None, prompt: None, convert: None, + layer_props: None, + tl_frame_view_open: false, + tl_color_open: None, convert_last: Default::default(), show_about: false, show_files: false, @@ -945,6 +954,26 @@ impl App { let top = self.s.timeline().layers.first().map(|l| l.id); self.onion_ui.sel.retain(|it| Some(it.layer) == top); } + Some("layerprops") => { + // Layer Properties (ADR 0061) on the active layer. + crate::layer_props::open(self, None); + } + Some("frameview") => self.tl_frame_view_open = true, + Some("layercolour") => self.tl_color_open = Some(self.s.layer), + Some("timelinepolish") => { + // Per-layer onion toggles, outlines in the layer colour and a taller layer + // (ADR 0061): onion skin on, the top layer outlined in orange and 200 % tall, + // the next one left out of onion skin. + self.onion.ghosts = true; + let ids: Vec = self.s.timeline().layers.iter().filter(|l| !matches!(l.kind, anicraft_engine::doc::LayerKind::Folder | anicraft_engine::doc::LayerKind::Camera)).map(|l| l.id.0).collect(); + if let Some(&top) = ids.first() { + self.run("layer.set_properties", json!({"layer": top, "outline": true, "color": "#ff8a65", "height": 200})); + } + if let Some(&next) = ids.get(1) { + self.run("layer.set_onion", json!({"layer": next, "onion": false})); + } + self.run("timeline.goto", json!({"frame": 12})); + } Some("onionsymbol") => { // Onion skin inside a symbol open in place (ADR 0051): the sample's spinning star, // its own frames before and after its playhead around it. @@ -1775,6 +1804,11 @@ impl App { self.show_plugins = true; return; } + if id == "layer.set_properties" { + // Modify › Timeline › Layer Properties: the dialog for the active layer. + crate::layer_props::open(self, None); + return; + } if id == "modify.convert_to_symbol" { // Name, type and Library folder (ADR 0053). crate::convert_symbol::open(self); @@ -2391,6 +2425,7 @@ impl App { crate::drop::frame(self, &ctx); self.prompt_window(&ctx); crate::convert_symbol::window(self, &ctx); + crate::layer_props::window(self, &ctx); self.about_window(&ctx); dialogs::show_all(self, &ctx); autosave::window(self, &ctx); diff --git a/src/icons.rs b/src/icons.rs index ec155d3c..cc2045c4 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -68,11 +68,13 @@ pub enum Icon { Magnet, Bone, EditMultiple, + Layer, } impl Icon { #[cfg(test)] - pub const ALL: [Icon; 54] = [ + pub const ALL: [Icon; 55] = [ + Icon::Layer, Icon::EditMultiple, Icon::Bone, Icon::Magnet, @@ -206,6 +208,8 @@ impl Icon { // Lucide's grid): Edit Multiple Frames. Icon::EditMultiple => ("anicraft-edit-multiple", false), Icon::FolderOpen => ("folder-open", false), + // A layer: a row with a keyframe and its span (AniCraft original, on Lucide's grid). + Icon::Layer => ("anicraft-layer", false), } } } @@ -258,6 +262,7 @@ static FILES: &[(&str, &str)] = &[ ("anicraft-eraser", include_str!("../assets/icons/anicraft-eraser.svg")), ("anicraft-eyedropper", include_str!("../assets/icons/anicraft-eyedropper.svg")), ("anicraft-masked", include_str!("../assets/icons/anicraft-masked.svg")), + ("anicraft-layer", include_str!("../assets/icons/anicraft-layer.svg")), ("anicraft-camera", include_str!("../assets/icons/anicraft-camera.svg")), ("anicraft-bone", include_str!("../assets/icons/anicraft-bone.svg")), ("anicraft-edit-multiple", include_str!("../assets/icons/anicraft-edit-multiple.svg")), diff --git a/src/layer_props.rs b/src/layer_props.rs new file mode 100644 index 00000000..0b3e0322 --- /dev/null +++ b/src/layer_props.rs @@ -0,0 +1,239 @@ +//! The Layer Properties dialog (ADR 0061), as in Animate: name, show and lock, type, outline +//! colour, View layer as outlines, onion skin and layer height. Opened by double-clicking a +//! layer's icon, from the layer's right-click menu or Modify › Timeline. OK sends one +//! `layer.set_properties` (one undo step) with what changed; Cancel changes nothing. + +use crate::a11y::Named; +use crate::app::App; +use crate::theme::{FORM_LABEL_DIALOG, Type, form_row, text, to_color32}; +use anicraft_engine::doc::{LayerId, LayerKind, MAX_LAYER_HEIGHT, Rgba}; +use egui::Key; +use serde_json::{Value, json}; + +/// The dialog while it is open: the layer and the values being edited. +pub struct LayerPropsDialog { + pub layer: LayerId, + pub name: String, + pub visible: bool, + pub locked: bool, + /// `normal`, `mask`, `masked`, `guide`, `guided`, or a kind that can't change (`folder`, + /// `camera`, `armature`). + pub ty: String, + pub color: [u8; 3], + pub outline: bool, + pub onion: bool, + /// Rows: 1, 2 or 3 (100, 200, 300 %). + pub height: u8, + /// What the layer had when the dialog opened: OK sends only what changed. + was: Value, + focus: bool, +} + +/// The layer's properties as the engine reports them. +fn current(app: &mut App, layer: LayerId) -> Option { + app.s.execute("layer.properties", &json!({"layer": layer.0})).ok() +} + +/// Opens the dialog for `layer` (default: the active layer). +pub fn open(app: &mut App, layer: Option) { + let id = layer.unwrap_or(app.s.layer); + let Some(p) = current(app, id) else { return }; + let Some(l) = app.s.timeline().layer(id) else { return }; + let c = to_color32(l.color); + app.playing = false; + app.layer_props = Some(LayerPropsDialog { + layer: id, + name: l.name.clone(), + visible: l.visible, + locked: l.locked, + ty: p.get("type").and_then(Value::as_str).unwrap_or("normal").to_string(), + color: [c.r(), c.g(), c.b()], + outline: l.outline, + onion: l.onion, + height: l.height(), + was: p, + focus: true, + }); +} + +/// The types a layer can be given here, with their names. +fn types() -> [(&'static str, &'static str); 5] { + [("normal", tr!("Normal")), ("guide", tr!("Guide")), ("guided", tr!("Guided")), ("mask", tr!("Mask")), ("masked", tr!("Masked"))] +} + +fn type_label(ty: &str) -> &'static str { + match ty { + "folder" => tr!("Folder"), + "camera" => tr!("Camera"), + "armature" => tr!("Armature"), + other => types().into_iter().find(|(k, _)| *k == other).map_or(tr!("Normal"), |(_, n)| n), + } +} + +pub fn window(app: &mut App, ctx: &egui::Context) { + if app.layer_props.as_ref().is_some_and(|d| app.s.timeline().layer(d.layer).is_none()) { + // The layer went away (undo, another edit): nothing to set. + app.layer_props = None; + } + let Some(d) = &mut app.layer_props else { return }; + // What each type needs: a mask or guide right above for masked and guided. + let (can_mask, can_guide, kind) = { + let tl = app.s.timeline(); + let i = tl.layers.iter().position(|l| l.id == d.layer); + let kind = i.and_then(|i| tl.layers.get(i)).map_or(LayerKind::Normal, |l| l.kind); + (i.and_then(|i| tl.mask_above(i)).is_some(), i.and_then(|i| tl.guide_above(i)).is_some(), kind) + }; + let fixed = matches!(kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature); + let (mut submit, mut cancel) = (false, false); + egui::Window::new(tr!("Layer Properties")).id(egui::Id::new("layer_props")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| { + ui.set_min_width(420.0); + form_row(ui, FORM_LABEL_DIALOG, tr!("Name"), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Layer name")); + if d.focus { + r.request_focus(); + d.focus = false; + } + if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { + submit = true; + } + }); + form_row(ui, FORM_LABEL_DIALOG, tr!("Layer"), |ui| { + crate::theme::checkbox(ui, &mut d.visible, tr!("Show")); + crate::theme::checkbox(ui, &mut d.locked, tr!("Lock")); + }); + form_row(ui, FORM_LABEL_DIALOG, tr!("Type"), |ui| { + if fixed { + ui.label(text(Type::Body, type_label(&d.ty))); + return; + } + ui.vertical(|ui| { + for (k, name) in types() { + let allowed = match k { + "masked" => can_mask || d.ty == k, + "guided" => can_guide || d.ty == k, + _ => true, + }; + let r = ui.add_enabled(allowed, egui::RadioButton::new(d.ty == k, name)); + let r = if allowed { + r + } else if k == "masked" { + r.on_disabled_hover_text(tr!("Only a layer right under a mask layer can be masked")) + } else { + r.on_disabled_hover_text(tr!("Only a layer right under a motion guide can be guided")) + }; + if r.clicked() { + d.ty = k.to_string(); + } + } + }); + }); + form_row(ui, FORM_LABEL_DIALOG, tr!("Outline colour"), |ui| { + ui.color_edit_button_srgb(&mut d.color).named(tr!("Outline colour")).on_hover_text(tr!("The colour of the layer's outlines and of its bar on the timeline")); + }); + if kind != LayerKind::Camera && kind != LayerKind::Folder { + form_row(ui, FORM_LABEL_DIALOG, tr!("Outlines"), |ui| { + crate::theme::checkbox(ui, &mut d.outline, tr!("View layer as outlines")).on_hover_text(tr!("Draw the layer's artwork as outlines in its colour, on the stage only (never in the movie or an export)")); + }); + form_row(ui, FORM_LABEL_DIALOG, tr!("Onion skin"), |ui| { + crate::theme::checkbox(ui, &mut d.onion, tr!("Onion skin this layer")).on_hover_text(tr!("Show this layer's frames around the playhead while onion skin is on")); + }); + } + form_row(ui, FORM_LABEL_DIALOG, tr!("Layer height"), |ui| { + egui::ComboBox::from_id_salt("layer_props_height") + .width(96.0) + .selected_text(text(Type::Data, format!("{} %", u32::from(d.height) * 100))) + .show_ui(ui, |ui| { + for h in 1..=MAX_LAYER_HEIGHT { + if ui.selectable_label(d.height == h, text(Type::Data, format!("{} %", u32::from(h) * 100))).clicked() { + d.height = h; + } + } + }) + .response + .set_name(tr!("Layer height")); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + if ui.button(tr!("OK")).clicked() { + submit = true; + } + if ui.button(tr!("Cancel")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { + cancel = true; + } + }); + }); + if submit { + accept(app); + } else if cancel { + app.layer_props = None; + } +} + +/// The params OK sends: the layer, and every property that differs from when the dialog opened. +pub fn changes(d: &LayerPropsDialog) -> Value { + let [r, g, b] = d.color; + let color = Rgba::new(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, 1.0).to_hex(); + let now = json!({ + "name": d.name.trim(), + "visible": d.visible, + "locked": d.locked, + "type": d.ty, + "color": color, + "outline": d.outline, + "onion": d.onion, + "height": u32::from(d.height) * 100, + }); + let mut out = json!({"layer": d.layer.0}); + if let (Some(now), Some(o)) = (now.as_object(), out.as_object_mut()) { + for (k, v) in now { + if d.was.get(k) != Some(v) { + o.insert(k.clone(), v.clone()); + } + } + } + out +} + +/// OK: one `layer.set_properties` with what changed (nothing changed: nothing sent). +fn accept(app: &mut App) { + let Some(d) = app.layer_props.take() else { return }; + let p = changes(&d); + if p.as_object().is_some_and(|o| o.len() > 1) { + app.request("layer.set_properties", p); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::sample; + + #[test] + fn ok_sets_what_changed_as_one_step_and_cancel_nothing() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + let id = app.s.layer; + open(&mut app, None); + let d = app.layer_props.as_mut().expect("the dialog opens on the active layer"); + assert_eq!(d.layer, id); + assert_eq!(changes(d), json!({"layer": id.0}), "nothing changed yet"); + d.name = " Hero ".into(); + d.height = 2; + d.outline = true; + assert_eq!(changes(d), json!({"layer": id.0, "name": "Hero", "height": 200, "outline": true})); + let steps = app.s.history().undo_len(); + accept(&mut app); + assert!(app.layer_props.is_none()); + let l = app.s.timeline().layer(id).unwrap(); + assert_eq!((l.name.as_str(), l.height(), l.outline), ("Hero", 2, true)); + assert_eq!(app.s.history().undo_len(), steps + 1, "one undo step"); + // OK with nothing changed sends nothing. + open(&mut app, Some(id)); + accept(&mut app); + assert_eq!(app.s.history().undo_len(), steps + 1); + // The menu command opens it too. + app.invoke("layer.set_properties"); + assert!(app.layer_props.is_some()); + } +} diff --git a/src/main.rs b/src/main.rs index c675b2e7..2037857f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,6 +32,7 @@ mod erasertool; mod bone_tool; mod camera_tool; mod convert_symbol; +mod layer_props; mod dialogs; mod drop; mod gpu_stage; @@ -191,7 +192,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|button|testhits|exporthtml|sound|envelope|library|librarymenu|colour]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|button|testhits|exporthtml|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/prefs.rs b/src/prefs.rs index 595e8c48..3e8c71b2 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -79,6 +79,8 @@ pub struct Prefs { /// Extra space before frame 1 on the timeline, in points, on top of the room the playhead /// needs (the playhead can't go there). Fixed on screen, whatever the zoom. pub timeline_start_gap: f32, + /// Frame view › Short (ADR 0061): timeline rows at their short height. + pub timeline_short_rows: bool, /// Keyboard shortcuts the user changed: action id → its full list of keys (empty = /// unbound). Actions not listed keep their defaults (`keymap`). pub shortcuts: std::collections::BTreeMap>, @@ -141,6 +143,7 @@ impl Default for Prefs { stage_renderer: StageRenderer::Gpu, native_dialogs: true, timeline_start_gap: 0.0, + timeline_short_rows: false, shortcuts: Default::default(), autosave: true, autosave_secs: 60, diff --git a/src/timeline.rs b/src/timeline.rs index 3ffc1087..39295cb2 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -34,6 +34,71 @@ fn frame_center(cell_left: f32, cell_w: f32) -> f32 { (cell_left + cell_w * 0.5).round() + 0.5 } const FOOTER_H: f32 = 38.0; +/// Frame View › Short (ADR 0061): row height (points). Layers 200 % and 300 % tall are that +/// many short rows. +const SHORT_ROW_H: f32 = 20.0; +/// Frame View's frame widths, Tiny to Large, as frame cell widths (the zoom slider sets any +/// width in between). +pub const FRAME_WIDTHS: [(&str, f32); 5] = [(tr_noop!("Tiny"), 4.0), (tr_noop!("Small"), 8.0), (tr_noop!("Normal"), CELL_DEFAULT), (tr_noop!("Medium"), 18.0), (tr_noop!("Large"), 28.0)]; + +/// A normal row's height: full, or Frame View › Short. +pub fn base_row_h(short: bool) -> f32 { + if short { SHORT_ROW_H } else { ROW_H } +} + +/// How many whole rows of heights `h` fit in `avail` points from row `first`: at least one +/// while any are left (a tall row in a small dock is cut off rather than hidden). +fn rows_fitting(h: &[f32], first: usize, avail: f32) -> usize { + let (mut used, mut n) = (0.0, 0); + for x in h.iter().skip(first) { + if n > 0 && used + x > avail + 0.5 { + break; + } + used += x; + n += 1; + } + n +} + +/// The scroll limit: the first row from which every row to the end fits. +fn max_first_row(h: &[f32], avail: f32) -> usize { + first_showing(h, h.len().saturating_sub(1), avail) +} + +/// The first row to show so that row `r` is the last one that fits (the least scroll that +/// brings it into view from above). +fn first_showing(h: &[f32], r: usize, avail: f32) -> usize { + let mut used = 0.0; + for i in (0..=r.min(h.len().saturating_sub(1))).rev() { + used += h.get(i).copied().unwrap_or(0.0); + if used > avail + 0.5 { + return (i + 1).min(r); + } + } + 0 +} + +/// The row `dy` points below the top of row `first` (negative: above it), within the rows. +fn row_at(h: &[f32], first: usize, dy: f32) -> usize { + if dy < 0.0 { + let mut y = 0.0; + for i in (0..first.min(h.len())).rev() { + y -= h.get(i).copied().unwrap_or(0.0); + if dy >= y { + return i; + } + } + return 0; + } + let mut y = 0.0; + for (i, x) in h.iter().enumerate().skip(first) { + y += x; + if dy < y { + return i; + } + } + h.len().saturating_sub(1) +} /// Eye / lock / outline toggles: square targets in each layer row. const TOGGLE: f32 = 24.0; /// Indent per folder or mask level in the layer list. @@ -171,13 +236,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // ---- header --------------------------------------------------------------------------- egui::Frame::NONE.fill(T.panel_alt).inner_margin(egui::Margin::symmetric(10, 5)).show(ui, |ui| { ui.horizontal(|ui| { - // Room kept at the right end for the frame zoom: the 56 pt slider, its field, spacing. - const ZOOM_W: f32 = 122.0; + // Room kept at the right end for the frame zoom (the 56 pt slider, its field, + // spacing) and the Frame View menu. + const ZOOM_W: f32 = 122.0 + 30.0; // The rest scrolls sideways (Shift+wheel) when the dock is narrow (a small window, a // large interface scale) instead of being cut off. let w = (ui.available_width() - ZOOM_W).max(0.0); egui::ScrollArea::horizontal().id_salt("tl_header").max_width(w).show(ui, |ui| ui.horizontal(|ui| header(app, ui, dock))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + frame_view_button(app, ui); let mut pct = app.tl_cell_w / CELL_DEFAULT * 100.0; let (lo, hi) = (CELL_RANGE.start() / CELL_DEFAULT * 100.0, CELL_RANGE.end() / CELL_DEFAULT * 100.0); ui.spacing_mut().slider_width = 56.0; @@ -261,29 +328,37 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { (0..tl.layers.len()).filter(|&i| !app.tl_collapsed.iter().any(|f| tl.is_inside(i, *f))).collect() }; let n_layers = rows.len(); - let rows_visible = ((body.height() - RULER_H - FOOTER_H) / ROW_H).floor().max(1.0) as usize; + // Each row is its layer's height (100, 200 or 300 % of a normal or short row, ADR 0061). + let base_h = base_row_h(app.prefs.timeline_short_rows); + let heights: Vec = { + let tl = app.s.timeline(); + rows.iter().map(|&i| f32::from(tl.layers.get(i).map_or(1, |l| l.height())) * base_h).collect() + }; + let avail = (body.height() - RULER_H - FOOTER_H).max(0.0); if ui.rect_contains_pointer(body) { let d = ui.input(|i| i.smooth_scroll_delta); if d.x != 0.0 { app.tl_scroll = (app.tl_scroll - d.x / cell_w).max(0.0); } if d.y != 0.0 { - app.tl_vscroll = (app.tl_vscroll - d.y / ROW_H).max(0.0); + app.tl_vscroll = (app.tl_vscroll - d.y / base_h).max(0.0); } } - app.tl_vscroll = app.tl_vscroll.min(n_layers.saturating_sub(rows_visible) as f32); + app.tl_vscroll = app.tl_vscroll.min(max_first_row(&heights, avail) as f32); if app.tl_last_layer != Some(app.s.layer) && let Some(ai) = app.s.active_layer_index().and_then(|li| rows.iter().position(|&r| r == li)) { // the active layer changed (e.g. picked on the stage): bring its row into view - if (ai as f32) < app.tl_vscroll { + let first = app.tl_vscroll.floor() as usize; + if ai < first { app.tl_vscroll = ai as f32; - } else if ai >= app.tl_vscroll as usize + rows_visible { - app.tl_vscroll = (ai + 1 - rows_visible) as f32; + } else if ai >= first + rows_fitting(&heights, first, avail) { + app.tl_vscroll = first_showing(&heights, ai, avail) as f32; } app.tl_last_layer = Some(app.s.layer); } let first_row = app.tl_vscroll.floor() as usize; + let rows_visible = rows_fitting(&heights, first_row, avail); let max_scroll = (frames_total + 30).saturating_sub(visible_cols) as f32; app.tl_scroll = app.tl_scroll.min(max_scroll.max(0.0)); // keep the playhead visible while playing @@ -361,19 +436,23 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let rows_top = ruler.bottom(); let rows_bottom = body.bottom() - FOOTER_H; let tl_now = app.s.timeline().clone(); + let mut next_y = rows_top; for (r, &i) in rows.iter().enumerate().skip(first_row) { let Some(layer) = layers.get(i) else { continue }; - let y = rows_top + (r - first_row) as f32 * ROW_H; - // Whole rows only: a cut-off row would sit under the footer (scroll for the rest). - if y + ROW_H > rows_bottom + 0.5 { + let y = next_y; + let rh = heights.get(r).copied().unwrap_or(base_h); + // Whole rows only: a cut-off row would sit under the footer (scroll for the rest). The + // first row always shows, however tall. + if r > first_row && y + rh > rows_bottom + 0.5 { break; } - let row = Rect::from_min_size(pos2(body.left(), y), vec2(body.width(), ROW_H)); + next_y += rh; + let row = Rect::from_min_size(pos2(body.left(), y), vec2(body.width(), rh)); let left = Rect::from_min_max(row.left_top(), pos2(grid.left(), row.bottom())); let is_active = layer.id == active; painter.rect_filled(left, 0.0, if is_active { T.accent_dim } else if r % 2 == 0 { T.panel } else { T.panel_alt }); // The layer's colour as a full-height edge bar. - painter.rect_filled(Rect::from_min_size(left.left_top(), vec2(4.0, ROW_H)), 0.0, to_color32(layer.color)); + painter.rect_filled(Rect::from_min_size(left.left_top(), vec2(4.0, rh)), 0.0, to_color32(layer.color)); // Layers are indented under the folders and masks that hold them. Folders carry a // disclosure chevron and a folder glyph; masks a stencil; masked layers its inside. let is_folder = layer.kind == LayerKind::Folder; @@ -384,35 +463,24 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let type_icon = |x: f32, icon: Icon| icons::paint(&painter, Rect::from_center_size(pos2(x, left.center().y), vec2(14.0, 14.0)), icon, name_color); let x0 = left.left() + 12.0 + tl_now.depth(i) as f32 * INDENT; let open = !app.tl_collapsed.contains(&layer.id); - let chevron = Rect::from_center_size(pos2(x0 + 6.0, left.center().y), vec2(TOGGLE, TOGGLE)); - let name_x = match layer.kind { - LayerKind::Folder => { - icons::paint(&painter, Rect::from_center_size(chevron.center(), vec2(12.0, 12.0)), if open { Icon::ChevronDown } else { Icon::ChevronRight }, T.text_dim); - type_icon(x0 + 24.0, if open { Icon::FolderOpen } else { Icon::Folder }); - x0 + 37.0 - } - LayerKind::Mask => { - type_icon(x0 + 7.0, Icon::Mask); - x0 + 20.0 - } - LayerKind::Normal if masked => { - type_icon(x0 + 7.0, Icon::Masked); - x0 + 20.0 - } - LayerKind::Guide => { - type_icon(x0 + 7.0, Icon::Guide); - x0 + 20.0 - } - LayerKind::Camera => { - type_icon(x0 + 7.0, Icon::Camera); - x0 + 20.0 - } - LayerKind::Armature => { - type_icon(x0 + 7.0, Icon::Bone); - x0 + 20.0 - } - _ => x0 + 4.0, + // Toggles and targets fit a short row. + let tg = TOGGLE.min(base_h - 2.0); + let chevron = Rect::from_center_size(pos2(x0 + 6.0, left.center().y), vec2(tg, tg)); + // Every layer has its type's icon; double-click it for Layer Properties (ADR 0061). + let (icon_x, name_x, icon) = match layer.kind { + LayerKind::Folder => (x0 + 24.0, x0 + 37.0, if open { Icon::FolderOpen } else { Icon::Folder }), + LayerKind::Mask => (x0 + 7.0, x0 + 20.0, Icon::Mask), + LayerKind::Normal if masked => (x0 + 7.0, x0 + 20.0, Icon::Masked), + LayerKind::Guide => (x0 + 7.0, x0 + 20.0, Icon::Guide), + LayerKind::Camera => (x0 + 7.0, x0 + 20.0, Icon::Camera), + LayerKind::Armature => (x0 + 7.0, x0 + 20.0, Icon::Bone), + LayerKind::Normal => (x0 + 7.0, x0 + 20.0, Icon::Layer), }; + if is_folder { + icons::paint(&painter, Rect::from_center_size(chevron.center(), vec2(12.0, 12.0)), if open { Icon::ChevronDown } else { Icon::ChevronRight }, T.text_dim); + } + type_icon(icon_x, icon); + let icon_rect = Rect::from_center_size(pos2(icon_x, left.center().y), vec2(16.0, tg)); let name_at = painter.text(pos2(name_x, left.center().y), Align2::LEFT_CENTER, &layer.name, font(Type::Body), name_color); let has_selection = holding.contains(&layer.id); if has_selection { @@ -421,15 +489,18 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_stroke(sq, 0.0, Stroke::new(1.0, T.text), StrokeKind::Outside); } - // eye / lock / outline toggles: 24 × 24 targets with a hover fill - let toggle = |k: f32| Rect::from_center_size(pos2(left.right() - 16.0 - k * (TOGGLE + 2.0), left.center().y), vec2(TOGGLE, TOGGLE)); + // Onion / eye / lock / outline toggles, right to left from the outline square: square + // targets with a hover fill (smaller on short rows). + let toggle = |k: f32| Rect::from_center_size(pos2(left.right() - 16.0 - k * (TOGGLE + 2.0), left.center().y), vec2(tg, tg)); let (eye, lock, outl) = (toggle(2.0), toggle(1.0), toggle(0.0)); - // A layer with sounds has a speaker before the eye: Mute (ADR 0039). - let speaker = layer.has_sounds().then(|| toggle(3.0)); - let hover = ui.input(|inp| inp.pointer.hover_pos()); - // The camera has no artwork to outline: its row has the eye (camera on or off) and lock. + // The camera has no artwork to outline or onion-skin: its row has the eye (camera on or + // off) and lock. A folder has no frames to onion-skin. let is_camera = layer.kind == LayerKind::Camera; - for r in [eye, lock, outl].into_iter().take(if is_camera { 2 } else { 3 }).chain(speaker) { + let onion_t = (!is_camera && !is_folder).then(|| toggle(3.0)); + // A layer with sounds has a speaker before the others: Mute (ADR 0039). + let speaker = layer.has_sounds().then(|| toggle(if onion_t.is_some() { 4.0 } else { 3.0 })); + let hover = ui.input(|inp| inp.pointer.hover_pos()); + for r in [eye, lock, outl].into_iter().take(if is_camera { 2 } else { 3 }).chain(onion_t).chain(speaker) { if hover.is_some_and(|h| r.contains(h)) { painter.rect_filled(r, T.rc(), T.hover); } @@ -437,12 +508,24 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let c_on = T.text; let c_off = T.text_faint; // eye and lock (state shows in the glyph and its brightness) - let glyph = |r: Rect| Rect::from_center_size(r.center(), vec2(15.0, 15.0)); + let glyph = |r: Rect| { + let s = r.height().min(15.0); + Rect::from_center_size(r.center(), vec2(s, s)) + }; icons::paint(&painter, glyph(eye), if layer.visible { Icon::Eye } else { Icon::EyeOff }, if layer.visible { c_on } else { c_off }); icons::paint(&painter, glyph(lock), if layer.locked { Icon::Lock } else { Icon::Unlock }, if layer.locked { c_on } else { c_off }); if let Some(sp) = speaker { icons::paint(&painter, glyph(sp), if layer.muted { Icon::SoundOff } else { Icon::Sound }, if layer.muted { T.accent_text } else { c_off }); } + // Onion skin for this layer (ADR 0061): bright while onion skin is on and draws it, + // faint while onion skin is off, struck through when the layer is left out. + if let Some(ot) = onion_t { + let g = glyph(ot); + icons::paint(&painter, g, Icon::Onion, if layer.onion && app.onion.ghosts { c_on } else { c_off }); + if !layer.onion { + painter.line_segment([g.left_bottom(), g.right_top()], Stroke::new(1.5, c_off)); + } + } // outline swatch let sw = Rect::from_center_size(outl.center(), vec2(10.0, 10.0)); if is_camera { @@ -453,7 +536,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } else { painter.rect_filled(sw, 0.0, to_color32(layer.color)); } - let name_rect = Rect::from_min_max(left.left_top(), pos2(speaker.unwrap_or(eye).left() - 4.0, left.bottom())); + let name_rect = Rect::from_min_max(left.left_top(), pos2(speaker.or(onion_t).unwrap_or(eye).left() - 4.0, left.bottom())); let nr = ui.interact(name_rect, ui.id().with(("lname", layer.id.0)), Sense::click()); // Screen readers hear the row as a selectable item, "Ball · layer", then its toggles. let name = &layer.name; @@ -476,10 +559,46 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { for (r, id, salt, label, on) in [(eye, "layer.toggle_visible", "eye", tr!("Show {name}", name = name), layer.visible), (lock, "layer.toggle_lock", "lock", tr!("Lock {name}", name = name), layer.locked), (outl, "layer.toggle_outline", "outline", tr!("Outline {name}", name = name), layer.outline)].into_iter().take(if is_camera { 2 } else { 3 }) { let rr = ui.interact(r, ui.id().with((salt, layer.id.0)), Sense::click()); a11y::control(ui, &rr, WidgetType::Checkbox, &label, Some(on)); + let rr = if salt == "outline" { rr.on_hover_text(tr!("View as outlines in the layer's colour (on the stage only)")) } else { rr }; if rr.clicked() { app.run(id, json!({"layer": layer.id.0})); } } + if let Some(ot) = onion_t { + let rr = ui.interact(ot, ui.id().with(("onion", layer.id.0)), Sense::click()); + a11y::control(ui, &rr, WidgetType::Checkbox, &tr!("Onion skin {name}", name = name), Some(layer.onion)); + if rr.on_hover_text(tr!("Onion skin this layer (Alt-click: this layer only, again: every layer)")).clicked() { + let solo = ui.input(|inp| inp.modifiers.alt); + if let Some(v) = app.run("layer.set_onion", json!({"layer": layer.id.0, "solo": solo})) { + if !app.onion.ghosts { + app.status_ok(tr!("Onion skin is off: turn it on in the timeline header to see the frames around the playhead")); + } else if solo { + let all = v["onion_layers"].as_array().map_or(0, Vec::len) > 1; + app.status_ok(if all { tr!("Onion skin on every layer again").to_string() } else { tr!("Onion skin on {name} only (Alt-click it again for every layer)", name = name) }); + } + } + } + } + // The colour chip on the row's edge: a click opens the layer's colour (ADR 0061). + let chip = Rect::from_min_size(left.left_top(), vec2(8.0, rh)); + let chip_r = ui.interact(chip, ui.id().with(("lcolor", layer.id.0)), Sense::click()); + a11y::control(ui, &chip_r, WidgetType::Button, &tr!("Colour of {name}", name = name), None); + if chip_r.hovered() { + painter.rect_filled(Rect::from_min_size(left.left_top(), vec2(7.0, rh)), 0.0, to_color32(layer.color)); + } + let chip_r = chip_r.on_hover_text(tr!("Layer colour: its outlines and its bar on the timeline")); + let menu_id = egui::Id::new(("layer_colour", layer.id.0)); + if app.tl_color_open == Some(layer.id) { + app.tl_color_open = None; + egui::Popup::open_id(ui.ctx(), menu_id); + } + let shown = egui::Popup::menu(&chip_r).id(menu_id).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| color_menu(app, ui, layer.id, layer.color)); + if let Some(r) = shown { + ui.ctx().accesskit_node_builder(r.response.id, |node| { + node.set_role(egui::accesskit::Role::Menu); + node.set_label(tr!("Layer colour")); + }); + } if let Some(sp) = speaker { let rr = ui.interact(sp, ui.id().with(("mute", layer.id.0)), Sense::click()); a11y::control(ui, &rr, WidgetType::Checkbox, &tr!("Mute {name}", name = layer.name), Some(layer.muted)); @@ -496,7 +615,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.run("layer.select", json!({"layer": layer.id.0})); } if nr.double_clicked() { - app.invoke("layer.rename"); + // On the layer's icon: Layer Properties, as in Animate; on its name: rename. + if nr.interact_pointer_pos().is_some_and(|p| icon_rect.contains(p)) { + crate::layer_props::open(app, Some(layer.id)); + } else { + app.invoke("layer.rename"); + } } // The folder chevron opens and closes the folder (on top of the name's click target). if is_folder { @@ -513,6 +637,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { for id in ["layer.rename", "layer.toggle_visible", "layer.toggle_lock"] { menus::cmd_item(app, ui, id); } + if ui.button(tr!("Properties…")).clicked() { + crate::layer_props::open(app, Some(layer.id)); + ui.close(); + } ui.separator(); if ui.button(tr!("Preview Through Camera")).clicked() { app.toggle_camera_preview(); @@ -534,6 +662,20 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if layer.has_sounds() && menus::check_item(ui, tr!("Mute"), layer.muted, true) { app.run("layer.toggle_mute", json!({"layer": layer.id.0})); } + if !is_folder && menus::check_item(ui, tr!("Onion Skin"), layer.onion, true) { + app.run("layer.set_onion", json!({"layer": layer.id.0})); + } + ui.menu_button(tr!("Layer Height"), |ui| { + for h in 1..=anicraft_engine::doc::MAX_LAYER_HEIGHT { + if menus::check_item(ui, &format!("{} %", u32::from(h) * 100), layer.height() == h, true) { + app.run("layer.set_height", json!({"layer": layer.id.0, "height": u32::from(h) * 100})); + } + } + }); + if ui.button(tr!("Properties…")).clicked() { + crate::layer_props::open(app, Some(layer.id)); + ui.close(); + } ui.separator(); // Layer type, as check items: Mask (masks the layer below) and Masked. if menus::check_item(ui, tr!("Mask"), layer.kind == LayerKind::Mask, !is_folder) { @@ -564,7 +706,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { }); // frame cells - let cells = Rect::from_min_max(pos2(grid.left(), y), pos2(grid.right(), y + ROW_H)); + let cells = Rect::from_min_max(pos2(grid.left(), y), pos2(grid.right(), y + rh)); let cp = painter.with_clip_rect(cells); if is_folder { // A folder has no frames: its row is a plain band across the timeline. @@ -581,11 +723,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { for f in first..first + visible_cols + 1 { let x = x_of(f); if (f + 1) % 5 == 0 && cell_w >= 6.0 { - cp.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell_w, ROW_H)), 0.0, Color32::from_white_alpha(6)); + cp.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell_w, rh)), 0.0, Color32::from_white_alpha(6)); } // Cell lines thin out with the ruler when zoomed out, so rows never turn to hatching. if (f + 1) % minor == 0 { - cp.line_segment([pos2(x + cell_w - 0.5, y), pos2(x + cell_w - 0.5, y + ROW_H)], Stroke::new(1.0, T.separator)); + cp.line_segment([pos2(x + cell_w - 0.5, y), pos2(x + cell_w - 0.5, y + rh)], Stroke::new(1.0, T.separator)); } } // Spans are solid square blocks, separated by a one-pixel gap rather than outlines: @@ -596,7 +738,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } let x0 = x_of(k.start); let x1 = x_of(k.end()); - let span = Rect::from_min_max(pos2(x0, y + 3.0), pos2(x1 - 1.0, y + ROW_H - 3.0)); + let span = Rect::from_min_max(pos2(x0, y + 3.0), pos2(x1 - 1.0, y + rh - 3.0)); let next_adjacent = layer.keyframes.get(ki + 1).is_some_and(|n| n.start == k.end()); let motion = k.motion.as_ref(); let tweened = k.tween.is_some() && next_adjacent && motion.is_none(); @@ -620,7 +762,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Still decoding (just opened): draw it when it's ready. ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); } - let kc = pos2(x0 + cell_w * 0.5, y + ROW_H * 0.5); + let kc = pos2(x0 + cell_w * 0.5, y + rh * 0.5); if let Some(m) = motion { // Property keyframes: small diamonds where any property has a key. A frame a // motion path point is pinned to (ADR 0049) has a larger one with a hole, as the @@ -671,7 +813,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { && sel.rows(&layers).is_some_and(|(a, b)| i >= a && i <= b) { let (f0, f1) = sel.frames(); - let r = Rect::from_min_max(pos2(x_of(f0), y + 1.0), pos2(x_of(f1 + 1) - 1.0, y + ROW_H - 1.0)); + let r = Rect::from_min_max(pos2(x_of(f0), y + 1.0), pos2(x_of(f1 + 1) - 1.0, y + rh - 1.0)); cp.rect_filled(r, SQUARE, T.selection.gamma_multiply(0.28)); cp.rect_stroke(r, SQUARE, Stroke::new(2.0, T.selection), StrokeKind::Inside); } @@ -684,7 +826,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { && src <= b as i64 { let (f0, f1) = sel.frames(); - let g = Rect::from_min_max(pos2(x_of(f0), y + 1.0), pos2(x_of(f1 + 1) - 1.0, y + ROW_H - 1.0)).translate(vec2(by as f32 * cell_w, 0.0)); + let g = Rect::from_min_max(pos2(x_of(f0), y + 1.0), pos2(x_of(f1 + 1) - 1.0, y + rh - 1.0)).translate(vec2(by as f32 * cell_w, 0.0)); cp.rect_stroke(g, SQUARE, Stroke::new(2.0, Color32::WHITE), StrokeKind::Inside); } // Span length being dragged on this row: the new end line and its length readout. @@ -693,14 +835,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { { // The frames gained (or given up), so the change reads as part of the span. let (a, b) = (x_of(end.min(to)), x_of(end.max(to))); - let changed = Rect::from_min_max(pos2(a, y + 2.0), pos2(b - 1.0, y + ROW_H - 2.0)); + let changed = Rect::from_min_max(pos2(a, y + 2.0), pos2(b - 1.0, y + rh - 2.0)); cp.rect_filled(changed, SQUARE, if to > end { T.selection.gamma_multiply(0.35) } else { Color32::from_black_alpha(120) }); let x = x_of(to); - cp.line_segment([pos2(x, y + 1.0), pos2(x, y + ROW_H - 1.0)], Stroke::new(2.0, Color32::WHITE)); + cp.line_segment([pos2(x, y + 1.0), pos2(x, y + rh - 1.0)], Stroke::new(2.0, Color32::WHITE)); let n = to - start; let secs = n as f32 / app.s.doc.stage.fps.max(1.0); let label = trn!("{n} frame · {secs} s", "{n} frames · {secs} s", n, secs = format!("{secs:.2}")); - let at = pos2(x + 6.0, y + ROW_H * 0.5); + let at = pos2(x + 6.0, y + rh * 0.5); let galley = painter.layout_no_wrap(label, font(Type::DataSmall), T.text); let (w, h) = (galley.rect.width(), galley.rect.height()); let bg = Rect::from_min_size(at - vec2(3.0, h * 0.5 + 2.0), vec2(w + 6.0, h + 4.0)); @@ -765,7 +907,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let f = frame_at(p.x); match (app.tl_drag, app.frame_sel.as_mut()) { (TlDrag::Select, Some(sel)) => { - let r = ((p.y - rows_top) / ROW_H).floor().max(0.0) as usize + first_row; + let r = row_at(&heights, first_row, p.y - rows_top).max(first_row); let row = rows.get(r.min(rows.len().saturating_sub(1))).copied().unwrap_or(0); if let Some(l) = layers.get(row) { sel.head = (l.id, f); @@ -775,7 +917,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Never before frame 1, and only onto layers that exist. let by = (i64::from(f) - i64::from(grab)).max(-i64::from(sel.frames().0)); // The row under the pointer, as a layer index (rows skip closed folders). - let vis = (((p.y - rows_top) / ROW_H).floor() as i64 + first_row as i64).clamp(0, rows.len() as i64 - 1).max(0) as usize; + let vis = row_at(&heights, first_row, p.y - rows_top); let row = rows.get(vis).map_or(grab_row as i64, |&li| li as i64); let rows_by = match sel.rows(&layers) { Some((a, b)) => (row - grab_row as i64).clamp(-(a as i64), layers.len() as i64 - 1 - b as i64), @@ -993,6 +1135,90 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { sr.on_hover_text(tr!("Scroll the timeline (or Shift+wheel anywhere over it)")); } +/// The layer colour popup (a click on a layer's colour chip, ADR 0061): the layer colours as +/// swatches, and a picker for any other (a drag in it is one undo step). +fn color_menu(app: &mut App, ui: &mut egui::Ui, layer: LayerId, color: anicraft_engine::doc::Rgba) { + use anicraft_engine::doc::Rgba; + ui.set_min_width(200.0); + ui.label(text(Type::Caption, tr!("Layer colour"))); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + ui.set_max_width(6.0 * 24.0); + for hex in anicraft_engine::LAYER_COLORS { + let c = Rgba::hex(hex); + let (r, resp) = ui.allocate_exact_size(vec2(20.0, 20.0), Sense::click()); + ui.painter().rect_filled(r, T.rc(), to_color32(c)); + if c.to_hex() == color.to_hex() { + ui.painter().rect_stroke(r, T.rc(), Stroke::new(2.0, T.text), StrokeKind::Outside); + } else if resp.hovered() { + ui.painter().rect_stroke(r, T.rc(), Stroke::new(1.0, T.text_dim), StrokeKind::Outside); + } + a11y::control(ui, &resp, WidgetType::Button, &tr!("Layer colour {hex}", hex = c.to_hex()), Some(c.to_hex() == color.to_hex())); + if resp.clicked() { + app.run("layer.set_color", json!({"layer": layer.0, "color": c.to_hex()})); + } + } + }); + ui.separator(); + // Any other colour: typed as hex, or picked in Layer Properties. + ui.horizontal(|ui| { + let id = ui.id().with(("layer_hex", layer.0)); + let mut hex = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_else(|| color.to_hex()); + let r = with_type(ui, Type::Data, |ui| ui.add(egui::TextEdit::singleline(&mut hex).desired_width(72.0).char_limit(9))).named(tr!("Layer colour as hex")); + if r.changed() { + ui.data_mut(|d| d.insert_temp(id, hex.clone())); + } + if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + ui.data_mut(|d| d.remove::(id)); + let typed = if hex.starts_with('#') { hex.trim().to_string() } else { format!("#{}", hex.trim()) }; + app.run("layer.set_color", json!({"layer": layer.0, "color": typed})); + } + if ui.button(tr!("More…")).on_hover_text(tr!("Pick any colour in Layer Properties")).clicked() { + crate::layer_props::open(app, Some(layer)); + ui.close(); + } + }); +} + +const FRAME_VIEW_MENU: &str = "tl_frame_view"; + +/// The timeline's Frame View menu (ADR 0061), as in Animate: frame widths Tiny to Large (the +/// zoom slider beside it sets any width between) and Short rows. View state. +fn frame_view_button(app: &mut App, ui: &mut egui::Ui) { + let id = egui::Id::new(FRAME_VIEW_MENU); + let (rect, resp) = ui.allocate_exact_size(vec2(TARGET, TARGET), Sense::click()); + let hot = resp.hovered() || egui::Popup::is_id_open(ui.ctx(), id); + ui.painter().rect_filled(rect, T.rc(), if hot { T.header } else { Color32::TRANSPARENT }); + icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), Icon::Layer, if hot { T.icon_hot } else { T.icon }); + a11y::control(ui, &resp, WidgetType::Button, tr!("Frame view"), None); + let resp = resp.on_hover_text(tr!("Frame view: frame width and row height")); + if std::mem::take(&mut app.tl_frame_view_open) { + egui::Popup::open_id(ui.ctx(), id); + } + let shown = egui::Popup::menu(&resp).id(id).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_min_width(160.0); + for (name, w) in FRAME_WIDTHS { + if menus::check_item(ui, crate::i18n::t(name), (app.tl_cell_w - w).abs() < 0.01, true) { + app.tl_cell_w = w; + } + } + ui.separator(); + if menus::check_item(ui, tr!("Short"), app.prefs.timeline_short_rows, true) { + let mut p = app.prefs.clone(); + p.timeline_short_rows = !p.timeline_short_rows; + let ctx = ui.ctx().clone(); + app.set_prefs(&ctx, p); + } + }); + // egui leaves the popup's own surface without a role or name. + if let Some(r) = shown { + ui.ctx().accesskit_node_builder(r.response.id, |node| { + node.set_role(egui::accesskit::Role::Menu); + node.set_label(tr!("Frame view")); + }); + } +} + /// Engine param for an easing preset. /// A keyframe's sound over its span: the waveform from the keyframe on, repeated as the sound /// repeats, as far as the span reaches (all a stream sound plays; an event sound plays on past @@ -1194,6 +1420,41 @@ mod tests { (1..=n).map(|i| Arc::new(Layer::new(LayerId(i), format!("L{i}")))).collect() } + #[test] + fn rows_take_their_layer_height_and_scroll_by_whole_rows() { + // A normal row, a 300 % row, two normal rows; 100 points to show them in. + let h = [28.0, 84.0, 28.0, 28.0]; + assert_eq!(rows_fitting(&h, 0, 100.0), 1, "the tall row doesn't fit after the first"); + assert_eq!(rows_fitting(&h, 1, 100.0), 1); + assert_eq!(rows_fitting(&h, 2, 100.0), 2); + assert_eq!(rows_fitting(&h, 1, 10.0), 1, "a row taller than the space still shows"); + assert_eq!(rows_fitting(&h, 4, 100.0), 0); + // Scrolled to the end, the last rows fill the space; a row is brought into view from above. + assert_eq!(max_first_row(&h, 100.0), 2); + assert_eq!(max_first_row(&h, 1000.0), 0, "everything fits: no scrolling"); + assert_eq!(first_showing(&h, 1, 100.0), 1); + assert_eq!(first_showing(&h, 3, 60.0), 2); + assert_eq!(first_showing(&h, 0, 5.0), 0); + // The pointer: rows by their own heights, from the first row shown, and above it. + assert_eq!(row_at(&h, 0, 10.0), 0); + assert_eq!(row_at(&h, 0, 28.0), 1); + assert_eq!(row_at(&h, 0, 111.0), 1); + assert_eq!(row_at(&h, 0, 112.0), 2); + assert_eq!(row_at(&h, 2, 30.0), 3); + assert_eq!(row_at(&h, 0, 9999.0), 3, "below the last row: the last row"); + assert_eq!(row_at(&h, 2, -1.0), 1, "just above the first row shown: the tall row"); + assert_eq!(row_at(&h, 2, -90.0), 0); + assert_eq!(row_at(&h, 2, -9999.0), 0); + assert_eq!(row_at(&[], 0, 5.0), 0); + assert_eq!(max_first_row(&[], 50.0), 0); + // Short rows, and a 200 % short row is two of them. + assert!(base_row_h(true) < base_row_h(false)); + // The frame widths run Tiny to Large inside the zoom range, Normal at 100 %. + assert!(FRAME_WIDTHS.windows(2).all(|w| w[0].1 < w[1].1)); + assert!(FRAME_WIDTHS.iter().all(|(_, w)| CELL_RANGE.contains(w))); + assert_eq!(FRAME_WIDTHS[2].1, CELL_DEFAULT); + } + #[test] fn frame_rates_read_without_needless_decimals() { assert_eq!(fps_label(24.0), "24 fps"); From d047e64255153aa87f3dcb846bda43f52fb6493c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 16:43:10 -0700 Subject: [PATCH 054/192] docs: ADR 0061 timeline polish, roadmap and changelog (M1) --- CHANGELOG.md | 15 ++++++ docs/adr/0061-timeline-polish.md | 84 ++++++++++++++++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 2 +- 4 files changed, 100 insertions(+), 2 deletions(-) create mode 100644 docs/adr/0061-timeline-polish.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 65528a94..c434986b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +* **Timeline polish** (ADR 0061, M1). + * A **per-layer onion skin toggle** in each layer row (Alt-click: this layer only, again: + every layer). Layers left out show only their playhead frame; Edit Multiple Frames still + edits them. + * **View as Outlines** draws a layer's artwork as hairlines in its colour **on the stage + only**. Exports, Test Movie and the player draw it as it is (before, an outlined layer + exported as outlines). The **colour chip** on the row's edge opens the layer colour. + * **Onion skin inside a symbol edited in place** now also shows the parent timeline's frames + around it, dimmed. + * **Layer Height** 100 / 200 / 300 % (right-click menu), **Layer Properties** (double-click a + layer's icon, Properties… or Modify › Timeline), and a **Frame View** menu with frame widths + Tiny to Large and **Short** rows. + * Headless: `layer.set_onion`, `layer.set_color`, `layer.set_height`, `layer.set_properties`, + `layer.properties`. Saved in the document with defaults left out, so older files open as + before. XFL import reads a layer's height. * **Files from the desktop, recent files and a start screen** (ADR 0059, M8). * **Drop files onto the window**: `.anicraft`, `.fla` and `.xfl` open (asking first over unsaved work); SVG drawings, PNG and JPEG images and WAV, Ogg and MP3 sounds dropped on the diff --git a/docs/adr/0061-timeline-polish.md b/docs/adr/0061-timeline-polish.md new file mode 100644 index 00000000..11e9d4e5 --- /dev/null +++ b/docs/adr/0061-timeline-polish.md @@ -0,0 +1,84 @@ +# ADR 0061: Timeline polish: per-layer onion skin, outline mode, layer height, Layer Properties, frame view + +* Status: accepted (2026-11-11) +* Relates to: ADR 0047 / 0051 (onion skin), ADR 0045 (symbols edited in place), ADR 0004 + (destructive actions), ADR 0017 (plug-in policy), ADR 0022 (accessibility), ADR 0040 + (interface languages) + +## Context + +Artists coming from Animate expect the everyday timeline details around onion skin and layers: +leaving a background layer out of onion skin, seeing a layer as outlines in its colour, making a +sound or a busy layer's row taller, one dialog for a layer's settings, and frame width presets. +ADR 0047 and 0051 left per-layer onion toggles and onion frames of the timeline around an open +symbol as "not yet". Outline mode existed, but `doc::evaluate` applied it everywhere, so a layer +left in outline mode exported as hairlines. + +Behaviour was learned from Adobe's public help pages on layers, onion skinning and the timeline, +the public JSFL reference (`layer.height`: 100, 200 or 300) and from watching the program. +Nothing was copied. + +## Decision + +1. **What is saved in the document and what is view state.** Per-layer onion, outline, colour + and height belong to the layer (Animate saves them in the file; a background left out of onion + skin should stay out tomorrow). They are `Layer` fields with `#[serde(default)]` and skipped + at their defaults: `onion: bool` (default true) and `height` (rows, 1–3, read through + `Layer::height()` which clamps whatever a file says). Older files open unchanged. Frame width + and Short rows are view state in the shell; Short is kept in the preferences. +2. **Commands** (`crates/engine/src/cmds_layer.rs`, all undoable, plug-ins may call them): + `layer.set_onion {onion?, solo?, layer?}` (toggle, set, or Animate's Alt-click solo: this + layer alone; solo again on the only layer left on turns every layer back on; folders and the + camera are left alone), `layer.set_color`, `layer.set_height {height: 100|200|300}`, + `layer.set_properties` (Layer Properties: name, type, colour, outline, height, show, lock, + onion, every param checked before anything changes, one undo step) and `layer.properties` + (read). XFL import reads `heightMultiplier`. +3. **Onion skin per layer.** `onion::ghosted` also needs the layer's toggle. Edit Multiple Frames + does not: the toggle is about the faded frames, and hiding keyframes from a multi-frame edit + because of it would be surprising. +4. **Outline mode on the stage only.** The evaluation context has a `stage` flag: on for the + evaluations the stage edits with (`evaluate_scene`, `evaluate_timeline[_at]`), off for the + movie (`evaluate`, which every export draws, `evaluate_scene_camera`, the player and button hit + areas). So exports, the player, Test Movie and Preview Through Camera draw the artwork as it + is. *Rejected:* stripping outlines in each exporter. There are many and a new one would forget. +5. **Onion frames of the parent timeline.** `Front` (the open symbol in a stage picture) keeps + `parent: Option`, the timeline the symbol was opened from (without the instance), its + frame, placement and dim opacity. With onion skin on (not Edit Multiple Frames), + `display_list_inside` draws that timeline through `compose_timeline` too, every item in one + group at the dim opacity, so it fades as one, as the dimmed instance it replaces did. Relative + markers reach as many frames from the parent's frame; anchored markers (which name the symbol's + frames) reach as far as they do from the symbol's playhead. Only the timeline right under the + symbol gets onion frames; deeper ones stay still. The other picture layers are drawn one by + one, bottom up, so the open symbol stays in front. +6. **In the timeline** (`src/timeline.rs`, `src/layer_props.rs`): + * An onion column before the eye: bright while onion skin is on and draws the layer, faint + while it is off, struck through when the layer is left out. Alt-click solos. The layer's + right-click menu has Onion Skin too. + * The colour square toggles View as Outlines (as before, now with a tooltip). The colour + chip on the row's edge opens the layer colour: twelve swatches, a hex field and More… (Layer + Properties' full picker). It is an accessible popup. + * Every layer has its type's icon (normal layers get a new AniCraft icon, a row with a keyframe + and its span). Double-clicking the icon opens **Layer Properties**; double-clicking the name + still renames. Also on the right-click menu (Properties…) and Modify › Timeline. + * **Layer Height** 100 / 200 / 300 % on the right-click menu and in Layer Properties. Rows are + laid out by height (`rows_fitting`, `max_first_row`, `first_showing`, `row_at`), so + scrolling, bringing the active layer into view and dragging across rows follow the real + rows. + * **Frame View** menu beside the zoom slider: Tiny, Small, Normal, Medium, Large (frame widths + 4, 8, 12, 18, 28 points; the slider still sets anything between) and **Short** rows (20 + points; a 200 % layer is two short rows). + +## Consequences + +* A layer left in outline mode no longer exports as hairlines (a fix as much as a feature). +* Layer Properties and the per-layer toggles work headless, over the CLI and MCP. +* Short rows are below the 28-point target size. They are a deliberate choice for dense + timelines, as in Animate, and their toggles shrink with them. +* Measured: no new per-frame cost for scenes. With a symbol open in place and onion skin on, the + parent's onion frames are one more `compose_timeline` of the parent (the same cost as onion skin + on the scene). +* Not in this slice: + * a per-layer onion toggle on folders (toggling everything inside); + * onion frames of timelines deeper than the one right under the open symbol; + * Layer Properties for several layers at once, and its Transparency (layer alpha) option; + * a timeline Preview / Preview in Context frame view (thumbnails in frames); diff --git a/docs/adr/README.md b/docs/adr/README.md index 4806482d..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0061 | m1/timeline-polish (M1) | Timeline polish: per-layer onion, outline mode, layer height, Layer Properties, frame view | diff --git a/docs/roadmap.md b/docs/roadmap.md index 2667c570..872da249 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -10,7 +10,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---| | Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). | | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | -| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | +| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | From 1bddc735036b969d8f6714eb54e9859f60cdd5d1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 19:32:21 -0500 Subject: [PATCH 055/192] Add Help > Check for Updates and bump to 0.2.1 (M8) (#165) * feat(updates): add manual release checks and verified native updates (M8) * chore: bump version to 0.2.1 (M8) * fix(flatpak): honor the launcher version choices (M8) * fix(updates): preserve pending edits and report restart outcomes (M8) * test(updates): verify startup consumes helper failures once (M8) --- Cargo.lock | 581 +++++++++++++++++- Cargo.toml | 6 +- deny.toml | 8 + docs/legal/compliance.md | 9 +- .../ai.storyteller.anicraft.bundle.yml | 7 +- .../linux/flatpak/ai.storyteller.anicraft.yml | 7 +- src/app.rs | 21 + src/main.rs | 12 + src/menus.rs | 4 + src/updates.rs | 476 ++++++++++++++ tests/flatpak_updates.rs | 27 + 11 files changed, 1134 insertions(+), 24 deletions(-) create mode 100644 src/updates.rs create mode 100644 tests/flatpak_updates.rs diff --git a/Cargo.lock b/Cargo.lock index ee7175cb..40120ca7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -216,7 +216,7 @@ dependencies = [ [[package]] name = "anicraft" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-audio", "anicraft-doc", @@ -225,6 +225,7 @@ dependencies = [ "anicraft-gpu", "anicraft-render", "cpal", + "craft-update", "eframe", "egui", "fontdb", @@ -242,7 +243,7 @@ dependencies = [ [[package]] name = "anicraft-actions" -version = "0.2.0" +version = "0.2.1" dependencies = [ "serde", "serde_json", @@ -250,7 +251,7 @@ dependencies = [ [[package]] name = "anicraft-audio" -version = "0.2.0" +version = "0.2.1" dependencies = [ "lewton", "nanomp3", @@ -258,7 +259,7 @@ dependencies = [ [[package]] name = "anicraft-cli" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-engine", @@ -269,7 +270,7 @@ dependencies = [ [[package]] name = "anicraft-doc" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-actions", "anicraft-audio", @@ -282,7 +283,7 @@ dependencies = [ [[package]] name = "anicraft-engine" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -306,7 +307,7 @@ dependencies = [ [[package]] name = "anicraft-geom" -version = "0.2.0" +version = "0.2.1" dependencies = [ "serde", "serde_json", @@ -314,7 +315,7 @@ dependencies = [ [[package]] name = "anicraft-gpu" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -330,7 +331,7 @@ dependencies = [ [[package]] name = "anicraft-plugins" -version = "0.2.0" +version = "0.2.1" dependencies = [ "serde", "serde_json", @@ -341,7 +342,7 @@ dependencies = [ [[package]] name = "anicraft-render" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -354,7 +355,7 @@ dependencies = [ [[package]] name = "anicraft-svg" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -365,7 +366,7 @@ dependencies = [ [[package]] name = "anicraft-text" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-geom", "fontdb", @@ -375,7 +376,7 @@ dependencies = [ [[package]] name = "anicraft-xfl" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -388,7 +389,7 @@ dependencies = [ [[package]] name = "anicraft-xml" -version = "0.2.0" +version = "0.2.1" dependencies = [ "thiserror 2.0.21", ] @@ -614,6 +615,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.10.0" @@ -641,6 +648,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -944,6 +960,15 @@ dependencies = [ "libc", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "num-traits", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -998,6 +1023,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -1008,6 +1042,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -1021,7 +1065,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -1034,7 +1078,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] @@ -1097,6 +1141,40 @@ dependencies = [ "windows-core", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "craft-update" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a#6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a" +dependencies = [ + "chrono", + "dunce", + "flate2", + "getrandom 0.3.4", + "log", + "plist", + "rustix 1.1.5", + "semver", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "ureq", + "verifysign", + "winreg", + "winsafe", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -1137,6 +1215,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1169,6 +1257,16 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1228,6 +1326,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dynify" version = "0.1.2" @@ -1352,6 +1456,7 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", + "webbrowser", "winit", ] @@ -1546,6 +1651,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -1630,6 +1745,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -1707,6 +1831,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1717,6 +1851,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1736,8 +1881,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", + "wasm-bindgen", ] [[package]] @@ -1949,6 +2096,22 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "icu_collections" version = "2.0.0" @@ -2038,6 +2201,27 @@ dependencies = [ "zerovec", ] +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "image" version = "0.25.10" @@ -2452,6 +2636,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2929,6 +3125,12 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "orbclient" version = "0.3.55" @@ -3104,6 +3306,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", +] + [[package]] name = "png" version = "0.17.16" @@ -3255,6 +3470,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -3459,6 +3683,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -3506,6 +3744,80 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3527,6 +3839,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -3539,6 +3860,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3550,6 +3894,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "serde" @@ -3614,6 +3962,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3807,6 +4166,12 @@ dependencies = [ "serde", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -3875,6 +4240,16 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -4116,6 +4491,18 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -4151,6 +4538,53 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + [[package]] name = "utf16_iter" version = "1.1.0" @@ -4160,6 +4594,21 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + [[package]] name = "utf_types" version = "1.0.0" @@ -4204,6 +4653,16 @@ dependencies = [ "vello_common", ] +[[package]] +name = "verifysign" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6efd25aadc22c756a9012267fae0b130278d335d6ceb512ec02ce82029b5ca9" +dependencies = [ + "core-foundation 0.10.1", + "windows-sys 0.61.2", +] + [[package]] name = "version_check" version = "0.9.5" @@ -4220,6 +4679,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -4536,7 +5001,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml", + "quick-xml 0.41.0", "quote", ] @@ -4572,6 +5037,31 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4986,7 +5476,7 @@ dependencies = [ "calloop 0.13.0", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -5031,6 +5521,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + [[package]] name = "winresource" version = "0.1.34" @@ -5041,6 +5541,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "winsafe" +version = "0.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -5292,6 +5798,26 @@ dependencies = [ "synstructure 0.14.0", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerotrie" version = "0.2.5" @@ -5327,6 +5853,25 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zip" +version = "9.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/Cargo.toml b/Cargo.toml index a6b981d9..fbd86a5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ default-members = [".", "crates/*"] [workspace.package] # 0.1.0 is the early alpha (release stage in src/app.rs, RELEASE_STAGE); see CHANGELOG.md # and docs/release.md. -version = "0.2.0" +version = "0.2.1" edition = "2024" license = "MIT OR Apache-2.0" # An application, not a library: not published to crates.io. @@ -107,7 +107,9 @@ web-time.workspace = true sys-locale = "0.3" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -eframe.workspace = true +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a" } + +eframe = { workspace = true, features = ["links"] } rfd.workspace = true # Sound output (Apache-2.0): WASAPI on Windows, CoreAudio on macOS, ALSA on Linux and the BSDs. cpal = { version = "0.18", optional = true } diff --git a/deny.toml b/deny.toml index d0de3539..1e0d8b9a 100644 --- a/deny.toml +++ b/deny.toml @@ -29,6 +29,12 @@ confidence-threshold = 0.93 crate = "epaint_default_fonts" allow = ["OFL-1.1", "Ubuntu-font-1.0"] +# Approved for the Mozilla certificate data pulled in by the shared HTTPS updater. +# The exception applies to this data crate and version, not application code. +[[licenses.exceptions]] +crate = "webpki-root-certs@=1.0.12" +allow = ["CDLA-Permissive-2.0"] + [licenses.private] # Our own workspace crates are MIT OR Apache-2.0 (checked by `cargo deny` like any other crate). ignore = false @@ -42,6 +48,8 @@ allow-wildcard-paths = true [sources] unknown-registry = "deny" unknown-git = "deny" +# Shared updater implementation, pinned to a reviewed commit in Cargo.toml. +allow-git = ["https://github.com/storytold/craft-libs"] allow-registry = ["https://github.com/rust-lang/crates.io-index"] [advisories] diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index 78020825..4ba95ee9 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -21,8 +21,13 @@ AniCraft is **MIT OR Apache-2.0**, the same as its sibling PhotoCraft (`LICENSE- Allowed: MIT, Apache-2.0 (incl. LLVM exception), BSD-2/3-Clause, ISC, Zlib, 0BSD, BSL-1.0, Unicode-3.0, Unlicense. Font licences (OFL-1.1, Ubuntu-font-1.0) are allowed **only** for `epaint_default_fonts`. Copyleft (GPL, LGPL, AGPL, MPL, EPL, CDDL, SSPL), "non-commercial", -"source-available" and unknown licences are **not allowed**. Only crates.io sources are allowed -(no unknown registries or git). +"source-available" and unknown licences are **not allowed**. Crates.io and the explicitly allowlisted Storytold shared library repository are allowed; +unknown registries and git sources remain denied. The native update checker uses `craft-update` +(MIT OR Apache-2.0), pinned to a commit of `storytold/craft-libs`; its HTTP, verification and +platform installer code are shared with the other Craft apps. A narrowly approved exception +accepts `webpki-root-certs` 1.0.12 under CDLA-Permissive-2.0 for Mozilla certificate data pulled +in by the HTTPS verifier. It applies only to that data crate and version; the code licence +allowlist is unchanged. ```sh cargo deny check licenses bans sources # policy in deny.toml; must pass before every commit diff --git a/packaging/linux/flatpak/ai.storyteller.anicraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.anicraft.bundle.yml index eed68ae1..5bfbc941 100644 --- a/packaging/linux/flatpak/ai.storyteller.anicraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.anicraft.bundle.yml @@ -17,6 +17,12 @@ runtime-version: '26.08' sdk: org.freedesktop.Sdk command: anicraft finish-args: + # Honor the launcher's pinned and nightly version choices before offering updates. + - --filesystem=xdg-data/ArtCraft/versions:ro + # Release checks and downloads use HTTPS. + - --share=network + # Verified update helpers run through flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland - --socket=fallback-x11 @@ -33,7 +39,6 @@ finish-args: - --filesystem=xdg-documents - --filesystem=xdg-pictures - --filesystem=xdg-videos - # Deliberately not granted: network (AniCraft never uses it) and home/host filesystem access. modules: - name: anicraft buildsystem: simple diff --git a/packaging/linux/flatpak/ai.storyteller.anicraft.yml b/packaging/linux/flatpak/ai.storyteller.anicraft.yml index d99fa96a..5a3f11ce 100644 --- a/packaging/linux/flatpak/ai.storyteller.anicraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.anicraft.yml @@ -19,6 +19,12 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: anicraft finish-args: + # Honor the launcher's pinned and nightly version choices before offering updates. + - --filesystem=xdg-data/ArtCraft/versions:ro + # Release checks and downloads use HTTPS. + - --share=network + # Verified update helpers run through flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland - --socket=fallback-x11 @@ -35,7 +41,6 @@ finish-args: - --filesystem=xdg-documents - --filesystem=xdg-pictures - --filesystem=xdg-videos - # Deliberately not granted: network (AniCraft never uses it) and home/host filesystem access. build-options: append-path: /usr/lib/sdk/rust-stable/bin modules: diff --git a/src/app.rs b/src/app.rs index 6ab5ed0e..877bdd25 100644 --- a/src/app.rs +++ b/src/app.rs @@ -277,6 +277,8 @@ pub const SHOT_FRAMES: u32 = 120; pub use anicraft_engine::doc::LibraryItem; pub struct App { + #[cfg(not(target_arch = "wasm32"))] + pub(crate) updates: crate::updates::Updates, pub s: Session, pub tool: Tool, pub view: StageView, @@ -462,6 +464,12 @@ pub const VIEW_SHORTCUTS: &[(&str, &str)] = &[ ]; impl App { + /// Show the last update's result once the native window begins drawing. + #[cfg(not(target_arch = "wasm32"))] + pub fn show_update_outcome_on_start(&mut self) { + self.updates.startup(); + } + pub fn new(cc: &eframe::CreationContext<'_>, session: Session, shot: Option) -> App { #[cfg_attr(not(gpu_stage), allow(unused_mut))] let mut app = App::with_context(&cc.egui_ctx, session, shot); @@ -495,6 +503,8 @@ impl App { // The editor draws as Animate does: merge drawing, until Object Drawing (J) is switched on. session.style.object_drawing = false; let mut app = App { + #[cfg(not(target_arch = "wasm32"))] + updates: Default::default(), s: session, tool: Tool::Select, view: StageView { zoom: 1.0, pan: egui::Vec2::ZERO, fit: true, fitted: None }, @@ -794,6 +804,8 @@ impl App { let last = self.s.doc.scenes.len().saturating_sub(1); self.run("scene.select", json!({"scene": last})); } + #[cfg(not(target_arch = "wasm32"))] + Some("updates") => self.updates.request(), Some("files") => self.show_files = true, Some("start") => { // The start screen with sample recent files (one pinned, one missing). @@ -2337,6 +2349,8 @@ impl eframe::App for App { fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { let clean = !self.s.is_dirty() || self.allow_close || self.shot.is_some(); self.recovery.finish(&self.s, clean); + #[cfg(not(target_arch = "wasm32"))] + self.updates.finish(); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { @@ -2348,6 +2362,13 @@ impl App { /// One frame of the whole interface. Needs no window, so tests run it headless. pub fn frame(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); + #[cfg(not(target_arch = "wasm32"))] + { + let safe = crate::updates::safe_to_install(self); + if self.updates.show(&ctx, safe) { + return; + } + } self.handle_screenshot(&ctx); self.poll_font_scan(&ctx); if let Some(p) = platform::picked_file() { diff --git a/src/main.rs b/src/main.rs index 97cbaeac..516f306a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,6 +40,8 @@ mod icons; mod keymap; mod library; mod menus; +#[cfg(not(target_arch = "wasm32"))] +mod updates; mod mixed; mod motion_editor; mod movie_explorer; @@ -121,6 +123,9 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o Box::new(move |cc| { let starting_fresh = file_given.is_none() && shot.is_none(); let mut a = app::App::new(cc, session, shot); + if a.shot.is_none() { + a.show_update_outcome_on_start(); + } // No document to open: the start screen, unless it was switched off (ADR 0059). if starting_fresh && a.prefs.start_screen { start::open(&mut a); @@ -145,6 +150,13 @@ fn main() { #[cfg(not(target_arch = "wasm32"))] fn main() -> eframe::Result { + if let Some(result) = updates::finish_helper() { + let failed = result.is_err(); + if let Err(error) = result { + eprintln!("Update failed: {error}"); + } + std::process::exit(i32::from(failed)); + } let mut shot: Option = None; let mut file: Option = None; let mut open: Option = None; diff --git a/src/menus.rs b/src/menus.rs index 7fc8e8fd..15cc5806 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -282,6 +282,10 @@ pub(crate) fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: & ui.label(text(Type::Caption, tr!("Panels are docked: Tools, Stage, Timeline, Properties, Library and Movie Explorer"))); } "Help" => { + #[cfg(not(target_arch = "wasm32"))] + if ui_item(ui, tr!("Check for Updates…"), "", None) { + app.updates.check(ui.ctx()); + } if ui_item(ui, tr!("Command Palette…"), "Ctrl+K", None) { app.palette = Some(crate::dialogs::Palette::default()); } diff --git a/src/updates.rs b/src/updates.rs new file mode 100644 index 00000000..1a85ec82 --- /dev/null +++ b/src/updates.rs @@ -0,0 +1,476 @@ +//! Native release checks and verified installation through craft-update's platform helpers. +use craft_update::pins::{Choice, Pins}; +use craft_update::{App, Http, Paths, Platform, Release, Stop, self_update}; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; + +// i18n-exempt: stable release identity, not interface text. +pub const APP: App = App::new("anicraft", "AniCraft", "Animation", "storytold/anicraft"); +const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// A pinned, nightly, or unknown launcher choice must never be replaced by a stable update. +fn stable_choice() -> Result<(), String> { + if Pins::load_default().choice(APP.id) == Choice::Stable { + Ok(()) + } else { + Err(tr!("ArtCraft Launcher manages this app's version. Change its version there.").into()) + } +} + +/// Whether an update may close the editor without losing pending document work. +pub(crate) fn safe_to_install(app: &crate::app::App) -> bool { + !app.s.is_dirty() + && !app.s.in_gesture() + && !app.playing + && app.text_edit.is_none() + && app.pen.is_none() + && app.pencil.is_empty() + && app.brush_samples.is_empty() + && app.raw_touched.is_empty() + && app.drag == crate::app::Drag::None + && app.motion_drag.is_none() + && app.tl_drag == crate::timeline::TlDrag::None + && app.me_drag.is_none() + && app.plugin_dialog.is_none() + && app.envelope.is_none() +} + +enum Reply { + Checked(Result, String>, bool), + Installed(Result), +} +#[derive(Default)] +pub struct Updates { + open: bool, + read_outcome_requested: bool, + requested: bool, + message: String, + release: Option, + installable: bool, + worker: Option>, + installing: bool, + restart: Option, +} +impl Updates { + /// Read the previous update result when the first desktop frame can show it. + pub fn startup(&mut self) { + self.read_outcome_requested = true; + } + + /// Queue a check from the command-line panel selector. + pub fn request(&mut self) { + self.requested = true; + } + + /// Start a manual check off the UI thread; repeated requests share the running check. + pub fn check(&mut self, ctx: &egui::Context) { + self.check_using(ctx, || { + let result = stable_choice() + .and_then(|()| Http::new(concat!("AniCraft/", env!("CARGO_PKG_VERSION")))) + .and_then(|http| craft_update::check_for_update(&APP, &http, VERSION)); + let installable = result + .as_ref() + .ok() + .and_then(|release| release.as_ref()) + .is_some_and(|release| self_update::is_self_updating(&APP) && self_update::release_installs(&APP, release)); + (result, installable) + }); + } + + fn check_using(&mut self, ctx: &egui::Context, check: impl FnOnce() -> (Result, String>, bool) + Send + 'static) { + self.open = true; + if self.worker.is_some() { + return; + } + self.message = tr!("Checking for updates…").into(); + self.release = None; + self.installable = false; + let (tx, rx) = channel(); + self.worker = Some(rx); + let ctx = ctx.clone(); + let result = std::thread::Builder::new().name("release-check".into()).spawn(move || { + let (result, installable) = check(); + let _ = tx.send(Reply::Checked(result, installable)); + ctx.request_repaint(); + }); + if let Err(error) = result { + self.worker = None; + self.message = error.to_string(); + } + } + fn install(&mut self, ctx: &egui::Context, release: Release) { + self.install_using(ctx, move || { + let install = self_update::current(&APP) + .ok_or(tr!("This installation is managed externally. Update it with its package manager or open Releases."))?; + let platform = Platform::current().ok_or(tr!("No installer is available for this platform."))?; + let http = Http::new(concat!("AniCraft/", env!("CARGO_PKG_VERSION")))?; + let paths = Paths::for_app(&APP)?; + self_update::prepare_update( + &APP, + &install, + &release, + platform, + &http, + &paths, + &Stop::default(), + &mut |_| {}, + &stable_choice, + Some(VERSION), + ) + }); + } + + fn install_using(&mut self, ctx: &egui::Context, install: impl FnOnce() -> Result + Send + 'static) { + self.installing = true; + self.message = tr!("Downloading and verifying the update…").into(); + let (tx, rx) = channel(); + self.worker = Some(rx); + let ctx = ctx.clone(); + let result = std::thread::Builder::new().name("release-install".into()).spawn(move || { + let result = install(); + let _ = tx.send(Reply::Installed(result)); + ctx.request_repaint(); + }); + if let Err(error) = result { + self.worker = None; + self.installing = false; + self.message = error.to_string(); + } + } + /// Returns true while installing: the caller pauses editing and starting work until restart. + pub fn show(&mut self, ctx: &egui::Context, safe_to_install: bool) -> bool { + if std::mem::take(&mut self.requested) { + self.check(ctx); + } + if std::mem::take(&mut self.read_outcome_requested) + && let Ok(paths) = Paths::for_app(&APP) + { + self.apply_outcome(self_update::take_outcome(&paths, VERSION)); + } + let reply = self.worker.as_ref().map(Receiver::try_recv); + match reply { + Some(Ok(Reply::Checked(result, installable))) => { + self.installable = installable; + self.worker = None; + self.checked(result); + } + Some(Ok(Reply::Installed(result))) => { + self.worker = None; + match result { + Ok(restart) => { + self.restart = Some(restart); + self.message = tr!("Update ready. Restarting…").into(); + } + Err(error) => { + self.installing = false; + self.message = error; + } + } + } + Some(Err(TryRecvError::Disconnected)) => { + self.worker = None; + self.installing = false; + self.message = tr!("The update worker stopped unexpectedly. Try checking again.").into(); + } + _ => {} + } + if self.restart.is_some() { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } else if self.installing && ctx.input(|i| i.viewport().close_requested()) { + // The platform helper may be replacing files. Keep this process alive until it finishes. + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + } + if self.worker.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + if self.open { + let mut open = true; + let mut install = false; + let mut again = false; + egui::Window::new(tr!("Check for Updates")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .default_width(440.0) + .max_width((ctx.content_rect().width() - 32.0).max(160.0)) + .show(ctx, |ui| { + ui.label(tr!("AniCraft {version}", version = VERSION)); + ui.label(&self.message); + if !safe_to_install && self.release.is_some() { + ui.label(tr!("Save your work and stop running tasks before installing an update.")); + } + if self.release.is_some() && !self.installable { + ui.label(tr!("Use Releases or your package manager to update this installation.")); + } + ui.horizontal(|ui| { + if let Some(release) = &self.release { + ui.hyperlink_to(tr!("Releases"), &release.html_url); + install = ui + .add_enabled( + safe_to_install && self.installable && self.worker.is_none() && self.restart.is_none(), + egui::Button::new(tr!("Update and restart")), + ) + .clicked(); + } else { + ui.hyperlink_to(tr!("Releases"), APP.releases_url()); + } + again = ui.add_enabled(self.worker.is_none() && !self.installing, egui::Button::new(tr!("Check again"))).clicked(); + }); + }); + self.open = open || self.installing; + if install && let Some(release) = self.release.clone() { + self.install(ctx, release); + } + if again { + self.check(ctx); + } + } + self.installing + } + fn apply_outcome(&mut self, outcome: Option) { + match outcome { + Some(self_update::Outcome::Installed(version)) => { + self.open = true; + self.message = tr!("Updated to {version}.", version = version); + } + Some(self_update::Outcome::Failed(error)) => { + self.open = true; + self.message = tr!("The update failed: {error}", error = error); + } + None => {} + } + } + + fn checked(&mut self, result: Result, String>) { + match result { + Ok(Some(release)) => { + self.message = tr!("{version} is available.", version = release.version_label()); + self.release = Some(release); + } + Ok(None) => { + self.message = tr!("You're up to date.").into(); + self.release = None; + } + Err(error) => { + self.message = tr!("Couldn't check for updates: {error}", error = error); + self.release = None; + } + } + } + /// Start the prepared helper only after the app's normal exit path has accepted closing. + pub fn finish(&mut self) { + if let Some(restart) = self.restart.take() + && let Err(error) = restart.start() + { + eprintln!("Couldn't restart after updating: {error}"); + } + } +} + +/// Runs the Windows installation helper before opening a normal application window. +pub fn finish_helper() -> Option> { + self_update::finish(&APP, &std::env::args_os().skip(1).collect::>()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn draw(updates: &mut Updates, safe: bool, close: bool) -> egui::FullOutput { + let ctx = egui::Context::default(); + let mut input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 400.0))), ..Default::default() }; + if close { + input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + } + let mut output = ctx.run_ui(input, |ui| { + updates.show(ui.ctx(), safe); + }); + output.textures_delta.clear(); + output + } + + #[test] + fn a_launcher_pin_stops_the_real_check_before_network_access() { + const CHILD: &str = "CRAFT_UPDATE_PIN_TEST_CHILD"; + if std::env::var_os(CHILD).is_some() { + assert!(stable_choice().is_err()); + let mut updates = Updates::default(); + updates.check(&egui::Context::default()); + let reply = updates + .worker + .as_ref() + .expect("check worker") + .recv_timeout(std::time::Duration::from_secs(5)) + .expect("pin check finishes without network"); + let (tx, rx) = channel(); + tx.send(reply).expect("receiver"); + updates.worker = Some(rx); + draw(&mut updates, true, false); + assert!(updates.message.contains("ArtCraft Launcher")); + assert!(updates.release.is_none()); + assert!(!updates.installable); + assert!(finish_helper().is_none()); + #[cfg(target_os = "linux")] + { + // This child has an isolated XDG data folder; never consume a user's update record. + let paths = Paths::for_app(&APP).expect("isolated app folders"); + std::fs::create_dir_all(paths.logs()).expect("test logs"); + let failure = paths.logs().join("self-update-error.txt"); + std::fs::write(&failure, "test installer failure").expect("test failure record"); + let mut restarted = Updates::default(); + restarted.startup(); + draw(&mut restarted, true, false); + assert!(restarted.open); + assert!(restarted.message.contains("test installer failure")); + assert!(!failure.exists(), "the helper result is consumed exactly once"); + restarted.open = false; + restarted.startup(); + draw(&mut restarted, true, false); + assert!(!restarted.open, "the old failure must not reappear on the next start"); + } + + return; + } + // Keep the process environment and the user's actual version choices untouched. + let dir = std::env::temp_dir().join(format!("{}-updater-pin-test-{}", APP.id, std::process::id())); + std::fs::create_dir_all(&dir).expect("test folder"); + let path = dir.join("versions.json"); + std::fs::write(&path, format!(r#"{{"apps":{{"{}":{{"Pinned":"0.1.0"}}}}}}"#, APP.id)).expect("test pin"); + let status = std::process::Command::new(std::env::current_exe().expect("test binary")) + .args(["--exact", "updates::tests::a_launcher_pin_stops_the_real_check_before_network_access"]) + .env(CHILD, "1") + .env(craft_update::pins::PATH_ENV, &path) + .env("XDG_DATA_HOME", dir.join("data")) + .status() + .expect("isolated pin test"); + std::fs::remove_dir_all(dir).expect("remove test folder"); + assert!(status.success()); + } + #[test] + fn available_release_is_shown_but_never_installed_without_confirmation() { + let release = Release { tag: "v99.0.0".into(), html_url: APP.releases_url(), ..Release::default() }; + let (tx, rx) = channel(); + tx.send(Reply::Checked(Ok(Some(release)), false)).expect("receiver is alive"); + let mut updates = Updates { open: true, worker: Some(rx), ..Updates::default() }; + let output = draw(&mut updates, false, false); + assert!(updates.message.contains("99.0.0")); + assert!(!output.shapes.is_empty(), "the result window must be rendered"); + assert!(updates.worker.is_none()); + assert!(!updates.installing); + assert!(!updates.installable, "externally managed installs must only offer Releases"); + updates.installable = true; + draw(&mut updates, true, false); + assert!(!updates.installing, "an available update alone must never install"); + } + + #[test] + fn checks_run_off_thread_and_repeated_requests_share_the_worker() { + let ctx = egui::Context::default(); + let (started, wait) = channel(); + let mut updates = Updates::default(); + updates.check_using(&ctx, move || { + wait.recv().expect("release test worker"); + (Ok(None), false) + }); + assert!(updates.worker.is_some()); + updates.check_using(&ctx, || panic!("must not start a second check")); + draw(&mut updates, false, false); + started.send(()).expect("worker waiting"); + let reply = updates.worker.as_ref().expect("worker").recv_timeout(std::time::Duration::from_secs(5)).expect("worker finishes"); + let (tx, rx) = channel(); + tx.send(reply).expect("receiver"); + updates.worker = Some(rx); + draw(&mut updates, true, false); + assert_eq!(updates.message, "You're up to date."); + assert!(updates.worker.is_none()); + } + + #[test] + fn an_install_failure_unlocks_editing_and_close_is_cancelled_until_it_finishes() { + let ctx = egui::Context::default(); + let (finish, wait) = channel(); + let mut updates = Updates { open: true, ..Updates::default() }; + updates.install_using(&ctx, move || { + wait.recv().expect("release test worker"); + Err("signature verification failed".into()) + }); + assert!(updates.installing); + let output = draw(&mut updates, false, true); + assert!(output.viewport_output.values().any(|v| v.commands.contains(&egui::ViewportCommand::CancelClose))); + finish.send(()).expect("worker waiting"); + let reply = updates.worker.as_ref().expect("worker").recv_timeout(std::time::Duration::from_secs(5)).expect("worker finishes"); + let (tx, rx) = channel(); + tx.send(reply).expect("receiver"); + updates.worker = Some(rx); + draw(&mut updates, false, false); + assert!(!updates.installing); + assert!(updates.worker.is_none()); + assert!(updates.restart.is_none(), "failed verification must never schedule a restart"); + assert!(updates.message.contains("signature verification failed")); + updates.finish(); + updates.apply_outcome(None); + } + #[test] + fn uncommitted_stage_text_and_pen_paths_prevent_installation() { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let mut app = crate::app::App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + assert!(!app.s.is_dirty()); + assert!(safe_to_install(&app)); + app.text_edit = Some(crate::app::TextEditing { + at: egui::Pos2::ZERO, + element: None, + text: "Uncommitted stage text".into(), + original: String::new(), + focus: false, + }); + assert!(!app.s.is_dirty(), "the edit has not reached Session yet"); + assert!(!safe_to_install(&app), "restarting would discard the text buffer"); + app.text_edit = None; + app.pen = Some(crate::pathtools::PenPath { knots: vec![[anicraft_engine::geom::Vec2::ZERO; 3]], dragging: false }); + assert!(!app.s.is_dirty()); + assert!(!safe_to_install(&app), "an unfinished Pen path is also pending work"); + app.pen = None; + assert!(safe_to_install(&app)); + app.s.begin_gesture("pending edit"); + assert!(!safe_to_install(&app), "an engine gesture must finish first"); + } + + #[test] + fn a_failed_helper_is_reported_when_the_old_app_restarts() { + let mut updates = Updates::default(); + updates.apply_outcome(Some(self_update::Outcome::Failed("installer refused the update".into()))); + assert!(updates.open); + assert!(updates.message.contains("installer refused the update")); + assert!(updates.worker.is_none()); + assert!(!updates.installing); + } + + #[test] + fn a_successful_restart_reports_the_installed_version() { + let mut updates = Updates::default(); + let version = craft_update::version::parse("1.2.3").expect("valid test version"); + updates.apply_outcome(Some(self_update::Outcome::Installed(version))); + assert!(updates.open); + assert!(updates.message.contains("1.2.3")); + } + + #[test] + fn a_manual_check_reports_success_and_failure() { + let mut updates = Updates::default(); + updates.checked(Ok(None)); + assert_eq!(updates.message, "You're up to date."); + updates.checked(Err("network unavailable".into())); + assert!(updates.message.contains("network unavailable")); + assert!(updates.release.is_none()); + } + #[test] + fn a_dropped_worker_reports_failure_and_unblocks_the_app() { + let (tx, rx) = channel(); + drop(tx); + let mut updates = Updates { worker: Some(rx), installing: true, ..Updates::default() }; + assert!(!updates.show(&egui::Context::default(), false)); + assert!(updates.message.contains("stopped unexpectedly")); + } +} diff --git a/tests/flatpak_updates.rs b/tests/flatpak_updates.rs new file mode 100644 index 00000000..292fbaf0 --- /dev/null +++ b/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../packaging/linux/flatpak/ai.storyteller.anicraft.bundle.yml"), + include_str!("../packaging/linux/flatpak/ai.storyteller.anicraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak", "--filesystem=xdg-data/ArtCraft/versions:ro"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} From b114d4adcd88155cd0dcde21fc0e8ba622198ac2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 17:04:14 -0700 Subject: [PATCH 056/192] docs(adr): reserve 0063 for animated PNG and WebP export (M4) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..0dd0bd2f 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0063 | m4/animated-png-webp | Animated PNG and animated WebP export | From a20a488fb6206a5955516158c459ae7aeaa9f044 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:03:12 -0700 Subject: [PATCH 057/192] feat(export): animated PNG and animated WebP export (M4) --- Cargo.lock | 11 + Cargo.toml | 2 + crates/cli/src/lib.rs | 22 +- crates/engine/Cargo.toml | 5 +- crates/engine/src/anim.rs | 502 ++++++++++++++++++++++++++++++ crates/engine/src/anim_tests.rs | 347 +++++++++++++++++++++ crates/engine/src/cmds_file.rs | 20 +- crates/engine/src/confirm.rs | 2 +- crates/engine/src/lib.rs | 1 + crates/engine/src/plugin_tests.rs | 2 + crates/engine/src/publish.rs | 30 +- crates/engine/src/web_tests.rs | 8 +- 12 files changed, 940 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/anim.rs create mode 100644 crates/engine/src/anim_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 40120ca7..7b834406 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -293,6 +293,7 @@ dependencies = [ "anicraft-text", "anicraft-xfl", "gif", + "image-webp", "miniz_oxide 0.8.9", "png 0.17.16", "rayon", @@ -2236,6 +2237,16 @@ dependencies = [ "tiff", ] +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "indexmap" version = "2.14.2" diff --git a/Cargo.toml b/Cargo.toml index fbd86a5a..a1a626b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,8 @@ png = "0.17" # JPEG decoding for imported images (already in the tree; MIT OR Apache-2.0 OR Zlib). zune-jpeg = { version = "0.5", default-features = false } gif = "0.14" +# Lossless WebP frames for animated WebP export (pure Rust, MIT OR Apache-2.0; ADR 0063). +image-webp = "0.2" # wgpu is the primary renderer; glow (OpenGL) is the fallback for GPUs/VMs where wgpu fails. # Default features off: we skip `links` (opening web links pulls in url/idna/ICU Unicode # tables we don't use) and the web-only screen-reader shim. Same set as PhotoCraft, plus glow. diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 42a4cc5b..a685d692 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -18,6 +18,9 @@ USAGE: anicraft-cli render --out [--frame N] [--scale S] anicraft-cli render-seq --out-dir [--from A] [--to B] [--scale S] anicraft-cli gif --out [--from A] [--to B] [--scale S] [--overwrite yes] + anicraft-cli apng|webp --out [--from A] [--to B] [--scale S] + [--loop forever|N] [--background yes] [--overwrite yes] + full colour with real transparency (WebP: lossless) anicraft-cli commands anicraft-cli run [--save ] anicraft-cli exec [] [--save ] @@ -148,9 +151,11 @@ pub fn run(argv: &[String]) -> Result { } exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string()) } - "gif" => { - let mut s = session(&a, Some(src.ok_or("gif needs a file or --sample")?))?; - let out = a.flag("out").ok_or("gif needs --out ")?; + "gif" | "apng" | "webp" => { + let mut s = session(&a, Some(src.ok_or(format!("{cmd} needs a file or --sample"))?))?; + let cmd = cmd.as_str(); + let ext = if cmd == "apng" { "png" } else { cmd }; + let out = a.flag("out").ok_or(format!("{cmd} needs --out "))?; let mut p = json!({"path": out}); if let Some(f) = one_based(&a, "from")? { p["from"] = json!(f); @@ -164,7 +169,16 @@ pub fn run(argv: &[String]) -> Result { if a.flag("overwrite").is_some_and(|v| v == "yes" || v == "true") { p["confirm"] = json!(true); } - exec(&mut s, "file.export_gif", &p).map(|v| v.to_string()) + if cmd != "gif" { + match a.flag("loop") { + None | Some("forever") => {} + Some(n) => p["loop"] = json!(n.parse::().map_err(|_| format!("--loop is forever or how many times it plays, not '{n}'"))?), + } + if a.flag("background").is_some_and(|v| v == "yes" || v == "true") { + p["background"] = json!(true); + } + } + exec(&mut s, &format!("file.export_{cmd}"), &p).map(|v| v.to_string()) } "new" => { let mut s = Session::default(); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 333dea00..f6d9eda8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -21,11 +21,12 @@ thiserror.workspace = true rayon.workspace = true web-time.workspace = true gif.workspace = true +# Animated PNG frames (ADR 0063; already in the tree through the renderer). +png.workspace = true +image-webp.workspace = true regex.workspace = true [dev-dependencies] -# Decodes exported sheets in tests (already in the tree through the renderer). -png.workspace = true # Packs the XFL corpus into .fla archives in tests (ADR 0054; already in the tree through xfl). miniz_oxide = "0.8" # Plug-in test fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception). diff --git a/crates/engine/src/anim.rs b/crates/engine/src/anim.rs new file mode 100644 index 00000000..b54c248e --- /dev/null +++ b/crates/engine/src/anim.rs @@ -0,0 +1,502 @@ +//! Animated PNG and animated WebP export (ADR 0063): full colour and real alpha, for the web +//! and chat apps, where an animated GIF has 256 colours and 1-bit transparency. +//! +//! Both formats share one pipeline. Frames render in parallel, a batch at a time (memory stays +//! bounded), as GIF export does. A frame identical to the one before it is merged into that +//! frame's delay. Every other frame is cut down to the rectangle that changed since the frame +//! before and compressed in parallel as an image of its own (a PNG, or a lossless WebP); the +//! compressed data is then put into one file in order, by hand, chunk by chunk: +//! +//! * **APNG** (the APNG specification): `IHDR`, `acTL`, then per frame an `fcTL` (its region, +//! delay, dispose op none, blend op) and its `IDAT` / `fdAT` data. Delays are exact fractions +//! of the document's frame rate (2 frames at 29.97 fps: 200/2997 s). A region whose changed +//! pixels are all opaque blends *over* the frame before, with its unchanged pixels left +//! transparent (they compress to almost nothing); otherwise it replaces (*source*). +//! * **WebP** (the WebP container specification): `VP8X`, `ANIM`, then an `ANMF` per frame +//! wrapping its `VP8L` (lossless) bitstream. Regions start on even pixels, as the format +//! needs, and replace what was there (no blending: the decoders' blend rounds opaque pixels). +//! Durations are whole milliseconds; each is rounded from the exact time the frame starts, so +//! the error never adds up and the running time is exact to the millisecond. +//! +//! A delay longer than one frame header can hold goes on, after the frame, as frames that +//! change nothing (one transparent pixel blended over), so timing is never cut short. + +use crate::params::*; +use crate::{EngineError, Result, Session}; +use anicraft_render::{View, render}; +use rayon::prelude::*; +use serde_json::{Value, json}; +use std::path::PathBuf; + +/// The two animated formats. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Apng, + Webp, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::Apng => "animated PNG", + Kind::Webp => "animated WebP", + } + } +} + +/// Largest animation made (frames × pixels), as for GIF: time stays bounded. +pub const MAX_ANIM_PIXELS: u64 = 600 * 1280 * 720; +/// WebP canvases and frames are at most 16384 px per side. +pub const MAX_WEBP_EDGE: u32 = 16_384; +/// Pixels rendered at once (a batch of frames), so memory stays bounded at any size. +const BATCH_PIXELS: u64 = 32 * 1024 * 1024; +/// Most plays a loop count says (both formats store it in 16 bits for WebP's sake). +pub const MAX_PLAYS: u32 = anicraft_doc::publish::MAX_PLAYS; +/// Longest WebP frame duration (24 bits of milliseconds). +const MAX_WEBP_MS: u64 = 0xFF_FFFF; + +/// A rectangle of the canvas, in pixels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub w: u32, + pub h: u32, +} + +/// One frame, compressed: the region it covers, whether it blends over what is there (else it +/// replaces it), and its image data (PNG `IDAT` data, or a whole `VP8L` chunk). +struct Encoded { + rect: Rect, + over: bool, + data: Vec, +} + +/// The frame rate as a fraction `p / q` frames per second: 24 → 24/1, 29.97 → 2997/100, +/// 23.976 → 2997/125. Rates no small fraction matches are taken to a thousandth. +pub fn fps_ratio(fps: f32) -> (u64, u64) { + let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 24.0 }; + for q in 1..=1001u64 { + let p = (fps * q as f64).round(); + if p >= 1.0 && (p / q as f64 - fps).abs() <= fps * 1e-6 { + return (p as u64, q); + } + } + let p = ((fps * 1000.0).round() as u64).max(1); + let g = gcd(p, 1000); + (p / g, 1000 / g) +} + +fn gcd(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +/// When frame `t` (from the first exported) starts, in whole milliseconds, rounded from the +/// exact time at `p / q` fps. +pub fn start_ms(t: u64, (p, q): (u64, u64)) -> u64 { + let p = u128::from(p.max(1)); + ((2 * u128::from(t) * 1000 * u128::from(q) + p) / (2 * p)) as u64 +} + +/// The APNG delays (numerator, denominator in seconds) of a frame shown from frame `start` for +/// `count` frames: one exact fraction, or more when it is longer than one `fcTL` holds. +pub fn apng_delays(start: u64, count: u64, (p, q): (u64, u64)) -> Vec<(u16, u16)> { + let mut out = Vec::new(); + if let Ok(den) = u16::try_from(p) { + // `count` frames last count·q/p s; pieces of at most 65535/q frames always fit. + let most = (u64::from(u16::MAX) / q.max(1)).max(1); + let mut left = count; + while left > 0 { + let m = left.min(most); + let (num, g) = (m * q, gcd(m * q, p)); + out.push((u16::try_from(num / g).unwrap_or(u16::MAX), u16::try_from(u64::from(den) / g).unwrap_or(den))); + left -= m; + } + } else { + // A rate with a huge denominator: milliseconds, rounded from each frame's start. + let mut ms = start_ms(start + count, (p, q)) - start_ms(start, (p, q)); + while ms > 0 { + let m = ms.min(u64::from(u16::MAX)); + out.push((m as u16, 1000)); + ms -= m; + } + } + if out.is_empty() { + out.push((0, 1)); + } + out +} + +/// The WebP durations (milliseconds) of a frame shown from frame `start` for `count` frames: +/// one, or more when it is longer than one `ANMF` holds. +pub fn webp_durations(start: u64, count: u64, ratio: (u64, u64)) -> Vec { + let mut ms = start_ms(start + count, ratio).saturating_sub(start_ms(start, ratio)); + let mut out = Vec::new(); + loop { + let m = ms.min(MAX_WEBP_MS); + out.push(m as u32); + ms -= m; + if ms == 0 { + return out; + } + } +} + +/// The smallest rectangle holding every pixel where RGBA8 images `a` and `b` (`w` × `h`) differ, +/// or `None` when they are the same. +pub fn changed(a: &[u8], b: &[u8], w: u32, h: u32) -> Option { + let stride = w as usize * 4; + let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0u32, 0u32); + for y in 0..h { + let at = y as usize * stride; + let (Some(ra), Some(rb)) = (a.get(at..at + stride), b.get(at..at + stride)) else { break }; + if ra == rb { + continue; + } + let (pa, pb) = (ra.as_chunks::<4>().0, rb.as_chunks::<4>().0); + let first = pa.iter().zip(pb).position(|(u, v)| u != v).unwrap_or(0) as u32; + let last = pa.iter().zip(pb).rposition(|(u, v)| u != v).unwrap_or(0) as u32; + x0 = x0.min(first); + x1 = x1.max(last); + y0 = y0.min(y); + y1 = y; + } + (y0 != u32::MAX).then(|| Rect { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 }) +} + +/// Rectangle `r` of RGBA8 image `px` (`w` wide). +fn crop(px: &[u8], w: u32, r: Rect) -> Vec { + let stride = w as usize * 4; + let mut out = Vec::with_capacity(r.w as usize * r.h as usize * 4); + for y in r.y..r.y + r.h { + let at = y as usize * stride + r.x as usize * 4; + if let Some(row) = px.get(at..at + r.w as usize * 4) { + out.extend_from_slice(row); + } + } + out +} + +/// What frame `cur` writes after frame `before` (none: it is the first, and covers the canvas): +/// the region, whether it blends over, and its pixels. +fn region(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> (Rect, bool, Vec) { + let full = Rect { x: 0, y: 0, w, h }; + let Some(before) = before else { return (full, false, cur.to_vec()) }; + let mut r = changed(before, cur, w, h).unwrap_or(full); + match kind { + Kind::Webp => { + // Frame offsets are stored halved: the region starts on an even pixel. + let (ex, ey) = (r.x & !1, r.y & !1); + r = Rect { x: ex, y: ey, w: r.w + (r.x - ex), h: r.h + (r.y - ey) }; + (r, false, crop(cur, w, r)) + } + Kind::Apng => { + let (old, new) = (crop(before, w, r), crop(cur, w, r)); + let (po, pn) = (old.as_chunks::<4>().0, new.as_chunks::<4>().0); + if po.iter().zip(pn).all(|(o, n)| o == n || n[3] == 255) { + // Every changed pixel is opaque: blend over, unchanged pixels transparent. + let mut px = Vec::with_capacity(new.len()); + for (o, n) in po.iter().zip(pn) { + px.extend_from_slice(if o == n { &[0, 0, 0, 0] } else { n }); + } + (r, true, px) + } else { + (r, false, new) + } + } + } +} + +/// A standalone PNG's image data: its `IDAT` chunks' contents, joined. +fn idat(png: &[u8]) -> Result> { + let mut out = Vec::new(); + let mut at = 8usize; + while let Some(head) = png.get(at..at + 8) { + let len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize; + let data = png.get(at + 8..at + 8 + len).ok_or_else(|| EngineError::Format("the PNG encoder wrote a short chunk".into()))?; + if &head[4..8] == b"IDAT" { + out.extend_from_slice(data); + } + at += 12 + len; + } + Ok(out) +} + +/// A RIFF file's first chunk named `id`, whole (header, data and padding). +fn riff_chunk<'a>(riff: &'a [u8], id: &[u8; 4]) -> Option<&'a [u8]> { + let mut at = 12usize; + while let Some(head) = riff.get(at..at + 8) { + let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; + let whole = 8 + len + (len & 1); + if &head[0..4] == id { + return riff.get(at..at + whole).or_else(|| riff.get(at..at + 8 + len)); + } + at += whole; + } + None +} + +/// Compresses `px` (`w` × `h` RGBA8) as one frame's data. +fn compress(kind: Kind, px: &[u8], w: u32, h: u32) -> Result> { + let fail = |e: String| EngineError::Format(format!("{} frame: {e}", kind.name())); + match kind { + Kind::Apng => { + let mut buf = Vec::new(); + { + let mut enc = png::Encoder::new(&mut buf, w, h); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.set_adaptive_filter(png::AdaptiveFilterType::Adaptive); + enc.set_compression(png::Compression::Best); + let mut wr = enc.write_header().map_err(|e| fail(e.to_string()))?; + wr.write_image_data(px).map_err(|e| fail(e.to_string()))?; + } + idat(&buf) + } + Kind::Webp => { + if px.len() != w as usize * h as usize * 4 { + return Err(fail("the frame has the wrong size".into())); + } + let mut buf = Vec::new(); + image_webp::WebPEncoder::new(&mut buf).encode(px, w, h, image_webp::ColorType::Rgba8).map_err(|e| fail(e.to_string()))?; + riff_chunk(&buf, b"VP8L").map(<[u8]>::to_vec).ok_or_else(|| fail("the WebP encoder wrote no lossless image".into())) + } + } +} + +fn encode(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> Result { + let (rect, over, px) = region(kind, before, cur, w, h); + Ok(Encoded { rect, over, data: compress(kind, &px, rect.w, rect.h)? }) +} + +/// A frame that changes nothing (one transparent pixel blended over the top-left corner): how +/// a delay too long for one frame header goes on. +fn still(kind: Kind) -> Result { + Ok(Encoded { rect: Rect { x: 0, y: 0, w: 1, h: 1 }, over: true, data: compress(kind, &[0, 0, 0, 0], 1, 1)? }) +} + +// ----- the files --------------------------------------------------------------------------- + +fn png_chunk(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { + let len = u32::try_from(data.len()).ok().filter(|l| *l < 1 << 31).ok_or_else(|| EngineError::Format("an animated PNG frame is too large".into()))?; + out.extend_from_slice(&len.to_be_bytes()); + let from = out.len(); + out.extend_from_slice(id); + out.extend_from_slice(data); + let crc = anicraft_xfl::zip::crc32(out.get(from..).unwrap_or(&[])); + out.extend_from_slice(&crc.to_be_bytes()); + Ok(()) +} + +/// The APNG file: frames with their delays (the first frame is the default image). +fn apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> Result> { + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = Vec::with_capacity(13); + ihdr.extend_from_slice(&w.to_be_bytes()); + ihdr.extend_from_slice(&h.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA, deflate, adaptive filters, no interlace + png_chunk(&mut out, b"IHDR", &ihdr)?; + let count = u32::try_from(frames.len()).map_err(|_| EngineError::Format("too many frames".into()))?; + let mut actl = count.to_be_bytes().to_vec(); + actl.extend_from_slice(&plays.to_be_bytes()); + png_chunk(&mut out, b"acTL", &actl)?; + let mut seq = 0u32; + for (k, (f, (num, den))) in frames.iter().enumerate() { + let mut fctl = Vec::with_capacity(26); + for v in [seq, f.rect.w, f.rect.h, f.rect.x, f.rect.y] { + fctl.extend_from_slice(&v.to_be_bytes()); + } + fctl.extend_from_slice(&num.to_be_bytes()); + fctl.extend_from_slice(&den.to_be_bytes()); + fctl.extend_from_slice(&[0, u8::from(f.over)]); // dispose: none; blend: source or over + png_chunk(&mut out, b"fcTL", &fctl)?; + seq += 1; + if k == 0 { + png_chunk(&mut out, b"IDAT", &f.data)?; + } else { + let mut fdat = Vec::with_capacity(f.data.len() + 4); + fdat.extend_from_slice(&seq.to_be_bytes()); + fdat.extend_from_slice(&f.data); + png_chunk(&mut out, b"fdAT", &fdat)?; + seq += 1; + } + } + png_chunk(&mut out, b"IEND", &[])?; + Ok(out) +} + +fn le24(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()[..3]); +} + +fn riff_push(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { + let len = u32::try_from(data.len()).map_err(|_| EngineError::Format("an animated WebP frame is too large".into()))?; + out.extend_from_slice(id); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(data); + if len & 1 == 1 { + out.push(0); + } + Ok(()) +} + +/// The animated WebP file: frames with their durations. `background` is the stage colour as +/// the `ANIM` background (RGBA), or transparent. +fn webp_file(w: u32, h: u32, plays: u32, alpha: bool, background: [u8; 4], frames: &[(&Encoded, u32)]) -> Result> { + let mut body = b"WEBP".to_vec(); + let mut vp8x = vec![if alpha { 0x10 | 0x02 } else { 0x02 }, 0, 0, 0]; + le24(&mut vp8x, w - 1); + le24(&mut vp8x, h - 1); + riff_push(&mut body, b"VP8X", &vp8x)?; + let [r, g, b, a] = background; + let mut anim = vec![b, g, r, a]; + anim.extend_from_slice(&u16::try_from(plays).unwrap_or(u16::MAX).to_le_bytes()); + riff_push(&mut body, b"ANIM", &anim)?; + for (f, ms) in frames { + let mut anmf = Vec::with_capacity(16 + f.data.len()); + le24(&mut anmf, f.rect.x / 2); + le24(&mut anmf, f.rect.y / 2); + le24(&mut anmf, f.rect.w - 1); + le24(&mut anmf, f.rect.h - 1); + le24(&mut anmf, *ms); + anmf.push(if f.over { 0 } else { 0x02 }); // blending: alpha-blend or replace; dispose: none + anmf.extend_from_slice(&f.data); + riff_push(&mut body, b"ANMF", &anmf)?; + } + let mut out = Vec::with_capacity(body.len() + 8); + riff_push(&mut out, b"RIFF", &body)?; + Ok(out) +} + +// ----- the command ------------------------------------------------------------------------- + +/// How many times it plays: `loop` true (or absent) forever (0), false once, or a count. +pub(crate) fn plays(p: &Value) -> Result { + match p.get("loop") { + None | Some(Value::Null) | Some(Value::Bool(true)) => Ok(0), + Some(Value::Bool(false)) => Ok(1), + Some(v) => v + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n <= MAX_PLAYS) + .ok_or_else(|| EngineError::Param(format!("param 'loop' must be true (forever), false (once) or how many times it plays (0 is forever, at most {MAX_PLAYS})"))), + } +} + +/// `file.export_apng` and `file.export_webp`. +pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + // The whole movie: every scene in order. + let last = s.doc.frame_count().saturating_sub(1); + let from = opt_u32(p, "from")?.unwrap_or(0).min(last); + let to = opt_u32(p, "to")?.unwrap_or(last).min(last); + if to < from { + return Err(EngineError::Param("'to' must not be before 'from'".into())); + } + let scale = crate::cmds_file::scale_param(p)?; + let plays = plays(p)?; + let background = opt_bool(p, "background")?.unwrap_or(false); + let mut view = View::stage(&s.doc, scale); + if !background { + view.background = None; + } + let (w, h) = (view.width.max(1), view.height.max(1)); + if kind == Kind::Webp && (w > MAX_WEBP_EDGE || h > MAX_WEBP_EDGE) { + return Err(EngineError::Param(format!("WebP frames are at most {MAX_WEBP_EDGE} px per side; lower 'scale'"))); + } + let n = u64::from(to - from) + 1; + if n * u64::from(w) * u64::from(h) > MAX_ANIM_PIXELS { + return Err(EngineError::Param(format!("that {} would be too large ({n} frames at {w}×{h}); lower 'scale' or the frame range", kind.name()))); + } + let doc = &s.doc; + let job = s.job.as_deref(); + let started = web_time::Instant::now(); + let batch = (BATCH_PIXELS / (u64::from(w) * u64::from(h))).clamp(2, 16) as usize; + // Each distinct frame: its first frame (from 0) and how many frames it shows for. + let mut shown: Vec<(u64, u64)> = Vec::new(); + let mut encoded: Vec = Vec::new(); + let mut prev: Option> = None; + let frames: Vec = (from..=to).collect(); + for (b, chunk) in frames.chunks(batch).enumerate() { + let images: Vec> = chunk + .par_iter() + .map(|&f| { + let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + crate::publish::tick(job, 1)?; + Ok(pm.to_rgba8()) + }) + .collect::>()?; + // A frame like the one before it only lengthens that frame's delay. + let mut fresh: Vec = Vec::new(); + let mut last_seen: Option<&[u8]> = prev.as_deref(); + for (i, img) in images.iter().enumerate() { + match shown.last_mut() { + Some((_, count)) if last_seen == Some(img.as_slice()) => *count += 1, + _ => { + shown.push(((b * batch + i) as u64, 1)); + fresh.push(i); + } + } + last_seen = Some(img.as_slice()); + } + let made = (0..fresh.len()) + .into_par_iter() + .map(|k| { + let cur = fresh.get(k).and_then(|&i| images.get(i)).ok_or_else(|| EngineError::Format("lost a frame".into()))?; + let before = match k.checked_sub(1) { + None => prev.as_deref(), + Some(j) => fresh.get(j).and_then(|&i| images.get(i)).map(Vec::as_slice), + }; + encode(kind, before, cur, w, h) + }) + .collect::>>()?; + encoded.extend(made); + if let Some(&i) = fresh.last() { + prev = images.into_iter().nth(i); + } + } + let ratio = fps_ratio(doc.stage.fps); + let pad = still(kind)?; + let bytes = match kind { + Kind::Apng => { + let mut list: Vec<(&Encoded, (u16, u16))> = Vec::new(); + for (e, &(start, count)) in encoded.iter().zip(&shown) { + for (k, d) in apng_delays(start, count, ratio).into_iter().enumerate() { + list.push((if k == 0 { e } else { &pad }, d)); + } + } + apng_file(w, h, plays, &list)? + } + Kind::Webp => { + let mut list: Vec<(&Encoded, u32)> = Vec::new(); + for (e, &(start, count)) in encoded.iter().zip(&shown) { + for (k, d) in webp_durations(start, count, ratio).into_iter().enumerate() { + list.push((if k == 0 { e } else { &pad }, d)); + } + } + let padded = list.len() > encoded.len(); + let c = s.doc.stage.background.sanitized(); + let q = |v: f32| (v * 255.0).round() as u8; + let bg = if background { [q(c.r), q(c.g), q(c.b), 255] } else { [0; 4] }; + webp_file(w, h, plays, !background || padded, bg, &list)? + } + }; + crate::vfs::write(&path, &bytes)?; + Ok(json!({ + "written": path.display().to_string(), + "frames": n, + "stored_frames": encoded.len(), + "bytes": bytes.len(), + "width": w, + "height": h, + "loop": plays, + "ms": started.elapsed().as_millis() as u64, + })) +} + +#[cfg(test)] +#[path = "anim_tests.rs"] +mod tests; diff --git a/crates/engine/src/anim_tests.rs b/crates/engine/src/anim_tests.rs new file mode 100644 index 00000000..fcce90cd --- /dev/null +++ b/crates/engine/src/anim_tests.rs @@ -0,0 +1,347 @@ +use super::*; +use crate::Session; +use anicraft_doc::sample; +use serde_json::json; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn tmp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-anim-{}-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// What the CPU renderer draws for movie frames `from..=to`, as straight RGBA8. +fn renders(doc: &anicraft_doc::Document, from: u32, to: u32, scale: f32, background: bool) -> Vec> { + let mut view = View::stage(doc, scale); + if !background { + view.background = None; + } + (from..=to).map(|f| render(&anicraft_doc::evaluate(doc, f), &view).unwrap().0.to_rgba8()).collect() +} + +/// An APNG decoded as a player shows it (the APNG specification's compositing): each frame's +/// canvas, its delay (num, den), its region and blend op, and the play count. +struct ApngFrame { + canvas: Vec, + delay: (u16, u16), + rect: Rect, + over: bool, +} + +struct Apng { + frames: Vec, + plays: u32, + size: (u32, u32), +} + +fn decode_apng(bytes: &[u8]) -> Apng { + let dec = png::Decoder::new(std::io::Cursor::new(bytes)); + let mut reader = dec.read_info().unwrap(); + let info = reader.info(); + let (w, h) = (info.width, info.height); + let actl = info.animation_control.expect("an acTL chunk"); + assert_eq!((info.color_type, info.bit_depth), (png::ColorType::Rgba, png::BitDepth::Eight)); + let mut canvas = vec![0u8; (w * h * 4) as usize]; + let mut frames = Vec::new(); + let mut buf = vec![0u8; reader.output_buffer_size()]; + for _ in 0..actl.num_frames { + let out = reader.next_frame(&mut buf).unwrap(); + let fc = *reader.info().frame_control().expect("an fcTL per frame"); + assert_eq!(fc.dispose_op, png::DisposeOp::None); + let over = fc.blend_op == png::BlendOp::Over; + let r = Rect { x: fc.x_offset, y: fc.y_offset, w: fc.width, h: fc.height }; + assert_eq!((out.width, out.height), (r.w, r.h)); + assert!(r.x + r.w <= w && r.y + r.h <= h); + for y in 0..r.h { + for x in 0..r.w { + let s = ((y * r.w + x) * 4) as usize; + let d = (((r.y + y) * w + r.x + x) * 4) as usize; + let src = &buf[s..s + 4]; + if over { + // Exact for the pixels the exporter blends: transparent or opaque. + assert!(src[3] == 0 || src[3] == 255, "an over-blended pixel is neither transparent nor opaque"); + if src[3] == 255 { + canvas[d..d + 4].copy_from_slice(src); + } + } else { + canvas[d..d + 4].copy_from_slice(src); + } + } + } + frames.push(ApngFrame { canvas: canvas.clone(), delay: (fc.delay_num, fc.delay_den), rect: r, over }); + } + Apng { frames, plays: actl.num_plays, size: (w, h) } +} + +/// The frames an APNG shows, one per movie frame at `ratio` fps (each delay is a whole number +/// of movie frames, exactly). +fn apng_movie(a: &Apng, (p, q): (u64, u64)) -> Vec> { + let mut out = Vec::new(); + for f in &a.frames { + let (num, den) = (u64::from(f.delay.0), u64::from(f.delay.1)); + // num/den s = k·q/p s + assert_eq!((num * p) % (den * q), 0, "a delay of {num}/{den} s is not a whole number of frames at {p}/{q} fps"); + for _ in 0..num * p / (den * q) { + out.push(f.canvas.clone()); + } + } + out +} + +/// A WebP decoded as a player shows it: each frame's canvas and duration. +/// An animated WebP's frames (canvas, milliseconds), loop count, size and whether it has alpha. +struct Webp { + frames: Vec<(Vec, u32)>, + looping: image_webp::LoopCount, + size: (u32, u32), + alpha: bool, +} + +fn decode_webp(bytes: &[u8]) -> Webp { + let mut dec = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).unwrap(); + assert!(dec.is_animated()); + let (w, h) = dec.dimensions(); + let alpha = dec.has_alpha(); + let mut buf = vec![0u8; dec.output_buffer_size().unwrap()]; + let mut frames = Vec::new(); + for _ in 0..dec.num_frames() { + let ms = dec.read_frame(&mut buf).unwrap(); + let rgba = if alpha { buf.clone() } else { buf.chunks(3).flat_map(|c| [c[0], c[1], c[2], 255]).collect() }; + frames.push((rgba, ms)); + } + Webp { frames, looping: dec.loop_count(), size: (w, h), alpha } +} + +/// The frames a WebP shows, one per movie frame: the frame showing when each starts. +fn webp_movie(frames: &[(Vec, u32)], n: u64, ratio: (u64, u64)) -> Vec> { + let mut starts = Vec::new(); + let mut t = 0u64; + for (_, ms) in frames { + starts.push(t); + t += u64::from(*ms); + } + assert_eq!(t, start_ms(n, ratio), "the running time is exact to the millisecond"); + (0..n).map(|f| { + let at = start_ms(f, ratio); + let i = starts.iter().rposition(|s| *s <= at).unwrap(); + frames[i].0.clone() + }) + .collect() +} + +fn same(got: &[Vec], want: &[Vec], what: &str) { + assert_eq!(got.len(), want.len(), "{what}: frame count"); + for (k, (g, w)) in got.iter().zip(want).enumerate() { + assert!(g == w, "{what}: frame {} differs from the CPU renderer", k + 1); + } +} + +/// A ball that holds still for 10 frames, jumps, and holds 6 more: 16 frames, 2 pictures. +fn holds() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.ellipse", json!({"x": 40, "y": 40, "w": 60, "h": 60})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 200, "dy": 30})); + run(&mut s, "timeline.goto", json!({"frame": 15})); + run(&mut s, "timeline.insert_frame", json!({})); + assert_eq!(s.frame_count(), 16); + s +} + +#[test] +fn frame_rates_are_exact_fractions() { + assert_eq!(fps_ratio(24.0), (24, 1)); + assert_eq!(fps_ratio(29.97), (2997, 100)); + assert_eq!(fps_ratio(23.976), (2997, 125)); + assert_eq!(fps_ratio(12.5), (25, 2)); + assert_eq!(fps_ratio(f32::NAN), (24, 1)); + assert_eq!(fps_ratio(-3.0), (24, 1)); + // Millisecond starts round from the exact time, so the error never adds up. + assert_eq!(start_ms(24, (24, 1)), 1000); + assert_eq!(start_ms(1, (30, 1)), 33); + assert_eq!(start_ms(2, (30, 1)), 67); + assert_eq!(start_ms(2997, (2997, 100)), 100_000); + assert_eq!(webp_durations(0, 3, (30, 1)), vec![100]); + let total: u32 = (0..30).flat_map(|i| webp_durations(i, 1, (30, 1))).sum(); + assert_eq!(total, 1000); + // APNG delays are fractions of the frame rate, reduced. + assert_eq!(apng_delays(0, 1, (24, 1)), vec![(1, 24)]); + assert_eq!(apng_delays(0, 6, (24, 1)), vec![(1, 4)]); + assert_eq!(apng_delays(5, 2, (2997, 100)), vec![(200, 2997)]); + // Longer than one fcTL holds: more pieces, adding up exactly. + let long = apng_delays(0, 200_000, (2997, 100)); + assert!(long.len() > 1); + let frames: u64 = long.iter().map(|&(n, d)| u64::from(n) * 2997 / (u64::from(d) * 100)).sum(); + assert_eq!(frames, 200_000); + // A rate with a huge denominator falls back to milliseconds, still adding up. + let odd = (100_003, 1000); + let ms: u64 = apng_delays(0, 1000, odd).iter().map(|&(n, d)| { + assert_eq!(d, 1000); + u64::from(n) + }).sum(); + assert_eq!(ms, start_ms(1000, odd)); + let hours = webp_durations(0, 100_000, (1, 1)); + assert_eq!(hours.iter().map(|&m| u64::from(m)).sum::(), 100_000_000); + assert!(hours.iter().all(|&m| u64::from(m) <= MAX_WEBP_MS) && hours.len() > 1); +} + +#[test] +fn the_changed_rectangle_is_tight() { + let (w, h) = (8u32, 6u32); + let a = vec![0u8; (w * h * 4) as usize]; + assert_eq!(changed(&a, &a, w, h), None); + let mut b = a.clone(); + b[((2 * w + 3) * 4 + 1) as usize] = 9; // (3, 2) + b[((4 * w + 6) * 4 + 3) as usize] = 9; // (6, 4) + assert_eq!(changed(&a, &b, w, h), Some(Rect { x: 3, y: 2, w: 4, h: 3 })); + // WebP regions start on even pixels; APNG's stay tight. + let (r, over, px) = region(Kind::Webp, Some(&a), &b, w, h); + assert_eq!((r, over, px.len()), (Rect { x: 2, y: 2, w: 5, h: 3 }, false, 5 * 3 * 4)); + let (r, over, _) = region(Kind::Apng, Some(&a), &b, w, h); + assert_eq!((r, over), (Rect { x: 3, y: 2, w: 4, h: 3 }, false), "semi-transparent changes replace"); + let mut c = a.clone(); + c[((2 * w + 3) * 4) as usize..((2 * w + 3) * 4 + 4) as usize].copy_from_slice(&[1, 2, 3, 255]); + let (r, over, px) = region(Kind::Apng, Some(&a), &c, w, h); + assert_eq!((r, over, px), (Rect { x: 3, y: 2, w: 1, h: 1 }, true, vec![1, 2, 3, 255]), "opaque changes blend over"); +} + +#[test] +fn apng_frames_match_the_renderer_exactly() { + let dir = tmp("apng"); + let mut s = Session::new(sample::demo()); + for background in [false, true] { + let path = dir.join(format!("walk-{background}.png")); + let v = run(&mut s, "file.export_apng", json!({"path": path.display().to_string(), "scale": 0.25, "to": 23, "background": background})); + assert_eq!(v["frames"], 24); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(v["bytes"], bytes.len()); + let a = decode_apng(&bytes); + assert_eq!(a.plays, 0, "loops forever by default"); + let want = renders(&s.doc, 0, 23, 0.25, background); + assert_eq!(a.size, (320, 180)); + same(&apng_movie(&a, fps_ratio(s.doc.stage.fps)), &want, "APNG"); + // Frames after the first cover only what changed. + assert!(a.frames.iter().skip(1).any(|f| f.rect.w * f.rect.h < 320 * 180), "dirty rectangles"); + if background { + assert!(a.frames.iter().skip(1).all(|f| f.over), "opaque frames blend over"); + } + // The default image is the first frame, and a plain PNG reader sees it. + let first = png::Decoder::new(std::io::Cursor::new(&bytes)).read_info().unwrap().info().frame_control.unwrap(); + assert_eq!((first.width, first.height, first.x_offset, first.y_offset), (320, 180, 0, 0)); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn webp_frames_match_the_renderer_exactly() { + let dir = tmp("webp"); + let mut s = Session::new(sample::demo()); + for background in [false, true] { + let path = dir.join(format!("walk-{background}.webp")); + let v = run(&mut s, "file.export_webp", json!({"path": path.display().to_string(), "scale": 0.25, "from": 4, "to": 27, "background": background})); + assert_eq!(v["frames"], 24); + let bytes = std::fs::read(&path).unwrap(); + assert!(bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP"); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len()); + let Webp { frames, looping, size, alpha } = decode_webp(&bytes); + assert_eq!((size, alpha), ((320, 180), !background)); + assert_eq!(looping, image_webp::LoopCount::Forever); + let want = renders(&s.doc, 4, 27, 0.25, background); + same(&webp_movie(&frames, 24, fps_ratio(s.doc.stage.fps)), &want, "WebP"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn identical_frames_merge_into_longer_delays() { + let dir = tmp("holds"); + let mut s = holds(); + let ratio = fps_ratio(s.doc.stage.fps); + let want = renders(&s.doc, 0, 15, 1.0, false); + let png = dir.join("holds.png"); + let v = run(&mut s, "file.export_apng", json!({"path": png.display().to_string(), "loop": 3})); + assert_eq!((v["frames"].as_u64(), v["stored_frames"].as_u64(), v["loop"].as_u64()), (Some(16), Some(2), Some(3))); + let a = decode_apng(&std::fs::read(&png).unwrap()); + assert_eq!(a.frames.len(), 2); + assert_eq!(a.plays, 3); + let fps = s.doc.stage.fps; + assert_eq!(a.frames[0].delay, apng_delays(0, 10, ratio)[0], "10 frames at {fps} fps"); + same(&apng_movie(&a, ratio), &want, "held APNG"); + let webp = dir.join("holds.webp"); + let v = run(&mut s, "file.export_webp", json!({"path": webp.display().to_string(), "loop": false})); + assert_eq!(v["stored_frames"], 2); + let Webp { frames, looping, .. } = decode_webp(&std::fs::read(&webp).unwrap()); + assert_eq!(frames.len(), 2); + assert_eq!(looping, image_webp::LoopCount::Times(std::num::NonZeroU16::new(1).unwrap())); + same(&webp_movie(&frames, 16, ratio), &want, "held WebP"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bad_params_are_refused_and_overwrites_confirm() { + let dir = tmp("params"); + let mut s = holds(); + let at = |n: &str| dir.join(n).display().to_string(); + for id in ["file.export_apng", "file.export_webp"] { + for bad in [json!({"loop": -1}), json!({"loop": 70_000}), json!({"loop": "yes"}), json!({"scale": 0}), json!({"from": 9, "to": 2}), json!({"background": 3})] { + let mut p = bad.clone(); + p["path"] = json!(at("x.out")); + assert!(s.execute(id, &p).is_err(), "{id} {bad}"); + } + assert!(s.execute(id, &json!({"path": at("big.out"), "scale": 8})).is_err(), "{id}: too large"); + assert!(!Path::new(&at("x.out")).exists() && !Path::new(&at("big.out")).exists()); + let path = at(&format!("once-{id}.out")); + run(&mut s, id, json!({"path": path, "to": 1})); + assert!(s.execute(id, &json!({"path": path})).is_err(), "{id}: replacing a file asks first"); + run(&mut s, id, json!({"path": path, "confirm": true})); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_cancelled_publish_stops_the_export() { + let mut s = Session::new(sample::demo()); + let job = std::sync::Arc::new(crate::publish::Control::default()); + job.cancel(); + s.job = Some(job); + let dir = tmp("cancel"); + let path = dir.join("walk.webp"); + let e = s.execute("file.export_webp", &json!({"path": path.display().to_string(), "scale": 0.1})).unwrap_err(); + assert!(matches!(e, EngineError::Cancelled), "{e}"); + assert!(!path.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +#[ignore = "a measurement: cargo test --release -p anicraft-engine anim::tests::sizes -- --ignored --nocapture"] +fn sizes() { + // docs/performance.md › Animated exports: the sample, every frame, at full size and half. + let dir = tmp("sizes"); + for scale in [1.0, 0.5] { + let mut s = Session::new(sample::demo()); + let mut row = format!("scale {scale}:"); + for (id, ext, extra) in [ + ("file.export_gif", "gif", json!({})), + ("file.export_apng", "png", json!({"background": true})), + ("file.export_apng", "png", json!({})), + ("file.export_webp", "webp", json!({"background": true})), + ("file.export_webp", "webp", json!({})), + ] { + let mut p = extra.clone(); + p["path"] = json!(dir.join(format!("walk-{scale}-{}.{ext}", extra.as_object().map_or(0, |o| o.len()))).display().to_string()); + p["scale"] = json!(scale); + p["confirm"] = json!(true); + let t = std::time::Instant::now(); + let v = run(&mut s, id, p); + row.push_str(&format!(" | {id} {extra}: {} KB, {} stored, {} ms", v["bytes"].as_u64().unwrap() / 1024, v["stored_frames"], t.elapsed().as_millis())); + } + println!("{row}"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index a3b900d1..7aa7fa93 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -74,6 +74,24 @@ pub fn specs() -> Vec { mutates: false, run: export_gif, }, + CommandSpec { + id: "file.export_apng", + label: "Export Animated PNG…", + menu: "File/Export", + shortcut: None, + params: "{path (.png or .apng), from?, to? (movie frames: every scene in order), scale?, loop? (true (default): forever; false: once; or how many times it plays), background? (default false: transparent), confirm?}", + mutates: false, + run: |s, p| crate::anim::export(s, p, crate::anim::Kind::Apng), + }, + CommandSpec { + id: "file.export_webp", + label: "Export Animated WebP…", + menu: "File/Export", + shortcut: None, + params: "{path (.webp; lossless), from?, to? (movie frames: every scene in order), scale?, loop? (true (default): forever; false: once; or how many times it plays), background? (default false: transparent), confirm?}", + mutates: false, + run: |s, p| crate::anim::export(s, p, crate::anim::Kind::Webp), + }, CommandSpec { id: "file.export_lottie", label: "Export Lottie Animation…", @@ -207,7 +225,7 @@ fn save(s: &mut Session, p: &Value) -> Result { Ok(json!({"saved": path.display().to_string()})) } -fn scale_param(p: &Value) -> Result { +pub(crate) fn scale_param(p: &Value) -> Result { match opt_f32(p, "scale")? { None => Ok(1.0), Some(v) if v > 0.0 && v <= 8.0 => Ok(v), diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index bf666f85..cee96054 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -109,7 +109,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { let same = s.path.as_deref() == Some(path); (!same && crate::vfs::exists(path)).then(|| overwrite(path, "Saving")) } - "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => { + "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => { let path = Path::new(p.get("path").and_then(Value::as_str)?); crate::vfs::exists(path).then(|| overwrite(path, "Exporting")) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 83438b1a..0a5ca065 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! JSON params, so headless and interactive behaviour cannot drift apart. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod anim; mod cmds_actions; mod cmds_bone; pub mod cmds_brush; diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index d8ae7d26..90335a60 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -136,6 +136,8 @@ fn plugins_cannot_reach_files_history_the_clipboard_or_other_plugins() { let forbidden = [ save.as_str(), r#"{"op":"command","id":"file.export_png","params":{"path":"x.png"}}"#, + r#"{"op":"command","id":"file.export_apng","params":{"path":"x.png"}}"#, + r#"{"op":"command","id":"file.export_webp","params":{"path":"x.webp"}}"#, r#"{"op":"command","id":"plugin.run","params":{"id":"org.test.sneaky"}}"#, r#"{"op":"command","id":"plugin.remove","params":{"id":"org.test.sneaky","confirm":true}}"#, r#"{"op":"command","id":"edit.undo"}"#, diff --git a/crates/engine/src/publish.rs b/crates/engine/src/publish.rs index 857f232b..64d83afc 100644 --- a/crates/engine/src/publish.rs +++ b/crates/engine/src/publish.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { label: "Publish Settings", menu: "", shortcut: None, - params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", + params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", mutates: true, run: settings_set, }, @@ -205,6 +205,17 @@ pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>) p.insert("loop".into(), json!(g.looping)); ("file.export_gif", n, vec![out]) } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background, command) = match f { + PublishFormat::Apng => (prof.apng.range, prof.apng.scale, prof.apng.plays, prof.apng.background, "file.export_apng"), + _ => (prof.webp.range, prof.webp.scale, prof.webp.plays, prof.webp.background, "file.export_webp"), + }; + let n = range_params(&mut p, range, last); + p.insert("scale".into(), json!(scale)); + p.insert("loop".into(), json!(plays)); + p.insert("background".into(), json!(background)); + (command, n, vec![out]) + } PublishFormat::Video => { let v = &prof.video; let n = range_params(&mut p, v.range, last); @@ -310,7 +321,7 @@ pub fn formats_param(p: &Value) -> Result>> { Some(Value::Array(list)) => list .iter() .take(64) - .map(|v| v.as_str().and_then(PublishFormat::from_key).ok_or_else(|| EngineError::Param(format!("unknown format {v} (html, gif, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))) + .map(|v| v.as_str().and_then(PublishFormat::from_key).ok_or_else(|| EngineError::Param(format!("unknown format {v} (html, gif, apng, webp, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))) .collect::>>() .map(Some), Some(_) => Err(EngineError::Param("param 'formats' must be a list of format names".into())), @@ -549,6 +560,7 @@ fn option_keys(f: PublishFormat) -> &'static [&'static str] { match f { PublishFormat::Html => &["title", "sound", "fit"], PublishFormat::Gif => &["from", "to", "scale", "loop"], + PublishFormat::Apng | PublishFormat::Webp => &["from", "to", "scale", "loop", "background"], PublishFormat::Video => &["from", "to", "scale", "audio"], PublishFormat::Lottie => &["from", "to", "background"], PublishFormat::SpriteSheet => &["from", "to", "scale", "columns", "padding", "background"], @@ -633,6 +645,18 @@ fn apply(prof: &mut PublishProfile, f: PublishFormat, p: &Value) -> Result<()> { set_scale(&mut g.scale, p)?; set_bool(&mut g.looping, p, "loop")?; } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background) = match f { + PublishFormat::Apng => (&mut prof.apng.range, &mut prof.apng.scale, &mut prof.apng.plays, &mut prof.apng.background), + _ => (&mut prof.webp.range, &mut prof.webp.scale, &mut prof.webp.plays, &mut prof.webp.background), + }; + set_range(range, p)?; + set_scale(scale, p)?; + if p.get("loop").is_some() { + *plays = crate::anim::plays(p)?; + } + set_bool(background, p, "background")?; + } PublishFormat::Video => { let v = &mut prof.video; set_range(&mut v.range, p)?; @@ -704,7 +728,7 @@ fn settings_set(s: &mut Session, p: &Value) -> Result { }; match opt_str(p, "format")? { Some(k) => { - let f = PublishFormat::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown format '{k}' (html, gif, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))?; + let f = PublishFormat::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown format '{k}' (html, gif, apng, webp, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))?; apply(&mut prof, f, p)?; } None if p.get("profile").is_none_or(Value::is_null) && p.as_object().is_some_and(|o| o.keys().any(|k| k != "confirm" && k != "profile")) => { diff --git a/crates/engine/src/web_tests.rs b/crates/engine/src/web_tests.rs index d496a0f5..2d04c05c 100644 --- a/crates/engine/src/web_tests.rs +++ b/crates/engine/src/web_tests.rs @@ -57,6 +57,8 @@ fn exports_come_back_as_files() { ("file.export_png", json!({"path": "frame.png"})), ("file.export_svg", json!({"path": "frame.svg"})), ("file.export_gif", json!({"path": "movie.gif", "to": 3})), + ("file.export_apng", json!({"path": "movie.png", "to": 3})), + ("file.export_webp", json!({"path": "movie.webp", "to": 3})), ("file.export_lottie", json!({"path": "movie.json"})), ("file.export_html", json!({"path": "movie.html"})), ("file.export_audio", json!({"path": "track.wav"})), @@ -67,12 +69,16 @@ fn exports_come_back_as_files() { s.execute("file.export_png_sequence", &json!({"dir": "frames", "to": 2})).unwrap(); let out = vfs::take_written(); let n = names(&out); - for want in ["frame.png", "frame.svg", "movie.gif", "movie.json", "movie.html", "track.wav", "sheet.png", "sheet.json", "frames/frame_00001.png", "frames/frame_00003.png"] { + for want in ["frame.png", "frame.svg", "movie.gif", "movie.png", "movie.webp", "movie.json", "movie.html", "track.wav", "sheet.png", "sheet.json", "frames/frame_00001.png", "frames/frame_00003.png"] { assert!(n.iter().any(|x| x == want), "{want} missing from {n:?}"); } assert!(out.iter().all(|(_, b)| !b.is_empty())); let png = &out.iter().find(|(p, _)| p == Path::new("frame.png")).unwrap().1; assert!(png.starts_with(b"\x89PNG")); + let apng = &out.iter().find(|(p, _)| p == Path::new("movie.png")).unwrap().1; + assert!(apng.starts_with(b"\x89PNG") && apng.windows(4).any(|w| w == b"acTL"), "an animated PNG"); + let webp = &out.iter().find(|(p, _)| p == Path::new("movie.webp")).unwrap().1; + assert!(webp.starts_with(b"RIFF") && webp.windows(4).any(|w| w == b"ANMF"), "an animated WebP"); let wav = &out.iter().find(|(p, _)| p == Path::new("track.wav")).unwrap().1; assert!(wav.starts_with(b"RIFF") && !n.iter().any(|x| x.ends_with(".tmp"))); let err = s.execute("file.export_video", &json!({"path": "movie.webm"})).unwrap_err().to_string(); From b61014682ed82be854f03ad0c644dd797f22046b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:03:12 -0700 Subject: [PATCH 058/192] feat(publish): animated PNG and WebP in Publish Settings and File > Export (M4) --- crates/doc/src/publish.rs | 62 +++++++++++++++++++++++++++++++++++++-- src/a11y.rs | 2 +- src/app.rs | 23 +++++++++++++++ src/dialogs.rs | 2 +- src/i18n/tests.rs | 6 ++-- src/main.rs | 2 +- src/platform.rs | 2 ++ src/publish_panel.rs | 28 ++++++++++++++++++ 8 files changed, 118 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/publish.rs b/crates/doc/src/publish.rs index 86343d5c..701ee881 100644 --- a/crates/doc/src/publish.rs +++ b/crates/doc/src/publish.rs @@ -14,6 +14,8 @@ use serde::{Deserialize, Serialize}; pub enum PublishFormat { Html, Gif, + Apng, + Webp, Video, Lottie, SpriteSheet, @@ -25,9 +27,11 @@ pub enum PublishFormat { impl PublishFormat { /// Every format, in the order Publish runs them. - pub const ALL: [PublishFormat; 9] = [ + pub const ALL: [PublishFormat; 11] = [ PublishFormat::Html, PublishFormat::Gif, + PublishFormat::Apng, + PublishFormat::Webp, PublishFormat::Video, PublishFormat::Lottie, PublishFormat::SpriteSheet, @@ -42,6 +46,8 @@ impl PublishFormat { match self { PublishFormat::Html => "html", PublishFormat::Gif => "gif", + PublishFormat::Apng => "apng", + PublishFormat::Webp => "webp", PublishFormat::Video => "video", PublishFormat::Lottie => "lottie", PublishFormat::SpriteSheet => "sprite_sheet", @@ -61,6 +67,8 @@ impl PublishFormat { match self { PublishFormat::Html => "HTML canvas", PublishFormat::Gif => "Animated GIF", + PublishFormat::Apng => "Animated PNG", + PublishFormat::Webp => "Animated WebP", PublishFormat::Video => "Video", PublishFormat::Lottie => "Lottie", PublishFormat::SpriteSheet => "Sprite sheet", @@ -76,6 +84,9 @@ impl PublishFormat { match self { PublishFormat::Html => "{name}.html", PublishFormat::Gif => "{name}.gif", + // Not {name}.png: the PNG image has that. + PublishFormat::Apng => "{name}_animated.png", + PublishFormat::Webp => "{name}.webp", PublishFormat::Video => "{name}.webm", PublishFormat::Lottie => "{name}.json", PublishFormat::SpriteSheet => "{name}_sheet.png", @@ -91,6 +102,8 @@ impl PublishFormat { match self { PublishFormat::Html => &["html", "htm"], PublishFormat::Gif => &["gif"], + PublishFormat::Apng => &["png", "apng"], + PublishFormat::Webp => &["webp"], PublishFormat::Video => &["webm", "mp4"], PublishFormat::Lottie => &["json"], PublishFormat::SpriteSheet | PublishFormat::Png => &["png"], @@ -107,6 +120,8 @@ pub const MAX_OUTPUT_CHARS: usize = 512; pub const MAX_TITLE_CHARS: usize = 256; /// Largest export scale. pub const MAX_PUBLISH_SCALE: f32 = 8.0; +/// Most plays an animated PNG or WebP's loop count says (WebP stores it in 16 bits). +pub const MAX_PLAYS: u32 = 65_535; /// Movie frames to publish (every scene in order, 0-based): `None` ends are the movie's ends. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -156,6 +171,30 @@ format_settings!( looping: bool = true, } ); +format_settings!( + /// An animated PNG: full colour, real alpha (`file.export_apng`, ADR 0063). + ApngSettings, PublishFormat::Apng, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + /// How many times it plays; 0: forever. + #[serde(rename = "loop")] + plays: u32 = 0, + /// The stage colour behind it; off: transparent. + background: bool = false, + } +); +format_settings!( + /// An animated WebP, lossless (`file.export_webp`, ADR 0063). + WebpSettings, PublishFormat::Webp, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + /// How many times it plays; 0: forever. + #[serde(rename = "loop")] + plays: u32 = 0, + /// The stage colour behind it; off: transparent. + background: bool = false, + } +); format_settings!( /// WebM or MP4 through the user's ffmpeg (`file.export_video`). VideoSettings, PublishFormat::Video, false, { @@ -220,6 +259,8 @@ format_settings!( pub struct PublishProfile { pub html: HtmlSettings, pub gif: GifSettings, + pub apng: ApngSettings, + pub webp: WebpSettings, pub video: VideoSettings, pub lottie: LottieSettings, pub sprite_sheet: SpriteSheetSettings, @@ -249,6 +290,8 @@ impl PublishProfile { match f { PublishFormat::Html => (self.html.enabled, &self.html.output), PublishFormat::Gif => (self.gif.enabled, &self.gif.output), + PublishFormat::Apng => (self.apng.enabled, &self.apng.output), + PublishFormat::Webp => (self.webp.enabled, &self.webp.output), PublishFormat::Video => (self.video.enabled, &self.video.output), PublishFormat::Lottie => (self.lottie.enabled, &self.lottie.output), PublishFormat::SpriteSheet => (self.sprite_sheet.enabled, &self.sprite_sheet.output), @@ -264,6 +307,8 @@ impl PublishProfile { match f { PublishFormat::Html => (&mut self.html.enabled, &mut self.html.output), PublishFormat::Gif => (&mut self.gif.enabled, &mut self.gif.output), + PublishFormat::Apng => (&mut self.apng.enabled, &mut self.apng.output), + PublishFormat::Webp => (&mut self.webp.enabled, &mut self.webp.output), PublishFormat::Video => (&mut self.video.enabled, &mut self.video.output), PublishFormat::Lottie => (&mut self.lottie.enabled, &mut self.lottie.output), PublishFormat::SpriteSheet => (&mut self.sprite_sheet.enabled, &mut self.sprite_sheet.output), @@ -290,16 +335,18 @@ impl PublishProfile { } } clip(&mut self.html.title, MAX_TITLE_CHARS); - for s in [&mut self.gif.scale, &mut self.video.scale, &mut self.sprite_sheet.scale, &mut self.png_sequence.scale, &mut self.png.scale] { + for s in [&mut self.gif.scale, &mut self.apng.scale, &mut self.webp.scale, &mut self.video.scale, &mut self.sprite_sheet.scale, &mut self.png_sequence.scale, &mut self.png.scale] { *s = clean_scale(*s); } self.sprite_sheet.padding = self.sprite_sheet.padding.min(256); + self.apng.plays = self.apng.plays.min(MAX_PLAYS); + self.webp.plays = self.webp.plays.min(MAX_PLAYS); self.sprite_sheet.columns = self.sprite_sheet.columns.min(10_000); self.audio.rate = self.audio.rate.clamp(8_000, 192_000); if !matches!(self.audio.bits, 16 | 24 | 32) { self.audio.bits = 16; } - for r in [&mut self.gif.range, &mut self.video.range, &mut self.lottie.range, &mut self.sprite_sheet.range, &mut self.png_sequence.range, &mut self.audio.range] { + for r in [&mut self.gif.range, &mut self.apng.range, &mut self.webp.range, &mut self.video.range, &mut self.lottie.range, &mut self.sprite_sheet.range, &mut self.png_sequence.range, &mut self.audio.range] { if let (Some(a), Some(b)) = (r.from, r.to) && b < a { @@ -344,6 +391,13 @@ mod tests { assert!(partial.gif.enabled && partial.html.enabled); assert_eq!(partial.gif.output, "{name}.gif"); assert_eq!(partial.gif.scale, 1.0); + assert_eq!((partial.apng.plays, partial.webp.background, partial.webp.enabled), (0, false, false), "formats newer than the file get their defaults"); + let mut q = PublishProfile::default(); + q.apng.plays = 3; + q.webp.background = true; + let text = serde_json::to_string(&q).unwrap(); + assert!(text.contains("\"apng\"") && text.contains("\"loop\":3"), "{text}"); + assert_eq!(serde_json::from_str::(&text).unwrap(), q); } #[test] @@ -354,12 +408,14 @@ mod tests { p.audio.rate = 5; p.audio.bits = 7; p.sprite_sheet.padding = u32::MAX; + p.webp.plays = u32::MAX; p.video.output = " ".into(); p.html.title = "x".repeat(10_000); p.lottie.range = FrameRange { from: Some(9), to: Some(2) }; p.sanitize(); assert_eq!((p.gif.scale, p.png.scale, p.audio.rate, p.audio.bits, p.sprite_sheet.padding), (1.0, MAX_PUBLISH_SCALE, 8_000, 16, 256)); assert_eq!(p.video.output, "{name}.webm"); + assert_eq!(p.webp.plays, MAX_PLAYS); assert_eq!(p.html.title.chars().count(), MAX_TITLE_CHARS); assert_eq!(p.lottie.range, FrameRange { from: Some(2), to: Some(9) }); } diff --git a/src/a11y.rs b/src/a11y.rs index 38603b04..dd3f2d9e 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -352,7 +352,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "start", "drop", "droplibrary"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index 877bdd25..fcc5cb00 100644 --- a/src/app.rs +++ b/src/app.rs @@ -855,6 +855,17 @@ impl App { crate::publish_panel::publish_now(self); } } + Some("publishanim") => { + // Publish Settings with the animated PNG on (ADR 0063): played three times, + // transparent, the WebP on beside it. + let dir = std::env::temp_dir().join("anicraft-publish-shot"); + let _ = std::fs::create_dir_all(&dir); + self.s.path = Some(dir.join("walk.anicraft")); + self.run("publish.settings_set", json!({"format": "apng", "enabled": true, "loop": 3})); + self.run("publish.settings_set", json!({"format": "webp", "enabled": true})); + self.publish.selected = anicraft_engine::doc::publish::PublishFormat::Apng; + crate::publish_panel::open(self); + } Some("explorer") => { // The Movie Explorer tab (ADR 0058), its first rows open: scene, layers, keyframes // and the instances on them, opening into their symbols. @@ -1702,6 +1713,16 @@ impl App { let done = trn!("Exported {path} ({n} frame, {kb} KB): open it in a web browser.", "Exported {path} ({n} frames, {kb} KB): open it in a web browser.", v["frames"].as_u64().unwrap_or(0), path = v["written"].as_str().unwrap_or(""), kb = kb); self.status_ok(format!("{done}{report}")); } + "file.export_apng" | "file.export_webp" => { + // Frames identical to the one before are kept once, with a longer delay. + let kb = v["bytes"].as_u64().unwrap_or(0).div_ceil(1024); + let n = v["frames"].as_u64().unwrap_or(0); + let stored = v["stored_frames"].as_u64().unwrap_or(n); + let path = v["written"].as_str().unwrap_or(""); + let done = trn!("Exported {path} ({n} frame, {kb} KB).", "Exported {path} ({n} frames, {kb} KB).", n, path = path, kb = kb); + let held = if stored < n { format!(" {}", tr!("Frames that repeat the one before are stored once, shown longer.")) } else { String::new() }; + self.status_ok(format!("{done}{held}")); + } "file.export_lottie" => { let report = v["report"].as_str().filter(|r| !r.is_empty()).map(|r| format!(" {r}")).unwrap_or_default(); let done = trn!("Exported {path} ({n} frame, {layers} layers).", "Exported {path} ({n} frames, {layers} layers).", v["frames"].as_u64().unwrap_or(0), path = v["written"].as_str().unwrap_or(""), layers = v["layers"]); @@ -1838,6 +1859,8 @@ impl App { "file.export_png" => Some((tr_noop!("Export frame as PNG"), "path", format!("frame_{:04}.png", self.s.frame + 1))), "file.export_png_sequence" => Some((tr_noop!("Export PNG sequence to folder"), "dir", "frames".to_string())), "file.export_gif" => Some((tr_noop!("Export animated GIF"), "path", "animation.gif".to_string())), + "file.export_apng" => Some((tr_noop!("Export animated PNG (full colour, transparent)"), "path", "animation.png".to_string())), + "file.export_webp" => Some((tr_noop!("Export animated WebP (lossless, transparent)"), "path", "animation.webp".to_string())), "file.export_svg" => Some((tr_noop!("Export frame as SVG"), "path", format!("frame_{:04}.svg", self.s.frame + 1))), "file.export_sprite_sheet" => Some((tr_noop!("Export sprite sheet (PNG + JSON frame map)"), "path", "sprites.png".to_string())), "file.export_video" => Some((tr_noop!("Export video (.webm or .mp4, made with your ffmpeg)"), "path", "animation.webm".to_string())), diff --git a/src/dialogs.rs b/src/dialogs.rs index 30041185..390d3ffc 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -201,7 +201,7 @@ impl Entry { /// Commands the palette can run without extra input (everything optional, or prompted). fn runnable(c: &CommandSpec) -> bool { - if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") { + if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") { return true; } let inner = c.params.trim().trim_start_matches('{').trim_end_matches('}'); diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index e4800e85..c633427d 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -587,7 +587,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("element.set_color_effect", serde_json::json!({"style": style})); })); } - for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "start"] { + for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "publishanim", "start"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] { @@ -607,12 +607,12 @@ fn status_lines_for_every_result_are_translated() { "kb": 12, "layers": 2, "masks": 1, "elements": 3, "report": "Imported walk.fla.", "copied": 2, "cut": 2, "pasted": 2, "removed": 2, "cleared": 2, "original_newer": true, "sounds": 1, "name": "beat", "sound": 1, "log": ["Did it."], "installed": [{"name": "Tint", "version": "1.0"}], "failed": ["bad.wasm: not a plug-in"], "replaced": "Tint 0.9", - "plugin": {"name": "Tint", "version": "1.0"}, "undone": "Move", "redone": "Move", + "plugin": {"name": "Tint", "version": "1.0"}, "undone": "Move", "redone": "Move", "bytes": 4096, "stored_frames": 2, }); let bare = json!({}); let ids = [ "file.new", "file.open", "file.recover", "file.discard_recovery", "file.save", "file.save_as", "file.import", "file.import_to_library", - "file.export_audio", "file.export_sprite_sheet", "file.export_html", "file.export_lottie", "file.export_png", "file.export_gif", + "file.export_audio", "file.export_sprite_sheet", "file.export_html", "file.export_lottie", "file.export_png", "file.export_gif", "file.export_apng", "file.export_webp", "sound.delete", "edit.undo", "edit.redo", "edit.delete", "layer.delete", "draw.erase_all", "scene.delete", "scene.new", "timeline.clear_keyframe", "timeline.copy_frames", "timeline.cut_frames", "timeline.paste_frames", "timeline.remove_frame", "plugin.run", "plugin.install", "plugin.remove", "plugin.reload", diff --git a/src/main.rs b/src/main.rs index 516f306a..7bf2894a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -204,7 +204,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|button|testhits|exporthtml|publish|publishreport|sound|envelope|library|librarymenu|colour]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/platform.rs b/src/platform.rs index b612b7c7..de1b2d25 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -260,6 +260,8 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { match cmd { "file.export_png" => (tr_noop!("PNG image"), &["png"]), "file.export_gif" => (tr_noop!("Animated GIF"), &["gif"]), + "file.export_apng" => (tr_noop!("Animated PNG"), &["png", "apng"]), + "file.export_webp" => (tr_noop!("Animated WebP"), &["webp"]), "file.export_svg" => (tr_noop!("SVG image"), &["svg"]), "file.export_lottie" => (tr_noop!("Lottie animation"), &["json"]), "file.export_html" => (tr_noop!("Web page"), &["html", "htm"]), diff --git a/src/publish_panel.rs b/src/publish_panel.rs index ebb86db3..8be65d31 100644 --- a/src/publish_panel.rs +++ b/src/publish_panel.rs @@ -81,6 +81,8 @@ pub fn label(f: PublishFormat) -> &'static str { crate::i18n::t(match f { PublishFormat::Html => tr_noop!("HTML canvas"), PublishFormat::Gif => tr_noop!("Animated GIF"), + PublishFormat::Apng => tr_noop!("Animated PNG"), + PublishFormat::Webp => tr_noop!("Animated WebP"), PublishFormat::Video => tr_noop!("Video"), PublishFormat::Lottie => tr_noop!("Lottie"), PublishFormat::SpriteSheet => tr_noop!("Sprite sheet"), @@ -96,6 +98,8 @@ fn about(f: PublishFormat) -> &'static str { crate::i18n::t(match f { PublishFormat::Html => tr_noop!("One web page that plays the movie, buttons and actions included."), PublishFormat::Gif => tr_noop!("An animated GIF, with exact frame timing."), + PublishFormat::Apng => tr_noop!("An animated PNG: full colour and real transparency, for the web and chat apps."), + PublishFormat::Webp => tr_noop!("An animated WebP, lossless: full colour and real transparency, smaller than PNG."), PublishFormat::Video => tr_noop!("WebM or MP4 video, made with your ffmpeg (ffmpeg.org)."), PublishFormat::Lottie => tr_noop!("A Lottie animation (JSON) for web and apps."), PublishFormat::SpriteSheet => tr_noop!("Frames in a grid on one PNG, with a JSON frame map beside it."), @@ -402,6 +406,23 @@ fn scale_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, scale: f32) { }); } +/// How many times it plays: forever, or a count. +fn plays_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, plays: u32) { + let mut forever = plays == 0; + form_row(ui, FORM_LABEL_DIALOG, tr!("Playback"), |ui| { + if crate::theme::checkbox(ui, &mut forever, tr!("Loop forever")).on_hover_text(tr!("Off: it plays the number of times you set, then stops on the last frame")).changed() { + set(app, f, "loop", json!(if forever { 0 } else { 1 }), false); + } + if !forever { + let mut n = plays.max(1); + ui.label(text(Type::Label, tr!("Plays"))); + if ui.add(egui::DragValue::new(&mut n).range(1..=anicraft_engine::doc::publish::MAX_PLAYS).speed(0.1)).named(tr!("Plays")).changed() { + set(app, f, "loop", json!(n), true); + } + } + }); +} + /// Which movie frames: all of them, or from one to another (shown 1-based, as the timeline). fn range_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, r: FrameRange) { let total = app.s.doc.frame_count(); @@ -467,6 +488,13 @@ fn options(app: &mut App, ui: &mut egui::Ui, f: PublishFormat) { scale_row(app, ui, f, p.gif.scale); check(app, ui, f, "loop", p.gif.looping, tr!("Loop"), tr!("Off: it plays once and stops on the last frame")); } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background) = if f == PublishFormat::Apng { (p.apng.range, p.apng.scale, p.apng.plays, p.apng.background) } else { (p.webp.range, p.webp.scale, p.webp.plays, p.webp.background) }; + range_row(app, ui, f, range); + scale_row(app, ui, f, scale); + plays_row(app, ui, f, plays); + check(app, ui, f, "background", background, tr!("Stage colour as background"), tr!("Off: transparent")); + } PublishFormat::Video => { range_row(app, ui, f, p.video.range); scale_row(app, ui, f, p.video.scale); From 0a6c085a9d7bb0fd2d3f1bbfa9dae51347e216d2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:03:13 -0700 Subject: [PATCH 059/192] docs: ADR 0063 animated PNG and WebP export, sizes versus GIF (M4) --- ATTRIBUTION.md | 1 + CHANGELOG.md | 16 ++++ docs/adr/0063-animated-png-and-webp-export.md | 96 +++++++++++++++++++ docs/adr/README.md | 1 - docs/legal/compliance.md | 9 ++ docs/performance.md | 18 ++++ docs/roadmap.md | 6 +- 7 files changed, 143 insertions(+), 4 deletions(-) create mode 100644 docs/adr/0063-animated-png-and-webp-export.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 44271455..5f962455 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -123,6 +123,7 @@ OR Apache-2.0) is noted in the table. | Resampling by cubic Hermite (Catmull-Rom) interpolation | `crates/audio/src/mix.rs` | E. Catmull and R. Rom, *A class of local interpolating splines* (1974); R. Keys, *Cubic convolution interpolation for digital image processing* (1981) | Public mathematical results. | | Ogg Vorbis decoding | `crates/audio/src/vorbis.rs` | `lewton` (MIT OR Apache-2.0) with `ogg` (BSD-3-Clause); Xiph.Org's open, royalty-free Vorbis I specification | Used as a library, not copied. | | MP3 (MPEG-1/2 audio layers I–III) decoding | `crates/audio/src/mp3.rs` | `nanomp3` (MIT OR Apache-2.0), a port of minimp3 (CC0) | Used as a library. The MP3 patents have expired; decoding only, no encoder. | +| Animated PNG and animated WebP files: APNG chunks (`acTL`, `fcTL`, `fdAT`), frame regions, blend and dispose ops; the WebP RIFF container (`VP8X`, `ANIM`, `ANMF`) | `crates/engine/src/anim.rs` | The APNG specification (Mozilla; part of W3C *Portable Network Graphics (PNG) Specification*, Third Edition); Google's public *WebP Container Specification* and *WebP Lossless Bitstream Specification*; PNG frame data by the `png` crate (MIT OR Apache-2.0), lossless WebP frames by `image-webp` (MIT OR Apache-2.0) | Open, royalty-free specifications; the chunks are written by our own code (ADR 0063). | ## Rust dependencies diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cc77a34..efa80c03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +* **Animated PNG and animated WebP export** (ADR 0063, M4). + * **File › Export › Export Animated PNG…** and **Export Animated WebP…** make full-colour + animations with real transparency, for the web and chat apps, where a GIF has 256 colours + and hard edges. WebP is lossless. Both are transparent by default; turn on the stage colour + as background if you want it. Loop forever, play once, or play a set number of times. + * Every frame is exactly what AniCraft renders. Frames that repeat the one before are stored + once and shown longer, and each later frame stores only the rectangle that changed, so + holds and small motions cost little. + * Timing is exact: APNG delays are fractions of the frame rate (29.97 fps stays 29.97), and + WebP's milliseconds never drift. + * Both are in **Publish Settings** (Animated PNG, Animated WebP) with frames, scale, loop and + background; in a browser they download. Headless: `file.export_apng`, `file.export_webp` + and `anicraft-cli apng` / `webp`. + * On the sample (48 frames, 1280 × 720) the APNG is 2.0 MB and the WebP 1.8 MB, against the + GIF's 1.4 MB, which has only 256 colours; both take less time to make than the GIF. + * **Publish Settings and Publish** (ADR 0060, M8). * **File › Publish Settings** (Ctrl+Shift+F12) is a window that stays open while you work. It lists every format AniCraft exports (HTML canvas, animated GIF, video, Lottie, sprite diff --git a/docs/adr/0063-animated-png-and-webp-export.md b/docs/adr/0063-animated-png-and-webp-export.md new file mode 100644 index 00000000..a13330aa --- /dev/null +++ b/docs/adr/0063-animated-png-and-webp-export.md @@ -0,0 +1,96 @@ +# ADR 0063: Animated PNG and animated WebP export + +* Status: accepted (2026-11-11) +* Relates to: ADR 0002 (CPU renderer as the oracle), ADR 0004 (destructive actions), ADR 0017 + (plug-in policy), ADR 0036 (web build), ADR 0040 (interface languages), ADR 0060 (Publish + Settings) + +## Context + +AniCraft exports animated GIF, video through the user's ffmpeg, Lottie, an HTML canvas page and +sprite sheets. GIF has 256 colours per frame and 1-bit transparency: gradients band and soft +edges get a hard fringe over any background other than the one they were made on. Animators who +post to the web and chat apps want **full colour with real alpha** in one file that plays +everywhere without a player. Two formats do that and are supported by every current browser: +**APNG** (animated PNG) and **animated WebP**. + +The specifications are public: the APNG specification (Mozilla, now part of the W3C PNG +Third Edition) and Google's WebP container and lossless bitstream specifications. Both +formats are royalty-free. + +## Decision + +1. **Two commands, one pipeline.** `file.export_apng` and `file.export_webp` (File › Export › + Export Animated PNG… / Export Animated WebP…) take `path`, `from`, `to` (movie frames, every + scene in order, as GIF), `scale`, `loop` (`true` = forever, the default; `false` = once; or + how many times it plays, 0 = forever, at most 65535) and `background` (default **off: + transparent**, the reason to pick these formats; on: the stage colour). Both live in + `crates/engine/src/anim.rs`. +2. **Rendering is GIF's.** Frames render on the CPU renderer (the oracle) in parallel, a batch + at a time. The batch is sized so that at most 32 Mpx are held at once (2 to 16 frames), so + memory stays bounded at any size. Publish's `Control` counts frames and cancels between + them. The size limit is GIF's (600 frames of 1280 × 720 in pixels). WebP frames are also + limited to 16384 px per side. +3. **Repeated frames are stored once.** A frame byte-identical to the one before it lengthens + that frame's delay and adds nothing else. Holds, which animators use all the time, cost + nothing. +4. **Only what changed is stored.** Each later frame is cut down to the smallest rectangle + holding every pixel that differs from the frame before it. Neither format disposes frames + (dispose op *none*): each frame is drawn over the one before it. + * **APNG**: when every changed pixel in the rectangle is opaque, the frame **blends over** + the canvas and its unchanged pixels are written fully transparent. They compress to + almost nothing, and a transparent pixel blended over leaves the canvas exactly as it was. + Otherwise (semi-transparent edges in a transparent export) the rectangle **replaces** + what is there (blend op *source*). Both are exact. + * **WebP**: rectangles start on even pixels (the format halves offsets) and always replace + (no blending). The decoders' blend (libwebp's, and `image-webp`'s port of it) rounds an + opaque pixel's channels down by one, so blending would not be lossless. +5. **Timing is exact.** The frame rate is taken as a fraction p/q (24 → 24/1, 29.97 → + 2997/100, 23.976 → 2997/125). + * APNG delays are fractions: a frame shown for k frames has a delay of k·q/p s, reduced. + 2 frames at 29.97 fps is 200/2997 s, never a rounded 67 ms. + * WebP durations are whole milliseconds. Each one is the difference between the rounded + starts of this frame and the next, so the rounding never adds up and the running time + is exact to the millisecond. + * A delay longer than one frame header holds (65535/q frames in APNG, 4.6 hours in WebP) + continues as extra frames that change nothing: one transparent pixel blended over the + corner. Timing is never cut short. +6. **Frames compress in parallel; we write the container.** Each frame's rectangle is + compressed on the thread pool as an image of its own: a PNG from the `png` crate (already + in the tree; RGBA8, adaptive filters, its best compression), or a lossless WebP from + `image-webp` (MIT OR Apache-2.0, pure Rust, `#![forbid(unsafe_code)]`). The file is then + put together in order by hand from the published chunk layouts. For APNG that is `IHDR`, + `acTL`, `fcTL` with `IDAT` for the first frame (so a plain PNG viewer shows the first + frame), `fcTL` with `fdAT` for the rest, and `IEND`. For WebP it is `RIFF`/`WEBP`, `VP8X`, + `ANIM` and one `ANMF` per frame wrapping that frame's `VP8L` chunk. + * The `png` crate can write APNG itself, but only from raw pixels, one frame after another + on one thread. Compression is most of the cost, so we use the crate for each frame's + data and write the chunks (a length, a type, the data and a CRC-32) ourselves. + `image-webp` has no animation encoder at all. +7. **Lossless WebP only, for now.** There is no permissively licensed, pure-Rust lossy (VP8) + WebP encoder on crates.io: `image-webp` encodes lossless only, and the `webp` and + `libwebp-sys` crates bind the C library, which this project does not build. The + commands therefore have no `quality` parameter yet. When a permissive pure-Rust VP8 + encoder exists, `quality` (lossy, with an `ALPH` chunk for alpha) slots into step 6 + without changing anything else. +8. **Everywhere GIF is.** File › Export lists both. Publish Settings (ADR 0060) gains + *Animated PNG* (`{name}_animated.png`, since `{name}.png` belongs to the PNG image; `.png` + or `.apng`) and *Animated WebP* (`{name}.webp`), each with frames, scale, loop forever or a + play count, and stage colour as background. Older profiles open with both off. Replacing a + file confirms (ADR 0004). Plug-ins can't call either command, like every `file.*` + command (ADR 0017). The CLI has `apng` and `webp` beside `gif`. In the web build the file + becomes a download, as GIF's does (ADR 0036). + +## Consequences + +* Every frame of both formats decodes back to the CPU renderer's pixels exactly (tests decode + with the `png` crate's APNG reader, compositing by the APNG rules, and `image-webp`'s + animation decoder), along with the delays, play counts, repeated-frame merging and the + rectangles. +* On the sample (48 frames, 1280 × 720) APNG is 2019 KB and WebP 1829 KB, against GIF's + 1464 KB of 256-colour frames; at half size they are 741 KB, 666 KB and 660 KB. Both are + faster to make than GIF: 0.18 s and 0.13 s against 0.42 s (docs/performance.md). +* Some players clamp very short delays. 240 fps is about 4 ms a frame, and a few browsers + slow down frames shorter than 10–20 ms, as they do for GIF. This is not worked around. +* `image-webp` is a new dependency. Its licence (MIT OR Apache-2.0) and its dependencies + (`byteorder-lite`, `quick-error`) are already allowed by `deny.toml`. diff --git a/docs/adr/README.md b/docs/adr/README.md index 0dd0bd2f..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0063 | m4/animated-png-webp | Animated PNG and animated WebP export | diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index 4ba95ee9..14884729 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -95,6 +95,15 @@ page's player in it. Nothing of it is in the app or the CLI. No new licence. The JavaScript is our own code (`crates/render/src/html/`), MIT OR Apache-2.0 like the rest, and uses no npm packages. +### Animated PNG and WebP (2026-11-11, ADR 0063) + +New crate, from crates.io: `image-webp` 0.2 (lossless WebP encoding and decoding in pure Rust, +`#![forbid(unsafe_code)]`, MIT OR Apache-2.0). Its dependencies, `byteorder-lite` (Unlicense +OR MIT) and `quick-error` (MIT OR Apache-2.0), were already in the tree. No new licence. APNG frames use the `png` crate already in +the tree. There is no lossy WebP yet: the only lossy encoders on crates.io bind the C libwebp +library, which this project does not build. APNG and WebP are both royalty-free (see the +codec table). + ### Sound (2026-11-09, ADR 0020) The audio slice adds, all permissive and from crates.io: `lewton` (Ogg Vorbis decoding, MIT OR diff --git a/docs/performance.md b/docs/performance.md index 8063616f..0e2f6ab6 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -230,6 +230,24 @@ frames 12, 30 and 48) with hairlines: onion ±5 outlines **17.1 ms** against 14. table in step. The GPU stage's are `BUDGETS` in `crates/gpu/examples/gpu_bench.rs` (`--check`; the CLI has no GPU). +## Animated PNG and WebP (2026-11-11, ADR 0063) + +The sample, all 48 frames, release build, Windows 10, 32 threads +(`cargo test --release -p anicraft-engine anim::tests::sizes -- --ignored --nocapture`). +Times include rendering every frame. + +| Export | 1280 × 720 | Time | 640 × 360 | Time | +|---|---|---|---|---| +| Animated GIF (256 colours, 1-bit alpha) | 1464 KB | 421 ms | 660 KB | 110 ms | +| Animated PNG | 2019 KB | 183 ms | 741 KB | 52 ms | +| Animated WebP, lossless | 1829 KB | 130 ms | 666 KB | 36 ms | + +The sample moves something in every frame, so all 48 frames are stored. Its sky is a full-stage +shape, so the transparent and stage-colour exports come out the same size. Compressing each +APNG frame at the `png` crate's best level instead of its default brought the file from 3387 KB +to 2019 KB for 25 % more time. The frames compress in parallel, which is why both formats are +faster than GIF, whose LZW coding runs on one thread. + ## Sound (2026-11-09, ADR 0020) Release build, Windows 10, one 120-second 48 kHz stereo sine, through `anicraft-cli run` diff --git a/docs/roadmap.md b/docs/roadmap.md index a5bbffdb..f8942320 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -14,9 +14,9 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | -| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | +| Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. Not yet: exact drop positions on the desktop (winit 0.30 gives none during a drag; a drop waits for the first pointer move, else lands mid-view), SVG into the Library, drops on the timeline, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. Not yet: exact drop positions on the desktop (winit 0.30 gives none during a drag; a drop waits for the first pointer move, else lands mid-view), SVG into the Library, drops on the timeline, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | @@ -36,7 +36,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: camera colour effects beyond tint, a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | -| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | +| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | From ccc1a34a8f6ed2720718e92604badfd60dd807e1 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 17:04:58 -0700 Subject: [PATCH 060/192] docs(adr): reserve 0062 for Test Movie in its own window (M8) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..af0902f4 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0062 | m8/test-movie-window | Test Movie in its own window, and opening documents on macOS | From a760667d5520b25fb808bdf5801626dc08d7dd5f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:03:14 -0700 Subject: [PATCH 061/192] feat(shell): Test Movie in its own window, and documents macOS hands over (M8) --- Cargo.lock | 12 + Cargo.toml | 8 + src/a11y.rs | 16 +- src/app.rs | 47 +++- src/dialogs.rs | 17 ++ src/drop.rs | 61 +++++ src/i18n/tests.rs | 9 +- src/main.rs | 195 +++++++++----- src/platform.rs | 236 +++++++++++++++++ src/prefs.rs | 17 ++ src/test_movie.rs | 634 +++++++++++++++++++++++++++++++--------------- 11 files changed, 975 insertions(+), 277 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 40120ca7..a8c54644 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -228,6 +228,7 @@ dependencies = [ "craft-update", "eframe", "egui", + "fmv-macos-events", "fontdb", "js-sys", "rfd", @@ -1684,6 +1685,17 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "fmv-macos-events" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55" +dependencies = [ + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "foldhash" version = "0.1.5" diff --git a/Cargo.toml b/Cargo.toml index fbd86a5a..181af8e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -114,6 +114,14 @@ rfd.workspace = true # Sound output (Apache-2.0): WASAPI on Windows, CoreAudio on macOS, ALSA on Linux and the BSDs. cpal = { version = "0.18", optional = true } +# macOS hands a double-clicked document to the app as an Apple Event, which winit 0.30 doesn't +# deliver (ADR 0062). This small crate (MIT OR Apache-2.0, ~170 lines, read in full) registers the +# open-documents and quit handlers with AppKit and hands us plain paths, so our code stays free of +# `unsafe`. Pinned exactly: it is young, and a new version is read again before it comes in. Its +# objc2 / objc2-app-kit / objc2-foundation are the versions wgpu already brings on macOS. +[target.'cfg(target_os = "macos")'.dependencies] +fmv-macos-events = "=0.1.0" + # The web build (ADR 0036, docs/web.md). The window draws with WebGL2 (glow): every current # browser has it, the stage is drawn on the CPU there, and leaving wgpu out keeps the download # smaller. The browser glue is wasm-bindgen's (MIT OR Apache-2.0), already under eframe's web diff --git a/src/a11y.rs b/src/a11y.rs index 38603b04..53c33459 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -97,6 +97,15 @@ pub fn name_title_bar(shown: &Option>, title: &str) { } } +/// Names the title bar of the window `ui` is drawn in (a window egui made itself, such as its +/// stand-in for a viewport where there is no window system). +pub fn name_own_title_bar(ui: &egui::Ui, title: &str) { + ui.ctx().accesskit_node_builder(ui.layer_id().id.with("__title_click"), |node| { + node.set_role(egui::accesskit::Role::TitleBar); + node.set_label(title); + }); +} + /// How a [`slider`]'s number reads. #[derive(Clone, Copy, Default)] pub struct SliderLook { @@ -352,9 +361,14 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "start", "drop", "droplibrary"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "start", "drop", "droplibrary", "testmovie", "testmovieinside"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } + // Test Movie in a window of its own (ADR 0062): its controls, named in that window. + found.extend(check("test movie window", |a, ctx| { + ctx.set_embed_viewports(false); + a.open_panel(Some("testmovie")); + })); // The layer depth row shows on artwork layers once the scene has a camera. found.extend(check("layer depth", |a, _| { a.open_panel(Some("camera")); diff --git a/src/app.rs b/src/app.rs index 877bdd25..b5901470 100644 --- a/src/app.rs +++ b/src/app.rs @@ -418,7 +418,7 @@ pub struct App { title: String, /// Keyboard shortcuts in effect (defaults plus the user's changes) and their lookup table. pub keymap: keymap::Keymap, - shortcuts: Vec<(Modifiers, Key, &'static str)>, + pub(crate) shortcuts: Vec<(Modifiers, Key, &'static str)>, /// The shortcut editor is waiting for a key press: global shortcuts pause. pub key_capture: Option, /// Crash-recovery autosave and the copies earlier sessions left behind (ADR 0015). @@ -661,6 +661,16 @@ impl App { } } + /// Something the system asked of the app outside its windows (ADR 0062): documents open as + /// a drop on the window does, through the unsaved-changes guard; a quit goes through the + /// close guard. + pub fn system_request(&mut self, ctx: &egui::Context, r: platform::SystemRequest) { + match r { + platform::SystemRequest::Open(files) => crate::drop::open_from_system(self, &files), + platform::SystemRequest::Quit => ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close), + } + } + /// A file the browser handed over: it goes where the command reads it, and the command runs /// (through `request`, so opening over unsaved work asks first). fn open_picked(&mut self, p: platform::Picked) { @@ -1026,6 +1036,12 @@ impl App { ]}), ); } + Some("testmovieinside") => { + // Test Movie floating inside the editor (ADR 0062), as where there can't be a + // window of its own; for this run only (screenshot runs never save preferences). + self.prefs.test_movie_window = false; + self.open_panel(Some("testmovie")); + } Some(which @ ("actions" | "testmovie")) => { // The interactive sample: its Play button selected with the Actions panel on // its events, or playing in Test Movie with the pointer over the button. @@ -2174,16 +2190,7 @@ impl App { }) }); if let Some(img) = image { - let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect(); - let result = anicraft_render::encode_png(img.size[0] as u32, img.size[1] as u32, &rgba).map_err(|e| e.to_string()).and_then(|png| { - if let Some(dir) = shot.path.parent() - && !dir.as_os_str().is_empty() - { - std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; - } - std::fs::write(&shot.path, png).map_err(|e| e.to_string()) - }); - match result { + match write_screenshot(&shot.path, &img) { Ok(()) => println!("screenshot saved to {}", shot.path.display()), Err(e) => eprintln!("screenshot failed: {e}"), } @@ -2321,6 +2328,18 @@ pub(crate) fn app_mark(ctx: &egui::Context) -> egui::TextureHandle { tex } +/// Writes a window's screenshot as a PNG (screenshot runs), making its folder if needed. +pub(crate) fn write_screenshot(path: &std::path::Path, img: &egui::ColorImage) -> Result<(), String> { + let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect(); + let png = anicraft_render::encode_png(img.size[0] as u32, img.size[1] as u32, &rgba).map_err(|e| e.to_string())?; + if let Some(dir) = path.parent() + && !dir.as_os_str().is_empty() + { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + std::fs::write(path, png).map_err(|e| e.to_string()) +} + /// Opens a file or folder with the operating system's default handler. pub(crate) fn open_in_system(path: &std::path::Path) -> Result<(), String> { // Tests click every control (`i18n::tests`): they never start another program. @@ -2347,6 +2366,8 @@ impl eframe::App for App { /// A clean exit (saved, or the user chose Don't Save) removes this session's recovery /// copy; otherwise the work is written once more and offered at the next start. fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { + // The Test Movie window's place, for next time (ADR 0062). + crate::test_movie::remember_place(self); let clean = !self.s.is_dirty() || self.allow_close || self.shot.is_some(); self.recovery.finish(&self.s, clean); #[cfg(not(target_arch = "wasm32"))] @@ -2374,6 +2395,10 @@ impl App { if let Some(p) = platform::picked_file() { self.open_picked(p); } + // Documents the system handed over while running (macOS: Finder, the Dock; ADR 0062). + for r in platform::take_requests() { + self.system_request(&ctx, r); + } if self.glyph_check { // Fonts installed last frame are live now: can they draw the macOS key symbols? let ok = ctx.fonts_mut(|f| f.has_glyphs(&theme::font(theme::Type::Key), "⌘⇧⌥")); diff --git a/src/dialogs.rs b/src/dialogs.rs index 30041185..3599a32b 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -504,6 +504,23 @@ fn preferences(app: &mut App, ctx: &egui::Context) { form_note(ui, LW, text(Type::Caption, tr!("The timeline always leaves room before frame 1 for the playhead; this adds more. It stays the same at every zoom."))); }); + // Test Movie in a window of its own, or inside the editor (ADR 0062). + section(ui, "prefs_test_movie", Section::Rule, tr!("Test Movie"), None, |ui| { + form_row(ui, LW, tr!("Window"), |ui| { + ui.vertical(|ui| { + crate::theme::checkbox(ui, &mut p.test_movie_window, text(Type::Body, tr!("Play Test Movie in a window of its own"))); + let note = match crate::platform::movie_host(ui.ctx().embed_viewports(), true) { + crate::platform::MovieHost::Inside(why) => why.note().map(crate::i18n::t), + crate::platform::MovieHost::Window if !crate::platform::window_positions() => Some(tr!("Off: it floats inside the editor. On Wayland the desktop places the window, so it can't open where it was last.")), + crate::platform::MovieHost::Window => Some(tr!("Off: it floats inside the editor. The window opens where it was last.")), + }; + if let Some(note) = note { + form_note(ui, toggle_indent, text(Type::Caption, note)); + } + }); + }); + }); + section(ui, "prefs_files", Section::Rule, tr!("Files"), None, |ui| { form_row(ui, LW, tr!("File dialogs"), |ui| { ui.vertical(|ui| { diff --git a/src/drop.rs b/src/drop.rs index d7b94a56..e13eda97 100644 --- a/src/drop.rs +++ b/src/drop.rs @@ -343,6 +343,19 @@ pub fn run(app: &mut App, files: &[PathBuf], spot: Spot) { } } +/// Files the system asked the running app to open (macOS: a double-click in Finder, a drop on +/// the Dock icon, Open With; ADR 0062). The first document opens as a drop on the window would, +/// through the unsaved-changes guard; nothing is imported this way. +pub fn open_from_system(app: &mut App, files: &[PathBuf]) { + let files: Vec = files.iter().take(anicraft_engine::cmds_drop::MAX_DROPPED).cloned().collect(); + if files.iter().any(|f| kind_of(f) == DropKind::Document) { + app.playing = false; + run(app, &files, Spot::Window); + } else if let Some(f) = files.first() { + app.status_err(tr!("Can't open {file}: {why}", file = crate::recent::display_name(f), why = refusal(DropKind::Unsupported, DropTarget::Window, false))); + } +} + /// A name for a file the browser describes only by its type while it is dragged. fn guess_name(mime: &str) -> &'static str { match mime { @@ -535,4 +548,52 @@ mod tests { run(&mut app, &[dir.join("other.anicraft")], Spot::Stage(0.0, 0.0)); assert!(app.confirm.is_some()); } + + /// Documents the system hands the running app (macOS Finder, the Dock; ADR 0062) arrive as + /// requests, are read at the start of a frame, and open through the unsaved-changes guard. + #[test] + fn documents_the_system_hands_over_open_through_the_guard() { + use crate::platform::{SystemRequest, push_request}; + let dir = std::env::temp_dir().join(format!("anicraft-shell-system-open-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (walk, other) = (dir.join("walk.anicraft"), dir.join("other.anicraft")); + for f in [&walk, &other] { + let mut s = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + s.execute("file.save", &json!({"path": f.display().to_string()})).unwrap(); + } + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(PathBuf::from("unused.png"))); + crate::start::open(&mut app); + let frame = |app: &mut App| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() }, |ui| app.frame(ui)); + out.textures_delta.clear(); + out + }; + // At launch (macOS sends the launching document this way too): the start screen gives + // way to it; a picture beside it is left out, and the status says so. + push_request(SystemRequest::Open(vec![dir.join("photo.png"), walk.clone()])); + frame(&mut app); + assert_eq!(app.s.path.as_deref(), Some(walk.as_path())); + assert!(app.start.is_none(), "the start screen gave way"); + assert!(app.status.as_ref().is_some_and(|s| s.text.contains("photo.png")), "{:?}", app.status.as_ref().map(|s| &s.text)); + // While running, over unsaved work: it asks first, and nothing changes until it's answered. + app.run("layer.new", json!({})); + assert!(app.s.is_dirty()); + push_request(SystemRequest::Open(vec![other.clone()])); + frame(&mut app); + assert!(app.confirm.as_ref().is_some_and(|c| c.id == "file.open"), "the unsaved-changes guard asks"); + assert_eq!(app.s.path.as_deref(), Some(walk.as_path())); + app.confirm = None; + // Only files AniCraft can't open: one clear message, nothing else. + push_request(SystemRequest::Open(vec![dir.join("notes.txt")])); + frame(&mut app); + assert!(app.status.as_ref().is_some_and(|s| s.error && s.text.contains("notes.txt"))); + assert!(app.confirm.is_none()); + // The Dock's Quit closes the editor's window, which the close guard intercepts. + push_request(SystemRequest::Quit); + let out = frame(&mut app); + let closes = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.commands.contains(&egui::ViewportCommand::Close)); + assert!(closes, "a quit request closes the editor's window"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index e4800e85..bae09541 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -587,9 +587,14 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("element.set_color_effect", serde_json::json!({"style": style})); })); } - for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "start"] { + for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "start", "testmovie", "testmovieinside"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } + // Test Movie in a window of its own (ADR 0062; egui stands in for the window system here). + found.extend(click_everything("test movie window", |a, ctx| { + ctx.set_embed_viewports(false); + a.open_panel(Some("testmovie")); + })); for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] { found.extend(click_everything(&format!("{tool:?}"), |a, _| a.tool = tool)); } @@ -777,7 +782,7 @@ fn screen_reader_names_are_translated_too() { found.extend(untranslated_names("library item", |a, _| { a.library_sel = a.s.doc.library.first().map(|s| crate::app::LibraryItem::Symbol(s.id)); })); - for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testscript", "exporthtml", "envelope"] { + for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testmovieinside", "testscript", "exporthtml", "envelope"] { found.extend(untranslated_names(panel, |a, _| a.open_panel(Some(panel)))); } assert!(found.is_empty(), "{} screen-reader names not translated in the pseudo-locale:\n{}", found.len(), found.join("\n")); diff --git a/src/main.rs b/src/main.rs index 516f306a..f5e7b30f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -95,7 +95,7 @@ fn open_session(file: Option<&Path>) -> (Session, Option) { /// `--theme` / `--scale`: the look for this run only (screenshots of high contrast or 200 %), /// over the saved preferences, without saving them. #[cfg(not(target_arch = "wasm32"))] -#[derive(Clone, Default)] +#[derive(Clone, Debug, Default, PartialEq)] struct Look { theme: Option, scale: Option, @@ -121,6 +121,8 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o "AniCraft", options, Box::new(move |cc| { + // A document the system hands over while AniCraft is idle wakes it (ADR 0062). + platform::wake_on_requests(&cc.egui_ctx); let starting_fresh = file_given.is_none() && shot.is_none(); let mut a = app::App::new(cc, session, shot); if a.shot.is_none() { @@ -148,6 +150,77 @@ fn main() { web::start(); } +/// What the command line asks for. A plain argument is the document to open: how Windows +/// (`"%1"` in the MSI's file association) and Linux (`Exec=anicraft %f` in the desktop entry) +/// hand over a double-clicked document. macOS sends it as an Apple Event instead (ADR 0062). +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug, Default, PartialEq)] +struct Args { + shot: Option, + file: Option, + open: Option, + renderer: Option, + look: Look, + /// `--version` / `--help`: print and leave. + print: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug, PartialEq)] +enum Print { + Version, + Help, +} + +/// Reads the arguments (without the program name). `Err` is the message for a bad one. +#[cfg(not(target_arch = "wasm32"))] +fn parse_args(args: impl IntoIterator) -> Result { + let mut out = Args::default(); + let mut args = args.into_iter(); + while let Some(a) = args.next() { + match a.as_str() { + "--screenshot" => out.shot = Some(PathBuf::from(args.next().ok_or("--screenshot needs a file name")?)), // i18n-exempt: a console message + "--open" => out.open = args.next(), + "--renderer" => out.renderer = args.next(), + "--theme" => match args.next().as_deref() { + Some("graphite") => out.look.theme = Some(theme::Palette::Graphite), + Some("high-contrast") => out.look.theme = Some(theme::Palette::HighContrast), + other => return Err(format!("--theme takes graphite or high-contrast, not {}", other.unwrap_or("nothing"))), // i18n-exempt: a console message + }, + "--scale" => match args.next().and_then(|s| s.trim_end_matches('%').parse::().ok()) { + Some(pct) if pct.is_finite() => out.look.scale = Some(pct / 100.0), + _ => return Err("--scale takes a percentage, such as 150".into()), // i18n-exempt: a console message + }, + "--lang" => match args.next() { + Some(code) if i18n::known(&code) => out.look.lang = Some(code), + other => { + let offered: Vec<&str> = i18n::offered().into_iter().map(|(c, _)| c).collect(); + return Err(format!("--lang takes auto, pseudo or a language this build has ({}), not {}", offered.join(", "), other.as_deref().unwrap_or("nothing"))); // i18n-exempt: a console message + } + }, + // Printed by the release packaging checks and for bug reports. + "--version" | "-V" => out.print = Some(Print::Version), + "--help" | "-h" => out.print = Some(Print::Help), + // Not a file: what older macOS added when Finder started an app. + other if platform::is_system_argument(other) => {} + other => out.file = Some(PathBuf::from(other)), + } + } + Ok(out) +} + +/// `--help` (the console's text, in English). +#[cfg(not(target_arch = "wasm32"))] +// i18n-exempt: the --help console text +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|button|testhits|exporthtml|publish|publishreport|sound|envelope|library|librarymenu|colour]\n\ + --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ + --open shows a panel at start (handy with --screenshot for visual checks)\n\ + ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ + --theme the interface palette for this run (not saved)\n\ + --scale the interface scale for this run, 75 to 200 (not saved)\n\ + --lang the interface language for this run (not saved); pseudo tests the layout\n\ + Headless use: anicraft-cli --help"; + #[cfg(not(target_arch = "wasm32"))] fn main() -> eframe::Result { if let Some(result) = updates::finish_helper() { @@ -157,71 +230,32 @@ fn main() -> eframe::Result { } std::process::exit(i32::from(failed)); } - let mut shot: Option = None; - let mut file: Option = None; - let mut open: Option = None; - let mut renderer_arg: Option = None; - let mut look = Look::default(); - let mut args = std::env::args().skip(1); - while let Some(a) = args.next() { - match a.as_str() { - "--screenshot" => match args.next() { - Some(p) => shot = Some(PathBuf::from(p)), - None => { - eprintln!("--screenshot needs a file name"); - std::process::exit(2); - } - }, - "--open" => open = args.next(), - "--renderer" => renderer_arg = args.next(), - "--theme" => match args.next().as_deref() { - Some("graphite") => look.theme = Some(theme::Palette::Graphite), - Some("high-contrast") => look.theme = Some(theme::Palette::HighContrast), - other => { - eprintln!("--theme takes graphite or high-contrast, not {}", other.unwrap_or("nothing")); - std::process::exit(2); - } - }, - "--scale" => match args.next().and_then(|s| s.trim_end_matches('%').parse::().ok()) { - Some(pct) if pct.is_finite() => look.scale = Some(pct / 100.0), - _ => { - eprintln!("--scale takes a percentage, such as 150"); - std::process::exit(2); - } - }, - "--lang" => match args.next() { - Some(code) if i18n::known(&code) => look.lang = Some(code), - other => { - let offered: Vec<&str> = i18n::offered().into_iter().map(|(c, _)| c).collect(); - eprintln!("--lang takes auto, pseudo or a language this build has ({}), not {}", offered.join(", "), other.as_deref().unwrap_or("nothing")); - std::process::exit(2); - } - }, - // Printed by the release packaging checks and for bug reports. - "--version" | "-V" => { - println!("AniCraft {} ({})", env!("CARGO_PKG_VERSION"), app::RELEASE_STAGE); - return Ok(()); - } - "--help" | "-h" => { - println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|button|testhits|exporthtml|publish|publishreport|sound|envelope|library|librarymenu|colour]\n\ - --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ - --open shows a panel at start (handy with --screenshot for visual checks)\n\ - ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ - --theme the interface palette for this run (not saved)\n\ - --scale the interface scale for this run, 75 to 200 (not saved)\n\ - --lang the interface language for this run (not saved); pseudo tests the layout\n\ - Headless use: anicraft-cli --help" - ); - return Ok(()); - } - other => file = Some(PathBuf::from(other)), + let args = match parse_args(std::env::args().skip(1)) { + Ok(a) => a, + Err(e) => { + eprintln!("{e}"); + std::process::exit(2); } + }; + match args.print { + Some(Print::Version) => { + println!("AniCraft {} ({})", env!("CARGO_PKG_VERSION"), app::RELEASE_STAGE); + return Ok(()); + } + Some(Print::Help) => { + println!("{HELP}"); + return Ok(()); + } + None => {} } + let Args { shot, file, open, renderer, look, .. } = args; + // macOS hands documents over as Apple Events, the one that launched the app included: listen + // from before the event loop starts until it ends (ADR 0062). + let _documents = platform::listen_for_documents(); // wgpu first (Vulkan/Metal/DX12). If it cannot start (old GPU, VM, missing drivers, common // on some Linux setups) retry once with OpenGL, unless the user forced a backend. - let forced = platform::forced_renderer(renderer_arg.as_deref()); + let forced = platform::forced_renderer(renderer.as_deref()); let first = forced.unwrap_or(eframe::Renderer::Wgpu); match run(first, file.as_deref(), shot.clone(), open.clone(), look.clone()) { Err(e) if forced.is_none() && first == eframe::Renderer::Wgpu => { @@ -232,6 +266,45 @@ fn main() -> eframe::Result { } } +#[cfg(test)] +mod args_tests { + use super::*; + + fn parse(args: &[&str]) -> Args { + parse_args(args.iter().map(|a| a.to_string())).unwrap_or_else(|e| panic!("{args:?}: {e}")) + } + + /// Windows (`"%1"`) and Linux (`%f`) hand a double-clicked document over as the one plain + /// argument, spaces and all; it opens through `file.open`, as File › Open does. + #[test] + fn a_double_clicked_document_arrives_on_the_command_line_and_opens() { + for path in [r"C:\Users\Ana Lima\My Films\walk cycle.anicraft", "/home/ana/Films/old scene.fla", "/home/ana/Films/Scene/DOMDocument.xfl", "relative.anicraft"] { + assert_eq!(parse(&[path]).file, Some(PathBuf::from(path)), "{path}"); + } + // The process serial number older macOS added is not a file. + assert_eq!(parse(&["-psn_0_1234567"]).file, None); + let a = parse(&["walk.anicraft", "--screenshot", "shots/x.png", "--open", "testmovie"]); + assert_eq!((a.file, a.shot, a.open.as_deref()), (Some(PathBuf::from("walk.anicraft")), Some(PathBuf::from("shots/x.png")), Some("testmovie"))); + assert!(parse_args(["--scale".to_string(), "lots".to_string()]).is_err()); + assert!(parse_args(["--screenshot".to_string()]).is_err()); + assert_eq!(parse(&["--version"]).print, Some(Print::Version)); + // And the file opens: the session starts with it, not the sample. + let dir = std::env::temp_dir().join(format!("anicraft-shell-args-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("walk cycle.anicraft"); + let mut s = Session::new(anicraft_engine::doc::sample::interactive()); + s.execute("file.save", &serde_json::json!({"path": path.display().to_string()})).unwrap(); + let file = parse(&[&path.display().to_string()]).file; + let (opened, _) = open_session(file.as_deref()); + assert_eq!(opened.path.as_deref(), Some(path.as_path())); + assert!(opened.doc == s.doc, "the document on the command line, not the sample"); + // A file that isn't there: the sample, never a crash. + let (fallback, _) = open_session(Some(&dir.join("missing.anicraft"))); + assert!(fallback.path.is_none()); + let _ = std::fs::remove_dir_all(&dir); + } +} + #[cfg(test)] mod guidelines_tests; #[cfg(test)] diff --git a/src/platform.rs b/src/platform.rs index b612b7c7..55160935 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -225,6 +225,16 @@ pub fn viewport(b: egui::ViewportBuilder) -> egui::ViewportBuilder { } } +/// Another window of the app (Test Movie, ADR 0062): the same app id, so docks and taskbars group +/// it with the editor, and the same icon. Native frames everywhere (the editor's unified macOS +/// title bar is for its menu row, which this window doesn't have). +pub fn secondary_window(b: egui::ViewportBuilder) -> egui::ViewportBuilder { + #[cfg(not(target_arch = "wasm32"))] + return b.with_app_id(APP_ID).with_icon(app_icon()); + #[cfg(target_arch = "wasm32")] + b +} + /// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets /// the tile on Apple's grid (with its transparent margin); elsewhere the full-bleed tile. #[cfg(not(target_arch = "wasm32"))] @@ -241,6 +251,181 @@ pub fn menu_inset() -> f32 { if OS == Os::Mac { 72.0 } else { 0.0 } } +// ----- more than one window (ADR 0062) --------------------------------------------------------- + +/// Where Test Movie plays. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MovieHost { + /// A window of its own on the desktop (an egui immediate viewport). + Window, + /// A floating window inside the editor, and why. + Inside(Inside), +} + +/// Why Test Movie plays inside the editor. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Inside { + /// Preferences › Test Movie says so. + Chosen, + /// A web page has one window (ADR 0036). + WebPage, + /// The windowing layer can't open another window here. + NoWindows, +} + +impl Inside { + /// What the floating window says about it (English: translated where it is shown); nothing + /// when the user chose it. + pub fn note(self) -> Option<&'static str> { + match self { + Inside::Chosen => None, + Inside::WebPage => Some(tr_noop!("Inside the editor: a web page can't open a window of its own")), + Inside::NoWindows => Some(tr_noop!("Inside the editor: this system can't open another window for it")), + } + } +} + +/// Where Test Movie plays, given whether egui embeds viewports (eframe sets that on the web and +/// wherever it has no multi-window support) and the user's choice. +pub fn movie_host(embed_viewports: bool, own_window: bool) -> MovieHost { + movie_host_for(OS, embed_viewports, own_window) +} + +pub fn movie_host_for(os: Os, embed_viewports: bool, own_window: bool) -> MovieHost { + if os == Os::Web { + MovieHost::Inside(Inside::WebPage) + } else if embed_viewports { + MovieHost::Inside(Inside::NoWindows) + } else if !own_window { + MovieHost::Inside(Inside::Chosen) + } else { + MovieHost::Window + } +} + +/// Whether AniCraft can put a window back where it was. Wayland never tells an app where its +/// windows are, nor lets it place them: the desktop does. +pub fn window_positions() -> bool { + let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); + window_positions_for(OS, env("WAYLAND_DISPLAY").is_some(), env("WINIT_UNIX_BACKEND").as_deref()) +} + +/// winit picks Wayland when `WAYLAND_DISPLAY` is set, unless `WINIT_UNIX_BACKEND=x11`. +pub fn window_positions_for(os: Os, wayland_display: bool, winit_backend: Option<&str>) -> bool { + match os { + Os::Linux | Os::Other => !wayland_display || winit_backend.is_some_and(|b| b.eq_ignore_ascii_case("x11")), + Os::Web => false, + Os::Mac | Os::Windows => true, + } +} + +/// A remembered window corner, if it can still be used: finite, and on or beside the screen the +/// editor is on (a monitor to its left or right is fine; a window lost far off-screen isn't). +pub fn usable_position(at: [f32; 2], monitor: Option) -> Option { + let [x, y] = at; + if !x.is_finite() || !y.is_finite() { + return None; + } + let m = monitor.filter(|m| m.x > 0.0 && m.y > 0.0).unwrap_or(egui::vec2(16384.0, 16384.0)); + let ok = x >= -m.x && x <= 2.0 * m.x - 64.0 && y >= -m.y && y <= 2.0 * m.y - 64.0; + ok.then(|| egui::pos2(x, y)) +} + +// ----- documents the system asks AniCraft to open (ADR 0062) ------------------------------------ + +/// Something the system asked of the running app, outside its windows. +// Only macOS hands documents to a running app; elsewhere the tests make requests. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SystemRequest { + /// Open these files (macOS: a double-click in Finder, a drop on the Dock icon, Open With). + Open(Vec), + /// Quit (macOS: the Dock's Quit, logging out): through the unsaved-changes guard. + Quit, +} + +thread_local! { + /// Requests not yet handled. Filled on the main thread (AppKit calls back there), read by + /// the frame on the same thread. + static REQUESTS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Most requests kept between two frames (a flood of Apple Events can't grow memory). +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +const MAX_REQUESTS: usize = 64; + +/// Queues a request for the next frame. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub fn push_request(r: SystemRequest) { + REQUESTS.with(|q| { + let mut q = q.borrow_mut(); + if q.len() < MAX_REQUESTS { + q.push(r); + } + }); +} + +/// The requests that arrived since the last frame, in order. +pub fn take_requests() -> Vec { + #[cfg(target_os = "macos")] + MAC_INBOX.with(|i| { + if let Some(inbox) = i.borrow().as_ref() { + for e in inbox.drain() { + push_request(match e { + fmv_macos_events::Event::Open(paths) => SystemRequest::Open(paths), + fmv_macos_events::Event::Quit => SystemRequest::Quit, + }); + } + } + }); + REQUESTS.with(|q| std::mem::take(&mut *q.borrow_mut())) +} + +#[cfg(target_os = "macos")] +thread_local! { + static MAC_INBOX: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// Listens for documents the system hands over while AniCraft runs. Keep the result until the +/// event loop returns. On macOS it must start before the event loop does, so the document that +/// launched the app (sent as an Apple Event, not on the command line) isn't missed. Windows and +/// Linux pass that document on the command line (`main`), and a second document starts a second +/// AniCraft, so there is nothing to listen for there. +pub struct DocumentListener { + #[cfg(target_os = "macos")] + _registration: fmv_macos_events::Registration, +} + +#[cfg(not(target_arch = "wasm32"))] +pub fn listen_for_documents() -> DocumentListener { + #[cfg(target_os = "macos")] + { + let (registration, inbox) = fmv_macos_events::Registration::install(); + MAC_INBOX.with(|i| *i.borrow_mut() = Some(inbox)); + DocumentListener { _registration: registration } + } + #[cfg(not(target_os = "macos"))] + DocumentListener {} +} + +/// A request that arrives while the app is idle wakes it. +#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] +pub fn wake_on_requests(ctx: &egui::Context) { + #[cfg(target_os = "macos")] + MAC_INBOX.with(|i| { + if let Some(inbox) = i.borrow().as_ref() { + let ctx = ctx.clone(); + inbox.set_wake(move || ctx.request_repaint()); + } + }); +} + +/// Arguments the system adds that aren't files: macOS before 10.9 passed `-psn_0_12345` (the +/// process serial number) to apps started from Finder. +pub fn is_system_argument(arg: &str) -> bool { + arg.starts_with("-psn_") +} + /// Renderer requested by `--renderer` / `ANICRAFT_RENDERER` (`wgpu` or `gl`), if any. #[cfg(not(target_arch = "wasm32"))] pub fn forced_renderer(arg: Option<&str>) -> Option { @@ -360,6 +545,57 @@ mod tests { } } + /// Test Movie gets a window of its own wherever the windowing layer can make one and the user + /// wants it; elsewhere it floats inside the editor and says why (ADR 0062). + #[test] + fn test_movie_falls_back_inside_the_editor_and_says_why() { + for os in [Os::Windows, Os::Mac, Os::Linux] { + assert_eq!(movie_host_for(os, false, true), MovieHost::Window, "{os:?}"); + assert_eq!(movie_host_for(os, false, false), MovieHost::Inside(Inside::Chosen)); + assert_eq!(movie_host_for(os, true, true), MovieHost::Inside(Inside::NoWindows)); + } + // A web page never has a second window, whatever egui or the preference say. + assert_eq!(movie_host_for(Os::Web, false, true), MovieHost::Inside(Inside::WebPage)); + assert!(Inside::Chosen.note().is_none(), "the user's own choice needs no explaining"); + assert!(Inside::WebPage.note().is_some_and(|n| n.contains("web page")) && Inside::NoWindows.note().is_some()); + // eframe embeds viewports where it can't open windows (the web, a headless context). + assert!(egui::Context::default().embed_viewports()); + } + + #[test] + fn wayland_hides_window_positions() { + assert!(window_positions_for(Os::Windows, false, None) && window_positions_for(Os::Mac, true, None)); + assert!(window_positions_for(Os::Linux, false, None), "X11"); + assert!(!window_positions_for(Os::Linux, true, None), "Wayland"); + assert!(window_positions_for(Os::Linux, true, Some("X11")), "XWayland, chosen"); + assert!(!window_positions_for(Os::Web, false, None)); + } + + #[test] + fn a_remembered_place_is_used_only_where_the_window_can_be_seen() { + let monitor = Some(egui::vec2(1920.0, 1080.0)); + assert_eq!(usable_position([100.0, 80.0], monitor), Some(egui::pos2(100.0, 80.0))); + assert!(usable_position([-1500.0, 100.0], monitor).is_some(), "a monitor to the left"); + assert!(usable_position([2500.0, 100.0], monitor).is_some(), "a monitor to the right"); + assert_eq!(usable_position([90_000.0, 0.0], monitor), None, "lost far off-screen"); + assert_eq!(usable_position([f32::NAN, 0.0], monitor), None); + assert!(usable_position([3000.0, 10.0], None).is_some(), "without the screen's size, a broad check"); + } + + #[test] + fn system_requests_arrive_in_order_and_are_bounded() { + assert!(take_requests().is_empty()); + push_request(SystemRequest::Open(vec![PathBuf::from("a.anicraft")])); + push_request(SystemRequest::Quit); + assert_eq!(take_requests(), vec![SystemRequest::Open(vec![PathBuf::from("a.anicraft")]), SystemRequest::Quit]); + assert!(take_requests().is_empty(), "each is handled once"); + for _ in 0..1000 { + push_request(SystemRequest::Quit); + } + assert_eq!(take_requests().len(), MAX_REQUESTS); + assert!(is_system_argument("-psn_0_8194") && !is_system_argument("walk.anicraft")); + } + #[test] fn renderer_override() { assert_eq!(forced_renderer(Some("gl")), Some(eframe::Renderer::Glow)); diff --git a/src/prefs.rs b/src/prefs.rs index 11a36e20..5c686a66 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -98,6 +98,12 @@ pub struct Prefs { pub recent: anicraft_engine::cmds_recent::RecentFiles, /// Show the start screen when AniCraft starts without a document to open (ADR 0059). pub start_screen: bool, + /// Test Movie plays in a window of its own (ADR 0062); off, or where a system can't open + /// one, it floats inside the editor. + pub test_movie_window: bool, + /// Where the Test Movie window was last, in points (its top-left corner); `None` until it + /// has been opened where the system says where windows are. + pub test_movie_pos: Option<[f32; 2]>, } /// Most publish presets kept, and the longest name one has. @@ -155,6 +161,8 @@ impl Default for Prefs { publish_presets: Default::default(), recent: Default::default(), start_screen: true, + test_movie_window: true, + test_movie_pos: None, } } } @@ -209,6 +217,7 @@ impl Prefs { }) .collect(); self.recent = std::mem::take(&mut self.recent).sanitized(); + self.test_movie_pos = self.test_movie_pos.filter(|[x, y]| x.is_finite() && y.is_finite() && x.abs() < 1e5 && y.abs() < 1e5); self } @@ -337,6 +346,14 @@ mod tests { let paths: Vec<_> = p.recent.entries().iter().map(|e| e.path.display().to_string()).collect(); assert_eq!(paths, ["a.anicraft"], "bad entries are skipped, the rest kept"); assert!(!p.start_screen, "and the other preferences with them"); + // Older files open Test Movie in its own window, with no remembered place (ADR 0062); + // a place someone broke by hand is forgotten, not used. + let p = Prefs::from_json(r#"{"ui_scale": 1.25}"#); + assert!(p.test_movie_window && p.test_movie_pos.is_none()); + let p = Prefs::from_json(r#"{"test_movie_window": false, "test_movie_pos": [120.5, 80]}"#); + assert_eq!((p.test_movie_window, p.test_movie_pos), (false, Some([120.5, 80.0]))); + assert_eq!(Prefs::from_json(r#"{"test_movie_pos": [1e9, 0]}"#).test_movie_pos, None); + assert_eq!(Prefs::from_json(&serde_json::to_string(&p).unwrap()), p, "both survive saving"); let p = Prefs::from_json(r#"{"recent": [{"path": "b.anicraft"}, {"path": "a.anicraft", "pinned": true}, {"path": "b.anicraft"}]}"#); let paths: Vec<_> = p.recent.entries().iter().map(|e| (e.path.display().to_string(), e.pinned)).collect(); assert_eq!(paths, [("a.anicraft".to_string(), true), ("b.anicraft".to_string(), false)]); diff --git a/src/test_movie.rs b/src/test_movie.rs index 467d3abc..fb2f1914 100644 --- a/src/test_movie.rs +++ b/src/test_movie.rs @@ -1,5 +1,8 @@ //! Test Movie (Control › Test Movie, Ctrl+Enter, as in Animate; ADR 0024): the movie played by -//! the interactive player in a window of its own, at the document's frame rate, with its +//! the interactive player in a window of its own on the desktop (ADR 0062; an egui immediate +//! viewport, sized to the stage, back where it was last), or floating inside the editor where +//! there can't be one (the web build) or by choice (Preferences › Test Movie), at the +//! document's frame rate, with its //! frame actions, frame scripts and buttons live under the pointer, and an Output panel for //! `trace` lines and messages. //! @@ -13,7 +16,7 @@ //! Its keyboard (ADR 0052): while the movie has the focus (it takes it when the window //! opens and when clicked), keys go to the movie's keyboard listeners as ActionScript key //! codes, Tab and the arrows included; shortcuts with Ctrl (⌘ on macOS) still reach the app, -//! and Esc closes the window. +//! and Esc or Ctrl+W (⌘W) closes the window. use crate::app::App; use crate::icons::Icon; @@ -120,6 +123,11 @@ pub struct TestMovie { focus: bool, /// Show Hit Areas: every button's hit area drawn over the movie (ADR 0057). pub hit_areas: bool, + /// The window of its own's size and place, once worked out (ADR 0062). + pub placement: Option, + /// Where the window of its own was last drawn (its outer top-left corner), when the system + /// says. + pub last_pos: Option, } impl TestMovie { @@ -160,9 +168,11 @@ pub fn open(app: &mut App) { let movie = Movie::start_seeded(&doc, if app.shot.is_some() { 0 } else { seed }, &mut runner); let name = app.s.path.as_ref().and_then(|p| p.file_stem()).map(|n| n.to_string_lossy().into_owned()); let skipped = anicraft_engine::player::kept_scripts(&doc).iter().filter(|k| !k.runs()).count(); - // Show Hit Areas stays as it was across a restart. - let hit_areas = app.test_movie.as_ref().is_some_and(|t| t.hit_areas); - let mut tm = TestMovie { doc, movie, paused: false, acc: 0.0, texture: None, shown: None, pointer: None, down: false, name, ms: 0.0, voices: Vec::new(), audio: false, skipped, focus: true, hit_areas }; + // Show Hit Areas, and the window's size and place, stay as they were across a restart. + let old = app.test_movie.as_ref(); + let hit_areas = old.is_some_and(|t| t.hit_areas); + let (placement, last_pos) = (old.and_then(|t| t.placement), old.and_then(|t| t.last_pos)); + let mut tm = TestMovie { doc, movie, paused: false, acc: 0.0, texture: None, shown: None, pointer: None, down: false, name, ms: 0.0, voices: Vec::new(), audio: false, skipped, focus: true, hit_areas, placement, last_pos }; // Sound only when there is some, and never in screenshot runs or tests. if sound::has_sounds(&tm.doc) && app.shot.is_none() { tm.resume(&mut app.sound); @@ -171,17 +181,165 @@ pub fn open(app: &mut App) { app.test_movie = Some(tm); } -/// The Test Movie window, when open. +/// What a frame of the Test Movie window asks of the app, done once the window is drawn. +#[derive(Default)] +struct Asked { + restart: bool, + close: bool, + /// Shortcuts with Ctrl (⌘) or Alt pressed in the window of its own: the app's commands. + commands: Vec<&'static str>, + quit: bool, +} + +/// The size and place a window of its own opens at, worked out once (a restart keeps them, so +/// the window stays where it is). +#[derive(Clone, Copy, Debug)] +pub struct Placement { + pub size: egui::Vec2, + pub at: Option, +} + +/// Room the controls and the Output take around the movie, in points. +const CHROME: egui::Vec2 = egui::vec2(24.0, 236.0); +/// The smallest window of its own. +const MIN_SIZE: [f32; 2] = [480.0, 320.0]; + +/// The window's size: the stage at 100 %, as in Animate, made smaller to fit 85 % of the +/// screen when it doesn't (aspect kept), never smaller than the controls need. +pub fn window_size(stage: egui::Vec2, monitor: Option) -> egui::Vec2 { + let stage = egui::vec2(stage.x.max(1.0), stage.y.max(1.0)); + let room = monitor.filter(|m| m.x > 0.0 && m.y > 0.0).map_or(egui::vec2(1600.0, 1000.0), |m| m * 0.85); + let k = ((room.x - CHROME.x) / stage.x).min((room.y - CHROME.y) / stage.y).clamp(0.05, 1.0); + let size = stage * k + CHROME; + egui::vec2(size.x.max(MIN_SIZE[0]), size.y.max(MIN_SIZE[1])) +} + +/// The Test Movie window, when open: a window of its own, or floating inside the editor where +/// there can't be one (ADR 0062). pub fn show(app: &mut App, ctx: &egui::Context) { + if app.test_movie.is_none() { + return; + } + let asked = match crate::platform::movie_host(ctx.embed_viewports(), app.prefs.test_movie_window) { + crate::platform::MovieHost::Window => own_window(app, ctx), + crate::platform::MovieHost::Inside(why) => inside(app, ctx, why), + }; + if asked.close { + close(app); + } else if asked.restart { + open(app); + } + // The app's shortcuts pressed over the movie, run in the editor's context (a command that + // talks to "the window" means the editor's). + for id in asked.commands { + app.invoke(id); + } + if asked.quit { + // Through the editor's close guard, so unsaved work is never lost. + ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close); + } +} + +/// Closes Test Movie, keeping where its window was. +pub fn close(app: &mut App) { + remember_place(app); + if app.test_movie.take().is_some_and(|tm| tm.audio) { + app.sound.stop(); + } +} + +/// Keeps where the window of its own is in the preferences, for next time (not in screenshot +/// runs, and not where the system doesn't say where windows are). +pub fn remember_place(app: &mut App) { + let Some(at) = app.test_movie.as_ref().and_then(|t| t.last_pos) else { return }; + let at = [at.x.round(), at.y.round()]; + if app.prefs.test_movie_pos == Some(at) || !crate::platform::window_positions() { + return; + } + app.prefs.test_movie_pos = Some(at); + if app.shot.is_none() + && let Err(e) = app.prefs.save() + { + app.status_err(tr!("Could not save preferences: {e}", e = e)); + } +} + +/// The id of the window of its own. +pub fn viewport_id() -> egui::ViewportId { + egui::ViewportId::from_hash_of("test_movie_window") +} + +fn title(tm: &TestMovie) -> String { + tr!("Test Movie — {name}", name = tm.name.as_deref().unwrap_or(tr!("Untitled"))) +} + +/// Test Movie in a window of its own: an immediate viewport, drawn in the editor's frame with +/// the editor's state (the sound output, the plug-ins, the shortcuts), so nothing is shared +/// across threads; its repaints run the editor's frame too (ADR 0062). +fn own_window(app: &mut App, ctx: &egui::Context) -> Asked { + let monitor = ctx.input(|i| i.viewport().monitor_size); + let remembered = app.prefs.test_movie_pos.and_then(|p| crate::platform::usable_position(p, monitor)); let plugins = &app.s.plugins; let out = &mut app.sound; - let Some(tm) = app.test_movie.as_mut() else { return }; + let shortcuts = &app.shortcuts; + let Some(tm) = app.test_movie.as_mut() else { return Asked::default() }; + let stage = egui::vec2(tm.doc.stage.width as f32, tm.doc.stage.height as f32); + // Worked out once the screen's size is known (not always on the very first frame). + let place = match (tm.placement, monitor) { + (Some(p), _) => p, + (None, Some(_)) => *tm.placement.insert(Placement { size: window_size(stage, monitor), at: remembered }), + (None, None) => Placement { size: window_size(stage, None), at: remembered }, + }; + let mut builder = egui::ViewportBuilder::default().with_title(title(tm)).with_inner_size(place.size).with_min_inner_size(MIN_SIZE); + if let Some(at) = place.at.filter(|_| crate::platform::window_positions()) { + builder = builder.with_position(at); + } + let builder = crate::platform::secondary_window(builder); + ctx.show_viewport_immediate(viewport_id(), builder, |ui, class| { + let mut asked = Asked::default(); + let (close_requested, outer) = ui.input(|i| (i.viewport().close_requested(), i.viewport().outer_rect)); + if let Some(r) = outer { + tm.last_pos = Some(r.min); + } + // Opened or restarted: the window comes to the front, with the keyboard. + if tm.focus { + ui.ctx().send_viewport_cmd(egui::ViewportCommand::Focus); + } + asked.restart = if class == egui::ViewportClass::EmbeddedWindow { + // egui's own stand-in, with no window system under it (tests): already in a window. + crate::a11y::name_own_title_bar(ui, &title(tm)); + body(tm, plugins, out, ui, None) + } else { + let frame = egui::Frame::NONE.fill(T.panel).inner_margin(egui::Margin::same(10)); + egui::CentralPanel::default().frame(frame).show(ui, |ui| body(tm, plugins, out, ui, None)).inner + }; + // Its keys: Esc and Ctrl+W (⌘W) close it, Ctrl+Q (⌘Q) quits, and the app's shortcuts + // with Ctrl (⌘) or Alt still work (Restart is Ctrl+Enter); the rest are the movie's. + let (close, quit, commands) = ui.input_mut(|i| { + let close = i.consume_key(egui::Modifiers::NONE, egui::Key::Escape) || i.consume_key(egui::Modifiers::COMMAND, egui::Key::W); + let quit = i.consume_key(egui::Modifiers::COMMAND, egui::Key::Q); + let fire: Vec<&'static str> = shortcuts.iter().filter(|(m, _, id)| (m.command || m.ctrl || m.alt) && !id.starts_with("view.") && !id.starts_with("tool.")).filter_map(|(m, k, id)| i.consume_key(*m, *k).then_some(*id)).collect(); + (close, quit, fire) + }); + asked.close = close_requested || close; + asked.quit = quit; + asked.commands = commands; + asked + }) +} + +/// Test Movie floating inside the editor: where there can't be a window of its own, or by choice. +fn inside(app: &mut App, ctx: &egui::Context, why: crate::platform::Inside) -> Asked { + let plugins = &app.s.plugins; + let out = &mut app.sound; + let Some(tm) = app.test_movie.as_mut() else { return Asked::default() }; let mut shown = true; let mut restart = false; let (sw, sh) = (tm.doc.stage.width as f32, tm.doc.stage.height as f32); let default_w = 760.0f32; let default_h = default_w * sh / sw.max(1.0) + 190.0; - let title = tr!("Test Movie — {name}", name = tm.name.as_deref().unwrap_or(tr!("Untitled"))); + let title = title(tm); + let note = why.note().map(crate::i18n::t); let win = egui::Window::new(title.clone()) .id(egui::Id::new("test_movie")) .open(&mut shown) @@ -190,203 +348,211 @@ pub fn show(app: &mut App, ctx: &egui::Context) { .default_size([default_w, default_h]) .default_pos(ctx.content_rect().center() - egui::vec2(default_w * 0.5 + 120.0, default_h * 0.5)) .min_size([320.0, 260.0]) - .show(ctx, |ui| { - // ---- controls ---- - ui.horizontal(|ui| { - if crate::timeline::icon_button(ui, &tr!("Restart from frame 1 with the document as it is now ({key})", key = crate::platform::shortcut_label("Ctrl+Enter")), None, Icon::First).clicked() { - restart = true; - } - let (icon, tip) = if tm.paused { (Icon::Play, tr!("Play")) } else { (Icon::Pause, tr!("Pause")) }; - if crate::timeline::icon_button(ui, tip, None, icon).clicked() { - tm.paused = !tm.paused; - tm.acc = 0.0; - if tm.paused { - out.stop(); - } else if tm.audio { - tm.resume(out); - } - } - if tm.paused && crate::timeline::icon_button(ui, tr!("Step one frame"), None, Icon::Next).clicked() { - let mut runner = ScriptRunner::new(plugins); - tm.movie.step(&tm.doc, &[], &mut runner); - tm.feed(out); - } - ui.add_space(8.0); - let st = &tm.movie.state; - let scene = tm.doc.scenes.get(st.scene).map_or("", |s| s.name.as_str()); - let frames = tm.doc.timeline(st.scene).frame_count(); - ui.label(text(Type::Body, scene).color(T.text_dim)); - ui.label(text(Type::Data, format!("{:>4} / {frames}", st.root.frame + 1))).on_hover_text(tr!("Main timeline frame")); - let what = if tm.paused { tr!("paused") } else if st.root.playing { tr!("playing") } else { tr!("stopped") }; - ui.label(text(Type::Caption, what)); - // A movie that listens for keys says where they go. - if tm.movie.state.stage.iter().any(|l| l.event.is_key()) { - let keys = if has_keys(ctx) { tr!("Keys go to the movie") } else { tr!("Click the movie to give it the keyboard") }; - ui.label(text(Type::Caption, keys).color(T.text_dim)); - } - ui.add_space(8.0); - ui.checkbox(&mut tm.hit_areas, tr!("Show hit areas")).on_hover_text(tr!("Draw where each button answers the pointer (its Hit frame) over the movie")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // i18n-exempt: numbers and units (data) - ui.label(text(Type::Data, format!("{:.0} fps · {:.1} ms", tm.doc.stage.fps, tm.ms)).color(T.text_faint)).on_hover_text(tr!("Frame rate, and the time the last picture took to draw")); - }); - }); - ui.add_space(4.0); - // ---- the movie, fitted to the window, with the pointer ---- - let output_h = 120.0f32.min(ui.available_height() * 0.4); - let avail = egui::vec2(ui.available_width(), (ui.available_height() - output_h - 40.0).max(60.0)); - let k = (avail.x / sw.max(1.0)).min(avail.y / sh.max(1.0)).max(0.01); - let size = egui::vec2(sw * k, sh * k); - let (outer, _) = ui.allocate_exact_size(egui::vec2(avail.x, size.y), egui::Sense::hover()); - let resp = ui.interact(outer, surface_id(), egui::Sense::click_and_drag()); - crate::a11y::surface(ui, &resp, tr!("The movie: point, click and type to play it")); - if tm.focus || resp.is_pointer_button_down_on() { - resp.request_focus(); - tm.focus = false; - } - // Tab and the arrows are the movie's keys while it has them, not focus moves. - if resp.has_focus() { - ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false })); - } - let rect = egui::Rect::from_center_size(outer.center(), size); - // The pointer, in stage coordinates, to the player. - let mut events = Vec::new(); - let to_stage = |p: egui::Pos2| Vec2::new((p.x - rect.left()) / k, (p.y - rect.top()) / k); - let latest = ui.input(|i| i.pointer.latest_pos()); - let inside = resp.hover_pos().is_some_and(|p| rect.contains(p)); - let down = resp.is_pointer_button_down_on(); - if let Some(p) = latest.map(to_stage) { - if inside && tm.pointer != Some(p) { - events.push(Event::Move(p)); - } - if !inside && tm.pointer.is_some() { - events.push(Event::Leave); - } - if down && !tm.down && inside { - events.push(Event::Down(p)); - } - // Released off the movie: an Up out there, which clicks nothing. - if !down && tm.down { - events.push(Event::Up(p)); - } - tm.pointer = inside.then_some(p); - } - tm.down = down && (tm.down || inside); - // The keyboard, while the movie has it (Ctrl/⌘ shortcuts stay the app's). - if resp.has_focus() { - ui.input(|i| { - for e in &i.events { - if let egui::Event::Key { key, pressed, modifiers, .. } = e - && !modifiers.command - && *key != egui::Key::Escape - && let Some(code) = key_code(*key) - { - events.push(if *pressed { Event::KeyDown(code) } else { Event::KeyUp(code) }); - } - } - }); - } - let mut runner = ScriptRunner::new(plugins); - tm.movie.input(&tm.doc, &events, &mut runner); - tm.feed(out); - if inside && tm.movie.state.hover.is_some() { - ctx.set_cursor_icon(egui::CursorIcon::PointingHand); - } - // ---- time: the document's frame rate, kept by the sound while it plays ---- - if !tm.paused { - let fps = f64::from(tm.doc.stage.fps.max(1.0)); - let rate = f64::from(out.rate().max(1)); - let heard = if tm.audio { out.movie_position() } else { None }; - let mut n = 0; - if let Some(pos) = heard { - let due = (pos as f64 * fps / rate).floor() as u64; - while tm.movie.state.tick < due && n < MAX_CATCH_UP { - tm.movie.step(&tm.doc, &[], &mut runner); - n += 1; - } - } else { - tm.acc += f64::from(ui.input(|i| i.stable_dt)).min(0.25); - while tm.acc >= 1.0 / fps && n < MAX_CATCH_UP { - tm.acc -= 1.0 / fps; - tm.movie.step(&tm.doc, &[], &mut runner); - n += 1; - } - if n == MAX_CATCH_UP { - tm.acc = 0.0; - } - } - tm.feed(out); - ctx.request_repaint(); - } - // ---- picture ---- - let ppp = ctx.pixels_per_point(); - let scale = (k * ppp).min(MAX_EDGE / sw.max(sh).max(1.0)); - let px = [((sw * scale).round() as u32).max(1), ((sh * scale).round() as u32).max(1)]; - let stale = tm.shown.as_ref().is_none_or(|(st, at, hits)| *st != tm.movie.state || *at != px || *hits != tm.hit_areas); - if stale { - let t0 = web_time::Instant::now(); - let mut dl = evaluate_player(&tm.doc, &tm.movie.state); - if tm.hit_areas { - let (tint, alpha) = crate::theme::hit_area(); - dl.append(anicraft_engine::doc::player::hit_overlay(&tm.doc, &tm.movie.state, tint, alpha)); - } - let view = View { transform: Affine::scale(scale, scale), width: px[0], height: px[1], background: Some(tm.doc.stage.background) }; - if let Ok((pm, _)) = render(&dl, &view) { - let image = egui::ColorImage::from_rgba_unmultiplied([px[0] as usize, px[1] as usize], &pm.to_rgba8()); - match &mut tm.texture { - Some(t) => t.set(image, egui::TextureOptions::LINEAR), - None => tm.texture = Some(ctx.load_texture("test-movie", image, egui::TextureOptions::LINEAR)), - } - } - tm.ms = t0.elapsed().as_secs_f32() * 1000.0; - tm.shown = Some((tm.movie.state.clone(), px, tm.hit_areas)); - } - ui.painter().rect_filled(outer, crate::theme::SQUARE, T.pasteboard); - if let Some(t) = &tm.texture { - ui.painter().image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); - } - // ---- output ---- - ui.add_space(6.0); - ui.horizontal(|ui| { - ui.label(text(Type::Heading, tr!("Output"))); - let n = tm.movie.output.len(); - ui.label(text(Type::Data, format!("{n}")).color(T.text_faint)).on_hover_text(tr!("Lines written")); - // Kept scripts that don't run (ADR 0013) are counted once here, not every - // time they pass; the Output's first lines say which and why. - if tm.skipped > 0 { - let what = trn!("{n} frame script doesn't run", "{n} frame scripts don't run", tm.skipped); - ui.label(text(Type::Caption, what).color(T.error)).on_hover_text(tr!("Kept with the document, but outside the ActionScript 3.0 subset AniCraft runs (or on a timeline that doesn't run scripts). The first Output lines say why; the Actions panel shows each problem in place.")); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add_enabled(n > 0, egui::Button::new(tr!("Clear"))).clicked() { - tm.movie.output.clear(); - } - }); - }); - egui::Frame::NONE.fill(T.field).inner_margin(egui::Margin::symmetric(8, 6)).show(ui, |ui| { - egui::ScrollArea::vertical().id_salt("test_movie_output").max_height(output_h).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 2.0; - if tm.movie.output.is_empty() { - ui.label(text(Type::Caption, tr!("Trace actions, frame-script logs and anything that couldn't run appear here."))); - } - for (tick, line) in &tm.movie.output { - ui.horizontal(|ui| { - ui.label(text(Type::DataSmall, format!("{tick:>5}")).color(T.text_faint)); - ui.label(text(Type::Data, line.as_str())); - }); - } - }); - }); - }); + .show(ctx, |ui| restart = body(tm, plugins, out, ui, note)); crate::a11y::name_title_bar(&win, &title); - let esc = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); - if !shown || esc { - if app.test_movie.take().is_some_and(|tm| tm.audio) { - app.sound.stop(); + // Esc closes it from anywhere in the editor, as it always has; Ctrl+W (⌘W) while the movie + // has the keyboard. + let esc = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) || (has_keys(ctx) && ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::W))); + Asked { restart, close: !shown || esc, ..Default::default() } +} + +/// The window's contents, wherever it is: the controls, the movie under the pointer and the +/// keyboard, and the Output. Returns whether Restart was clicked. +fn body(tm: &mut TestMovie, plugins: &anicraft_engine::plugins::Registry, out: &mut crate::sound::SoundOut, ui: &mut egui::Ui, note: Option<&str>) -> bool { + let ctx = ui.ctx().clone(); + let mut restart = false; + let (sw, sh) = (tm.doc.stage.width as f32, tm.doc.stage.height as f32); + // ---- controls ---- + ui.horizontal(|ui| { + if crate::timeline::icon_button(ui, &tr!("Restart from frame 1 with the document as it is now ({key})", key = crate::platform::shortcut_label("Ctrl+Enter")), None, Icon::First).clicked() { + restart = true; } - } else if restart { - open(app); + let (icon, tip) = if tm.paused { (Icon::Play, tr!("Play")) } else { (Icon::Pause, tr!("Pause")) }; + if crate::timeline::icon_button(ui, tip, None, icon).clicked() { + tm.paused = !tm.paused; + tm.acc = 0.0; + if tm.paused { + out.stop(); + } else if tm.audio { + tm.resume(out); + } + } + if tm.paused && crate::timeline::icon_button(ui, tr!("Step one frame"), None, Icon::Next).clicked() { + let mut runner = ScriptRunner::new(plugins); + tm.movie.step(&tm.doc, &[], &mut runner); + tm.feed(out); + } + ui.add_space(8.0); + let st = &tm.movie.state; + let scene = tm.doc.scenes.get(st.scene).map_or("", |s| s.name.as_str()); + let frames = tm.doc.timeline(st.scene).frame_count(); + ui.label(text(Type::Body, scene).color(T.text_dim)); + ui.label(text(Type::Data, format!("{:>4} / {frames}", st.root.frame + 1))).on_hover_text(tr!("Main timeline frame")); + let what = if tm.paused { tr!("paused") } else if st.root.playing { tr!("playing") } else { tr!("stopped") }; + ui.label(text(Type::Caption, what)); + // A movie that listens for keys says where they go. + if tm.movie.state.stage.iter().any(|l| l.event.is_key()) { + let keys = if has_keys(&ctx) { tr!("Keys go to the movie") } else { tr!("Click the movie to give it the keyboard") }; + ui.label(text(Type::Caption, keys).color(T.text_dim)); + } + ui.add_space(8.0); + ui.checkbox(&mut tm.hit_areas, tr!("Show hit areas")).on_hover_text(tr!("Draw where each button answers the pointer (its Hit frame) over the movie")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // i18n-exempt: numbers and units (data) + ui.label(text(Type::Data, format!("{:.0} fps · {:.1} ms", tm.doc.stage.fps, tm.ms)).color(T.text_faint)).on_hover_text(tr!("Frame rate, and the time the last picture took to draw")); + }); + }); + // Why it isn't in a window of its own, when that isn't the user's choice. + if let Some(note) = note { + ui.label(text(Type::Caption, note).color(T.text_dim)); } + ui.add_space(4.0); + // ---- the movie, fitted to the window, with the pointer ---- + let output_h = 120.0f32.min(ui.available_height() * 0.4); + let avail = egui::vec2(ui.available_width(), (ui.available_height() - output_h - 40.0).max(60.0)); + let k = (avail.x / sw.max(1.0)).min(avail.y / sh.max(1.0)).max(0.01); + let size = egui::vec2(sw * k, sh * k); + let (outer, _) = ui.allocate_exact_size(egui::vec2(avail.x, size.y), egui::Sense::hover()); + let resp = ui.interact(outer, surface_id(), egui::Sense::click_and_drag()); + crate::a11y::surface(ui, &resp, tr!("The movie: point, click and type to play it")); + if tm.focus || resp.is_pointer_button_down_on() { + resp.request_focus(); + tm.focus = false; + } + // Tab and the arrows are the movie's keys while it has them, not focus moves. + if resp.has_focus() { + ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false })); + } + let rect = egui::Rect::from_center_size(outer.center(), size); + // The pointer, in stage coordinates, to the player. + let mut events = Vec::new(); + let to_stage = |p: egui::Pos2| Vec2::new((p.x - rect.left()) / k, (p.y - rect.top()) / k); + let latest = ui.input(|i| i.pointer.latest_pos()); + let inside = resp.hover_pos().is_some_and(|p| rect.contains(p)); + let down = resp.is_pointer_button_down_on(); + if let Some(p) = latest.map(to_stage) { + if inside && tm.pointer != Some(p) { + events.push(Event::Move(p)); + } + if !inside && tm.pointer.is_some() { + events.push(Event::Leave); + } + if down && !tm.down && inside { + events.push(Event::Down(p)); + } + // Released off the movie: an Up out there, which clicks nothing. + if !down && tm.down { + events.push(Event::Up(p)); + } + tm.pointer = inside.then_some(p); + } + tm.down = down && (tm.down || inside); + // The keyboard, while the movie has it (Ctrl/⌘ shortcuts stay the app's). + if resp.has_focus() { + ui.input(|i| { + for e in &i.events { + if let egui::Event::Key { key, pressed, modifiers, .. } = e + && !modifiers.command + && *key != egui::Key::Escape + && let Some(code) = key_code(*key) + { + events.push(if *pressed { Event::KeyDown(code) } else { Event::KeyUp(code) }); + } + } + }); + } + let mut runner = ScriptRunner::new(plugins); + tm.movie.input(&tm.doc, &events, &mut runner); + tm.feed(out); + if inside && tm.movie.state.hover.is_some() { + ctx.set_cursor_icon(egui::CursorIcon::PointingHand); + } + // ---- time: the document's frame rate, kept by the sound while it plays ---- + if !tm.paused { + let fps = f64::from(tm.doc.stage.fps.max(1.0)); + let rate = f64::from(out.rate().max(1)); + let heard = if tm.audio { out.movie_position() } else { None }; + let mut n = 0; + if let Some(pos) = heard { + let due = (pos as f64 * fps / rate).floor() as u64; + while tm.movie.state.tick < due && n < MAX_CATCH_UP { + tm.movie.step(&tm.doc, &[], &mut runner); + n += 1; + } + } else { + tm.acc += f64::from(ui.input(|i| i.stable_dt)).min(0.25); + while tm.acc >= 1.0 / fps && n < MAX_CATCH_UP { + tm.acc -= 1.0 / fps; + tm.movie.step(&tm.doc, &[], &mut runner); + n += 1; + } + if n == MAX_CATCH_UP { + tm.acc = 0.0; + } + } + tm.feed(out); + ctx.request_repaint(); + } + // ---- picture ---- + let ppp = ctx.pixels_per_point(); + let scale = (k * ppp).min(MAX_EDGE / sw.max(sh).max(1.0)); + let px = [((sw * scale).round() as u32).max(1), ((sh * scale).round() as u32).max(1)]; + let stale = tm.shown.as_ref().is_none_or(|(st, at, hits)| *st != tm.movie.state || *at != px || *hits != tm.hit_areas); + if stale { + let t0 = web_time::Instant::now(); + let mut dl = evaluate_player(&tm.doc, &tm.movie.state); + if tm.hit_areas { + let (tint, alpha) = crate::theme::hit_area(); + dl.append(anicraft_engine::doc::player::hit_overlay(&tm.doc, &tm.movie.state, tint, alpha)); + } + let view = View { transform: Affine::scale(scale, scale), width: px[0], height: px[1], background: Some(tm.doc.stage.background) }; + if let Ok((pm, _)) = render(&dl, &view) { + let image = egui::ColorImage::from_rgba_unmultiplied([px[0] as usize, px[1] as usize], &pm.to_rgba8()); + match &mut tm.texture { + Some(t) => t.set(image, egui::TextureOptions::LINEAR), + None => tm.texture = Some(ctx.load_texture("test-movie", image, egui::TextureOptions::LINEAR)), + } + } + tm.ms = t0.elapsed().as_secs_f32() * 1000.0; + tm.shown = Some((tm.movie.state.clone(), px, tm.hit_areas)); + } + ui.painter().rect_filled(outer, crate::theme::SQUARE, T.pasteboard); + if let Some(t) = &tm.texture { + ui.painter().image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + // ---- output ---- + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.label(text(Type::Heading, tr!("Output"))); + let n = tm.movie.output.len(); + ui.label(text(Type::Data, format!("{n}")).color(T.text_faint)).on_hover_text(tr!("Lines written")); + // Kept scripts that don't run (ADR 0013) are counted once here, not every + // time they pass; the Output's first lines say which and why. + if tm.skipped > 0 { + let what = trn!("{n} frame script doesn't run", "{n} frame scripts don't run", tm.skipped); + ui.label(text(Type::Caption, what).color(T.error)).on_hover_text(tr!("Kept with the document, but outside the ActionScript 3.0 subset AniCraft runs (or on a timeline that doesn't run scripts). The first Output lines say why; the Actions panel shows each problem in place.")); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add_enabled(n > 0, egui::Button::new(tr!("Clear"))).clicked() { + tm.movie.output.clear(); + } + }); + }); + egui::Frame::NONE.fill(T.field).inner_margin(egui::Margin::symmetric(8, 6)).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("test_movie_output").max_height(output_h).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + if tm.movie.output.is_empty() { + ui.label(text(Type::Caption, tr!("Trace actions, frame-script logs and anything that couldn't run appear here."))); + } + for (tick, line) in &tm.movie.output { + ui.horizontal(|ui| { + ui.label(text(Type::DataSmall, format!("{tick:>5}")).color(T.text_faint)); + ui.label(text(Type::Data, line.as_str())); + }); + } + }); + }); + restart } /// `--open testmovie` (screenshots): the sample's Play button clicked, the show played through @@ -480,6 +646,70 @@ mod tests { frame(&ctx, &mut app, vec![]); } + fn ctrl(key: egui::Key) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND } + } + + /// The window of its own (ADR 0062), with egui standing in for the window system: it opens + /// with the keyboard, its keys are the movie's, Ctrl+Enter restarts it, Ctrl+W and Esc + /// close it, and the preference puts it back inside the editor. + #[test] + fn the_window_of_its_own_has_the_keyboard_and_closes_with_esc_or_ctrl_w() { + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::interactive()); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + app.run("layer.select", json!({"index": 0})); + // i18n-exempt: script source, document content + let script = "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { trace(\"down \" + e.keyCode); });"; + assert!(app.run("script.set", json!({"frame": 0, "text": script})).is_some_and(|v| v["runs"] == true)); + assert_eq!(crate::platform::movie_host(ctx.embed_viewports(), app.prefs.test_movie_window), crate::platform::MovieHost::Window); + open(&mut app); + for _ in 0..3 { + frame(&ctx, &mut app, vec![]); + } + assert!(has_keys(&ctx), "the movie takes the keyboard when its window opens"); + let place = app.test_movie.as_ref().and_then(|t| t.placement); + frame(&ctx, &mut app, vec![key(egui::Key::A, true)]); + assert!(lines(&app).iter().any(|l| l == "down 65"), "{:?}", lines(&app)); + // Ctrl+Enter (⌘↩) in the movie's window restarts it, in the same place. + frame(&ctx, &mut app, vec![ctrl(egui::Key::Enter)]); + assert!(app.test_movie.as_ref().is_some_and(|t| t.movie.output.iter().all(|(_, l)| l != "down 65")), "a fresh run"); + assert_eq!(app.test_movie.as_ref().and_then(|t| t.placement).map(|p| p.size), place.map(|p| p.size), "a restart keeps the window as it is"); + frame(&ctx, &mut app, vec![]); + frame(&ctx, &mut app, vec![ctrl(egui::Key::W)]); + assert!(app.test_movie.is_none(), "Ctrl+W closes it"); + open(&mut app); + frame(&ctx, &mut app, vec![]); + frame(&ctx, &mut app, vec![key(egui::Key::Escape, true)]); + assert!(app.test_movie.is_none(), "Esc closes it"); + // Inside the editor by choice: the floating window, Ctrl+W there too. + app.prefs.test_movie_window = false; + open(&mut app); + for _ in 0..2 { + frame(&ctx, &mut app, vec![]); + } + assert!(ctx.memory(|m| m.area_rect(egui::Id::new("test_movie")).is_some()), "the floating window"); + frame(&ctx, &mut app, vec![ctrl(egui::Key::W)]); + assert!(app.test_movie.is_none()); + } + + #[test] + fn the_window_opens_at_the_stage_size_and_fits_the_screen() { + let chrome = CHROME; + // A 1280 × 720 stage at 100 % on a large screen, as in Animate. + let big = window_size(egui::vec2(1280.0, 720.0), Some(egui::vec2(2560.0, 1440.0))); + assert_eq!(big, egui::vec2(1280.0, 720.0) + chrome); + // On a small screen it shrinks to fit, keeping the movie's shape. + let small = window_size(egui::vec2(1280.0, 720.0), Some(egui::vec2(1366.0, 768.0))); + assert!(small.y <= 768.0 * 0.85 + 0.5 && small.x < big.x, "{small:?}"); + let (mw, mh) = (small.x - chrome.x, small.y - chrome.y); + assert!((mw / mh - 1280.0 / 720.0).abs() < 0.01); + // Tiny or broken stages still get usable controls. + assert_eq!(window_size(egui::vec2(10.0, 0.0), None), egui::vec2(MIN_SIZE[0], MIN_SIZE[1])); + assert!(window_size(egui::vec2(f32::MAX, 1.0), Some(egui::vec2(800.0, 600.0))).x.is_finite()); + } + #[test] fn key_codes_are_actionscript_s() { use egui::Key as K; From 4bdb32ee83ec522494aa752706120f9cae3a5043 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:03:15 -0700 Subject: [PATCH 062/192] docs: ADR 0062, Test Movie window and macOS document opening (M8) --- CHANGELOG.md | 18 +++ docs/adr/0024-frame-scripts-and-test-movie.md | 3 +- docs/adr/0026-packaging-and-signing.md | 4 + ...movie-window-and-macos-document-opening.md | 151 ++++++++++++++++++ docs/adr/README.md | 1 - docs/legal/compliance.md | 9 ++ docs/roadmap.md | 8 +- 7 files changed, 188 insertions(+), 6 deletions(-) create mode 100644 docs/adr/0062-test-movie-window-and-macos-document-opening.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cc77a34..000fc213 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ ## Unreleased +* **Test Movie in its own window, and opening documents on macOS** (ADR 0062, M8). + * **Control › Test Movie** (Ctrl+Enter) now opens in a **window of its own** on the desktop, + as in Animate. It is sized to the stage at 100 % (smaller if that wouldn't fit the + screen), titled with the document's name, and opens where it was last. It takes the + keyboard when it opens. **Esc** or **Ctrl+W (⌘W)** closes it, Ctrl+Enter restarts it in + place, and the editor's Ctrl and Alt shortcuts still work from it. + * In the web build, and wherever the system can't open another window, it floats inside the + editor as before and says why. **Preferences › Test Movie** keeps it inside the editor if + you prefer. On Wayland the desktop places the window, so it can't come back where it was + (Preferences says so). + * **macOS:** double-clicking a `.anicraft`, `.fla` or `.xfl` in Finder, dropping it on the + Dock icon, or choosing Open With › AniCraft opens it, whether AniCraft is running or + not. If there are unsaved changes it asks first, and the Dock's Quit asks to save too. + This uses the small `fmv-macos-events` crate (MIT OR Apache-2.0), so AniCraft's own code + stays free of `unsafe`. Still to be checked on a Mac (the list is in ADR 0062). + * Windows and Linux already open a double-clicked document from the command line; a test + now covers it. + * **Publish Settings and Publish** (ADR 0060, M8). * **File › Publish Settings** (Ctrl+Shift+F12) is a window that stays open while you work. It lists every format AniCraft exports (HTML canvas, animated GIF, video, Lottie, sprite diff --git a/docs/adr/0024-frame-scripts-and-test-movie.md b/docs/adr/0024-frame-scripts-and-test-movie.md index 9f3033cc..bbf66bd7 100644 --- a/docs/adr/0024-frame-scripts-and-test-movie.md +++ b/docs/adr/0024-frame-scripts-and-test-movie.md @@ -129,4 +129,5 @@ confirmation). Command plug-ins may call `actions.*` and `instance.*` but not `c * Not in this slice: ActionScript parsing (ADR 0013 tiers), HTML canvas export, sound actions, keyboard events, drag, variables and conditions, persistent script state, scripts inside graphic symbols (they never run, as in Animate) and button frame scripts, masks in - hit tests, a separate OS window for Test Movie. + hit tests, a separate OS window for Test Movie (done in ADR 0062: a window of its own where + the system has windows, this floating window as the fallback). diff --git a/docs/adr/0026-packaging-and-signing.md b/docs/adr/0026-packaging-and-signing.md index 20262762..26663971 100644 --- a/docs/adr/0026-packaging-and-signing.md +++ b/docs/adr/0026-packaging-and-signing.md @@ -97,6 +97,10 @@ prompt they didn't ask for. With"), but macOS hands the file to a running app as an Apple Event, not on the command line, and winit 0.30 doesn't deliver it; double-clicking a `.anicraft` starts AniCraft without opening the file. Needs an open-documents hook in the shell without `unsafe`. + **Done in ADR 0062:** the open-documents and quit Apple Events reach the shell through + `platform.rs`, at launch and while running, and open through the unsaved-changes guard. + A test covers Windows' and Linux's command-line hand-over. The Mac-only checks are listed + there. * A version override for manual release runs (the family's `cargo xtask version set`): AniCraft has no `xtask` yet, so the dispatch input was removed; a manual run builds the `Cargo.toml` version. diff --git a/docs/adr/0062-test-movie-window-and-macos-document-opening.md b/docs/adr/0062-test-movie-window-and-macos-document-opening.md new file mode 100644 index 00000000..d1b7ab3f --- /dev/null +++ b/docs/adr/0062-test-movie-window-and-macos-document-opening.md @@ -0,0 +1,151 @@ +# ADR 0062: Test Movie in its own window, and opening documents on macOS + +* Status: accepted (2026-11-11) +* Relates to: ADR 0006 (platform layer), ADR 0022 (accessibility), ADR 0024 (Test Movie), + ADR 0026 (packaging), ADR 0036 (web build), ADR 0040 (interface languages), ADR 0052 + (Test Movie keyboard), ADR 0059 (files from the desktop) + +## Context + +Test Movie (ADR 0024) floated inside the editor until AniCraft could open more than one window. +In Animate, Control › Test Movie opens the movie in a window of its own, at the stage's size, +which artists put on a second screen or beside the editor and close with the usual +window-close key. eframe 0.36 can open more windows (viewports) on Windows, macOS, X11 and +Wayland, but not in a browser. + +The packaging work (ADR 0026) declared AniCraft's document types to macOS, but double-clicking +a `.anicraft` file in Finder started AniCraft without opening the file. macOS does not put the +file on the command line. It sends an Apple Event (`kAEOpenDocuments`), both at launch and +while the app runs, and winit 0.30 has no event for it (`WindowEvent::DroppedFile` is a drop on +a window, which is something else). winit's docs say to install your own `NSApplication` +delegate, which needs `unsafe` Objective-C. AniCraft forbids `unsafe` in its code. + +Windows and Linux already pass the document on the command line (`"%1"` in the MSI's file +association, `Exec=anicraft %f` in the desktop entry). Nothing had tested that. + +## Decision + +### Test Movie + +1. **An immediate viewport**, not a deferred one. Test Movie plays with the editor's own + state: the sound output (ADR 0039), the plug-in registry the frame scripts run on, the + shortcut table, and the preferences. An immediate viewport's callback runs inside the + editor's frame with `&mut App`, so nothing is shared across threads and there is no + `Arc>` around the sound device. A deferred viewport would need `Send + Sync` + state, and a second copy of the shortcut dispatch. The cost is that the editor redraws + whenever the movie does. That redraw is cheap, because the stage keeps its tiles cached + (ADR 0007) and the movie only renders when its state changes. If profiling shows a + problem, the movie can move to a deferred viewport behind the same `show`. +2. **One body, two hosts** (`test_movie::body`). The controls, the movie under the pointer + and keyboard, and the Output are drawn once. They go either in the window of its own + (`own_window`: an `egui::CentralPanel` in the viewport) or in the floating egui window + (`inside`). Behaviour can't differ between the two. +3. **Where it plays** is `platform::movie_host` (ADR 0006: OS decisions live in + `platform.rs`): + * the web build: inside, and it says *"a web page can't open a window of its own"*; + * `Context::embed_viewports()` true (eframe sets that wherever it has no multi-window + support; headless contexts too): inside, and it says the system can't open another + window; + * **Preferences › Test Movie › Play Test Movie in a window of its own** off: inside, with no + note (the user chose it). This is also the way out on a Wayland setup whose compositor + handles a second window badly. We can't detect that from inside the app, so we don't + guess. + * otherwise its own window. + We decide before calling `show_viewport_immediate`. We never rely on egui's own embedded + stand-in, which panics if its window is hidden (golden rule 1). +4. **Size, title, place.** The window opens at the stage's size at 100 % plus the controls, + as in Animate. If that doesn't fit 85 % of the screen it is made smaller with the aspect + kept, and never smaller than 480 × 320 (`window_size`). The size is worked out once the + screen's size is known, and kept across a restart, so Ctrl+Enter doesn't move or resize + the window. The title is *"Test Movie — "*, in the interface language. The + window has the app id and icon (`platform::secondary_window`), so docks and taskbars group + it with the editor. + **Its place is remembered** in the preferences (`test_movie_pos`: the outer top-left + corner, in points). It is saved when the window closes and when the app quits, and not in + screenshot runs. A remembered place is only used if it is on or beside the editor's screen + (`usable_position`), so a monitor that has since been unplugged can't strand the window off + screen. Wayland never tells apps where their windows are, and doesn't let them choose: + there the desktop places the window, Preferences says so (`window_positions`), and nothing + is saved. +5. **Keyboard** (ADR 0052). The window comes to the front with the keyboard when it opens or + restarts (`ViewportCommand::Focus`, then focus on the movie surface; egui keeps focus per + viewport). The movie's keys go to its listeners as before. In the window of its own, + **Esc** and **Ctrl+W (⌘W)** close it, **Ctrl+Q (⌘Q)** quits through the editor's close + guard, and the editor's other shortcuts with Ctrl (⌘) or Alt still work there (Restart is + Ctrl+Enter). They are collected in the viewport and run after it, in the editor's context, + so a command that talks to "the window" means the editor's. The floating window keeps Esc + from anywhere and gains Ctrl+W while the movie has the keyboard. The OS close button closes + it like Esc. +6. **Screenshots.** eframe 0.36 doesn't capture an immediate viewport + (`ViewportCommand::Screenshot` reaches only windows it paints by themselves), so + `--screenshot` captures the editor only. `--open testmovieinside` shows the floating + fallback in the editor's screenshot. The window of its own was checked from a capture of + that window alone (PrintWindow on Windows). + +### Documents macOS hands over + +7. **`fmv-macos-events` 0.1.0** (MIT OR Apache-2.0, crates.io, pinned with `=`, about 170 + lines, read in full) registers AppKit's open-documents (`aevt/odoc`) and quit (`aevt/quit`) + Apple Event handlers. It does this before the event loop starts and again on + `NSApplicationWillFinishLaunching`, so the document that launched the app isn't missed. It + hands back plain `PathBuf`s through an inbox on the main thread. It does **not** replace + winit's application delegate. Its `unsafe` stays inside it, and our code stays + `unsafe`-free. Its objc2 / objc2-app-kit / objc2-foundation are the versions wgpu already + brings, so no other crate is added. Other options: + * our own delegate or Apple Event handler: `unsafe` in our code, which is forbidden; + * `bevy_macos_open_files`: tied to Bevy; + * waiting for winit: no released winit has the event yet. + It is a young crate from one author. It is pinned exactly, `Cargo.lock` holds its + checksum, and any new version is read again before it comes in. It is replaced as soon as + winit or eframe deliver the event. +8. **One path for every platform.** `platform::listen_for_documents` (main, before + `run_native`, kept until it returns) and `platform::wake_on_requests` (the editor repaints + when one arrives) are the only macOS code. Requests (`SystemRequest::Open(paths)` / + `Quit`) go through a bounded queue (64) that `App::frame` drains first thing. + * **Open** goes through the same routing as a drop on the window (ADR 0059): the first + `.anicraft` / `.fla` / `.xfl` opens via `file.open` through `request`, so **unsaved + changes ask first**. Other files in the same request are left out with a reason, and a + request with no document says what AniCraft opens. The start screen gives way. + * **Quit** (the Dock's Quit, logging out) closes the editor's window, which the close + guard intercepts when there is unsaved work. The handler replaces AppKit's default, which + would terminate without asking. +9. **Command-line documents** (Windows, Linux) are now parsed by `main::parse_args`, a pure + function. It ignores `-psn_…`, which older macOS added when Finder started an app. A test + checks that a path with spaces arrives as the file and that `open_session` opens it instead + of the sample. + +## Consequences + +* Test Movie can sit on another screen while the editor stays usable. Closing it is the usual + key. The web build and anyone who prefers it keep the floating window. +* The editor redraws while the movie plays (point 1). This is measured and recorded in the PR. +* One small third-party crate holds `unsafe` macOS code on our behalf. It is a supply-chain + risk, mitigated by an exact pin and a full read, and listed for the lead. +* The workspace's `rust-version` is 1.90, but `fmv-macos-events` declares 1.95. The macOS build + therefore needs Rust 1.95 or newer (CI and releases use the current stable). Windows and Linux + don't build the crate. + +## Only a Mac can verify + +The crate compiles and passes clippy for `aarch64-apple-darwin` from Windows, but nobody has run +it on a Mac yet. Check on a Mac, from a signed DMG install: + +1. Double-clicking a `.anicraft` while AniCraft is closed starts it with that document (not the + start screen). +2. Double-clicking another document while it runs opens it, and asks first if there are + unsaved changes. +3. Dropping a `.fla` on the Dock icon, and Finder › Open With › AniCraft, open it. +4. Dock › Quit with unsaved work asks to save. Logging out does the same. +5. The Test Movie window opens at the stage's size, comes to the front, ⌘W and Esc close it, + ⌘↩ restarts it, and it reopens where it was. + +## Not in this slice + +* Several documents at once: AniCraft has one document window, so a second document replaces + the first (after asking). Windows and Linux start a second AniCraft for a second + double-click; a single-instance hand-over is later. +* `file://` URLs from Linux desktops that pass `%u`. Our desktop entry passes `%f` paths. +* Test Movie as a deferred viewport (point 1), a full-screen mode, zoom inside the movie + window, and remembering its size. +* Detecting a Wayland compositor that fails to show a second window: the preference is the + answer for now. diff --git a/docs/adr/README.md b/docs/adr/README.md index af0902f4..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0062 | m8/test-movie-window | Test Movie in its own window, and opening documents on macOS | diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index 4ba95ee9..ae2c0751 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -55,6 +55,15 @@ cargo deny check advisories # RustSec security advisories (needs ne user's own files: AniCraft ships none in the binary; the sample plug-ins are source under `examples/plugins` (MIT OR Apache-2.0). +### Opening documents on macOS (2026-11-11, ADR 0062) + +New crate, from crates.io, macOS builds only: `fmv-macos-events` 0.1.0 (MIT OR Apache-2.0), +pinned with `=`. It registers AppKit's open-documents and quit Apple Event handlers so that +AniCraft's own code stays free of `unsafe`. It was read in full before it was added: about 170 +lines, no network or file access. Its `objc2` 0.6, `objc2-app-kit` 0.3 and `objc2-foundation` +0.3 (MIT, Zlib OR Apache-2.0 OR MIT) were already in the tree through wgpu. No new licence. It +declares `rust-version = 1.95`, so the macOS build needs that toolchain or newer. + ### Find and Replace (2026-11-11, ADR 0058) New crates, from crates.io: `regex` 1 with `regex-syntax` and `regex-automata` (MIT OR diff --git a/docs/roadmap.md b/docs/roadmap.md index a5bbffdb..4ff66a27 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -13,7 +13,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | -| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | +| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. Not yet: exact drop positions on the desktop (winit 0.30 gives none during a drag; a drop waits for the first pointer move, else lands mid-view), SVG into the Library, drops on the timeline, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | @@ -22,7 +22,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | | Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. | -| Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. Not yet: double-clicking a document in Finder opens it (the app starts, the file doesn't open), AppImage desktop integration, portable mode, store listings, video export inside the Flatpak. | +| Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. **Opening documents on macOS** (ADR 0062): a double-click in Finder, a drop on the Dock icon or Open With opens the document, at launch or while running (the open-documents Apple Event through `platform.rs`, by `fmv-macos-events`, so no `unsafe` of ours), through the unsaved-changes guard; the Dock's Quit asks to save too; Windows and Linux command-line hand-over covered by a test. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, AppImage desktop integration, portable mode, store listings, video export inside the Flatpak. | | Languages | **First slice** (ADR 0040, `docs/localisation.md`): every shell string goes through `tr!`/`trn!` (keyed by its English; placeholders; CLDR plurals for whole numbers), menus translate the registry's labels when drawn (ids, CLI, MCP and the file format stay English), screen-reader names too. Catalogs are craft-i18n's TSV, read by our own parser and embedded from `CRAFT_I18N_DIR` (fallback app → shared → base language → English). Preferences › Appearance › Language (system language by default) and `--lang`. A **pseudo-locale** (`--lang pseudo`: accented, a third longer, bracketed) tests layout; checked by a source guideline test and a pseudo-locale accessibility audit; `scripts/i18n-extract.sh` writes the translators' template and per-locale coverage. Not yet: a real language (craft-i18n has no `anicraft.tsv` yet), engine messages and confirmation bodies (`@msg`), default document names, right to left (needs bidi and shaping in egui upstream), CJK and Georgian (need a font), shaped scripts. | | Accessibility | **First pass** (ADR 0022, `docs/accessibility.md`): AccessKit (via eframe) gives every control a name and role, checked by a headless test that walks the tree in 23 interface states (custom-painted tools, layer rows and toggles, icon buttons, Library rows, every Properties field, the Motion Editor, every dialog; the stage is a named canvas; the status bar a polite live region). **Ctrl+F6 / Ctrl+Shift+F6** move focus between Stage, Timeline, Properties, Library and Tools (rebindable); focused controls keep Enter/Space/arrows while other shortcuts still work; pointer-only surfaces are not Tab stops. **High contrast** palette (Preferences › Theme) from the same roles, text ≥ 7:1, controls and focus ≥ 3:1; both palettes checked by the contrast test (the graphite one now meets AA everywhere). **Interface scale** 75–200 % holds up (stage refits, tools and timeline header scroll, status truncates). Not yet: stage elements and single frames exposed one by one, keyboard menu bar, following the OS contrast setting, manual passes with Narrator, VoiceOver and Orca. | | Stage rendering & build | **Tiled stage** (ADR 0007): 512 px cached tiles, batched per frame with one scene evaluation per frame, look-ahead ring and playback prefetch, scaled older tiles instead of blank areas, pixel-aligned (no seams). **Space-biased build**: debug build 6.9 GB → 1.04 GB, fresh build 44 s, edit rebuild 4–6 s (`docs/development.md`). | @@ -40,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | -| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. | +| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. | ## Releases @@ -61,7 +61,7 @@ titled with its milestone. | M5 | Audio layers: import, waveform, playback sync | timeline, layers | | M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | -| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | +| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); next: the accessibility follow-ups | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and ActionScript (on M6's plug-in host). From 70e8111f42d6bc2d7ed8e23451ede89fd7d9e7c3 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:31:57 -0700 Subject: [PATCH 063/192] fix(timeline): frame zoom in the bottom bar so the header fits at the default size, with a test (M1) --- CHANGELOG.md | 4 ++- docs/adr/0061-timeline-polish.md | 7 ++++ docs/roadmap.md | 2 +- src/app.rs | 4 +++ src/timeline.rs | 60 +++++++++++++++++++++++--------- 5 files changed, 58 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20b1a854..5fa9b805 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,9 @@ around it, dimmed. * **Layer Height** 100 / 200 / 300 % (right-click menu), **Layer Properties** (double-click a layer's icon, Properties… or Modify › Timeline), and a **Frame View** menu with frame widths - Tiny to Large and **Short** rows. + Tiny to Large and **Short** rows. Frame zoom and Frame View sit at the right end of the + timeline's bottom bar, as in Animate, so the header fits at the default window size again + (the tween-kind menu was cut off). * Headless: `layer.set_onion`, `layer.set_color`, `layer.set_height`, `layer.set_properties`, `layer.properties`. Saved in the document with defaults left out, so older files open as before. XFL import reads a layer's height. diff --git a/docs/adr/0061-timeline-polish.md b/docs/adr/0061-timeline-polish.md index 11e9d4e5..ec95511f 100644 --- a/docs/adr/0061-timeline-polish.md +++ b/docs/adr/0061-timeline-polish.md @@ -64,6 +64,13 @@ Nothing was copied. laid out by height (`rows_fitting`, `max_first_row`, `first_showing`, `row_at`), so scrolling, bringing the active layer into view and dragging across rows follow the real rows. + * **Frame zoom moves to the timeline's bottom bar**, at the right end of the scroll bar, as + in Animate. The header had grown (onion options, the camera) until the zoom field covered + the tween-kind menu at the default window size. The header now has the dock's full width + and fits at 1600 × 940; a test measures it (`the_header_fits_at_the_default_window_size`). + Sideways scrolling stays the fallback for small windows, large interface scales and long + translations. *Rejected:* an overflow menu for the onion and camera toggles. They are + everyday controls, and hiding them costs a click every time. * **Frame View** menu beside the zoom slider: Tiny, Small, Normal, Medium, Large (frame widths 4, 8, 12, 18, 28 points; the slider still sets anything between) and **Short** rows (20 points; a 200 % layer is two short rows). diff --git a/docs/roadmap.md b/docs/roadmap.md index 748eda64..61ebd63c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -10,7 +10,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---| | Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). | | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | -| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | +| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | diff --git a/src/app.rs b/src/app.rs index 71b58956..cc44c5e6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -304,6 +304,9 @@ pub struct App { pub layer_props: Option, /// Open the timeline's Frame View menu on the next frame (screenshots, the audit). pub tl_frame_view_open: bool, + /// How far the timeline header's content overflowed its width last frame (points; ≤ 0: it + /// fits). Checked by a test at the default window size. + pub tl_header_spill: f32, /// Open this layer's colour popup on the next frame (screenshots, the audit). pub tl_color_open: Option, pub convert_last: crate::convert_symbol::Last, @@ -529,6 +532,7 @@ impl App { convert: None, layer_props: None, tl_frame_view_open: false, + tl_header_spill: 0.0, tl_color_open: None, convert_last: Default::default(), show_about: false, diff --git a/src/timeline.rs b/src/timeline.rs index 39295cb2..9a871832 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -34,6 +34,9 @@ fn frame_center(cell_left: f32, cell_w: f32) -> f32 { (cell_left + cell_w * 0.5).round() + 0.5 } const FOOTER_H: f32 = 38.0; +/// The bottom bar's frame zoom and Frame View at its right end: the 56 pt slider, its field, the +/// menu button and spacing. +const ZOOM_W: f32 = 168.0; /// Frame View › Short (ADR 0061): row height (points). Layers 200 % and 300 % tall are that /// many short rows. const SHORT_ROW_H: f32 = 20.0; @@ -236,23 +239,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // ---- header --------------------------------------------------------------------------- egui::Frame::NONE.fill(T.panel_alt).inner_margin(egui::Margin::symmetric(10, 5)).show(ui, |ui| { ui.horizontal(|ui| { - // Room kept at the right end for the frame zoom (the 56 pt slider, its field, - // spacing) and the Frame View menu. - const ZOOM_W: f32 = 122.0 + 30.0; - // The rest scrolls sideways (Shift+wheel) when the dock is narrow (a small window, a - // large interface scale) instead of being cut off. - let w = (ui.available_width() - ZOOM_W).max(0.0); - egui::ScrollArea::horizontal().id_salt("tl_header").max_width(w).show(ui, |ui| ui.horizontal(|ui| header(app, ui, dock))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - frame_view_button(app, ui); - let mut pct = app.tl_cell_w / CELL_DEFAULT * 100.0; - let (lo, hi) = (CELL_RANGE.start() / CELL_DEFAULT * 100.0, CELL_RANGE.end() / CELL_DEFAULT * 100.0); - ui.spacing_mut().slider_width = 56.0; - let r = with_type(ui, Type::Data, |ui| a11y::slider(ui, &mut pct, lo..=hi, tr!("Frame zoom"), a11y::SliderLook { suffix: " %", max_decimals: Some(0), logarithmic: true, ..Default::default() })); - if r.on_hover_text(tr!("Frame zoom: frame width (Ctrl+wheel over the frames)")).changed() { - app.tl_cell_w = (pct / 100.0 * CELL_DEFAULT).clamp(*CELL_RANGE.start(), *CELL_RANGE.end()); - } - }); + // The whole width is the header's (frame zoom and Frame View sit in the bottom bar, + // as in Animate). What doesn't fit scrolls sideways (Shift+wheel) in a small window + // or at a large interface scale, instead of being cut off. + let w = ui.available_width(); + let out = egui::ScrollArea::horizontal().id_salt("tl_header").max_width(w).show(ui, |ui| ui.horizontal(|ui| header(app, ui, dock))); + app.tl_header_spill = out.content_size.x - out.inner_rect.width(); }); }); @@ -1111,6 +1103,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let bar = Rect::from_min_max(pos2(grid.left(), body.bottom() - FOOTER_H), body.right_bottom()); painter.rect_filled(bar, 0.0, T.panel_alt); painter.line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, T.border)); + // Frame zoom and Frame View at the bar's right end, as Animate has them; the scroll track + // takes the rest. + let zoom_area = Rect::from_min_max(pos2((bar.right() - ZOOM_W).max(bar.left()), bar.top()), bar.right_bottom()); + let bar = Rect::from_min_max(bar.left_top(), pos2(zoom_area.left(), bar.bottom())); let track = bar.shrink2(vec2(10.0, (FOOTER_H - 12.0) * 0.5)); let content = (frames_total + 30).max(visible_cols) as f32; let frac = (visible_cols as f32 / content).clamp(0.05, 1.0); @@ -1133,6 +1129,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_filled(track, T.rc(), T.field); painter.rect_filled(thumb, T.rc(), if sr.hovered() || sr.dragged() { T.control_edge } else { T.hover }); sr.on_hover_text(tr!("Scroll the timeline (or Shift+wheel anywhere over it)")); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(zoom_area.shrink2(vec2(6.0, 4.0))).layout(egui::Layout::right_to_left(egui::Align::Center))); + frame_view_button(app, &mut child); + let mut pct = app.tl_cell_w / CELL_DEFAULT * 100.0; + let (lo, hi) = (CELL_RANGE.start() / CELL_DEFAULT * 100.0, CELL_RANGE.end() / CELL_DEFAULT * 100.0); + child.spacing_mut().slider_width = 56.0; + let r = with_type(&mut child, Type::Data, |ui| a11y::slider(ui, &mut pct, lo..=hi, tr!("Frame zoom"), a11y::SliderLook { suffix: " %", max_decimals: Some(0), logarithmic: true, ..Default::default() })); + if r.on_hover_text(tr!("Frame zoom: frame width (Ctrl+wheel over the frames)")).changed() { + app.tl_cell_w = (pct / 100.0 * CELL_DEFAULT).clamp(*CELL_RANGE.start(), *CELL_RANGE.end()); + } } /// The layer colour popup (a click on a layer's colour chip, ADR 0061): the layer colours as @@ -1455,6 +1460,27 @@ mod tests { assert_eq!(FRAME_WIDTHS[2].1, CELL_DEFAULT); } + /// The header at the default window size (1600 × 940, `main.rs`), in the widest state the + /// sample has: a classic tween at the playhead (Ease and tween-kind menus both shown). + fn header_spill(width: f32) -> f32 { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + assert!(app.s.active_layer().and_then(|l| l.keyframe_at(app.s.frame)).is_some_and(|k| k.tween.is_some()), "the widest header: a classic tween"); + let input = || egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 940.0))), ..Default::default() }; + for _ in 0..4 { + ctx.run_ui(input(), |ui| app.frame(ui)).textures_delta.clear(); + } + app.tl_header_spill + } + + #[test] + fn the_header_fits_at_the_default_window_size() { + let spill = header_spill(1600.0); + assert!(spill <= 0.5, "the timeline header overflows by {spill:.0} pt at 1600 × 940"); + // The measure is real: at the smallest window the header scrolls sideways instead. + assert!(header_spill(960.0) > 0.5); + } + #[test] fn frame_rates_read_without_needless_decimals() { assert_eq!(fps_label(24.0), "24 fps"); From bd9e37091b7f5fddface7fef541e8c464dff8642 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:34:41 -0700 Subject: [PATCH 064/192] docs(adr): reserve 0064 for accessibility, second pass (M8) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..7bdad542 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0064 | m8/accessibility-2 | Accessibility, second pass: stage elements, frames, keyboard menu bar, system contrast | From c2a6d42705556d2214bb94cf62e80ba4cde6f73a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:36:03 -0700 Subject: [PATCH 065/192] feat(engine): element.select toggle, for keyboard selection on the stage (M8) --- crates/engine/src/cmds_draw.rs | 19 +++++++++++++------ crates/engine/src/selection_tests.rs | 11 +++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index c54c24f5..db1cf314 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { }), c("edit.delete", "Clear", "Edit", Some("Delete"), "{} (on every layer with selected items)", true, delete_selection), c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?} (each copy on its original's layer)", true, |s, p| s.each_layer(true, |s| duplicate(s, p))), - c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); the active layer becomes the first one's unless it has some of them", false, select), + c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, toggle?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); `toggle` takes each one that is selected out of the selection and adds the others (Shift+Space on a stage element); the active layer becomes the first one's unless it has some of them", false, select), c("element.pick", "Select at Point", "", None, "{x, y, add?: bool} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer", false, pick), c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends (the nearest to `from`) then snaps onto a point, line or fill edge of the rest within that distance", true, translate), c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), @@ -210,6 +210,7 @@ fn select(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param(format!("param 'ids' has more than {MAX_SELECT} ids"))); } let add = opt_bool(p, "add")?.unwrap_or(false); + let toggle = opt_bool(p, "toggle")?.unwrap_or(false); // Where each element is at the playhead: on `layer`, else the active layer first, then the // others top to bottom. let order: Vec = match opt_u64(p, "layer")?.map(LayerId) { @@ -234,11 +235,17 @@ fn select(s: &mut Session, p: &Value) -> Result { } picked.push((l, id)); } - if !add { - s.selection.clear(); - } - for &(l, id) in &picked { - s.selection.insert(l, id); + if toggle { + for &(l, id) in &picked { + s.selection.toggle(l, id); + } + } else { + if !add { + s.selection.clear(); + } + for &(l, id) in &picked { + s.selection.insert(l, id); + } } // As a click does: the active layer is where the artwork is. if let Some(&(l, _)) = picked.first() diff --git a/crates/engine/src/selection_tests.rs b/crates/engine/src/selection_tests.rs index 082436c5..f701857c 100644 --- a/crates/engine/src/selection_tests.rs +++ b/crates/engine/src/selection_tests.rs @@ -562,3 +562,14 @@ fn clicking_a_layer_name_selects_its_artwork() { run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true})); assert!(s.selection.is_empty()); } + +#[test] +fn select_with_toggle_takes_one_out_and_puts_it_back_across_layers() { + // Shift+Space on a stage element (ADR 0064): the others stay selected, on either layer. + let (mut s, top, bottom, a, b) = two_layers(); + run(&mut s, "element.select", json!({"ids": [b.0], "toggle": true})); + assert!(s.selection.contains(top, a) && !s.selection.contains(bottom, b)); + run(&mut s, "element.select", json!({"ids": [b.0], "toggle": true})); + assert!(s.selection.contains(top, a) && s.selection.contains(bottom, b)); + assert!(s.execute("element.select", &json!({"ids": [b.0], "toggle": "yes"})).is_err(), "toggle is a bool"); +} From e57bb9da4525aa75bf9dae9e97c9f21ac71eebf9 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:40:34 -0700 Subject: [PATCH 066/192] feat(a11y): stage elements for screen readers, keyboard selection on the stage (M8) --- src/a11y.rs | 84 +++++++++++ src/app.rs | 3 + src/main.rs | 1 + src/stage.rs | 2 + src/stage_a11y.rs | 376 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 466 insertions(+) create mode 100644 src/stage_a11y.rs diff --git a/src/a11y.rs b/src/a11y.rs index 6c57a9ca..ac3cb06a 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -437,6 +437,90 @@ mod tests { assert!(app.playing, "Enter on the focused stage plays"); } + /// Presses `key` and lets a frame pass for focus to settle. Returns the last frame's tree. + fn key(ctx: &egui::Context, app: &mut App, key: egui::Key, modifiers: egui::Modifiers) -> Option { + frame(ctx, app, press(key, modifiers)); + frame(ctx, app, input(1.0)).platform_output.accesskit_update + } + + fn focus_stage(ctx: &egui::Context, app: &mut App) { + while focused_region(ctx) != Some(Region::Stage) { + key(ctx, app, egui::Key::F6, egui::Modifiers::COMMAND); + } + } + + fn node<'a>(t: &'a TreeUpdate, id: egui::Id) -> Option<&'a Node> { + t.nodes.iter().find(|(n, _)| *n == id.accesskit_id()).map(|(_, n)| n) + } + + #[test] + fn the_stage_lists_its_elements_and_selects_them_from_the_keyboard() { + let (_, mut app, ctx) = tree(|_, _| {}); + // Unfocused, the stage has no element nodes: the tree stays small. + assert!(app.stage_nav.focused(&ctx).is_none()); + focus_stage(&ctx, &mut app); + app.run("edit.deselect", serde_json::json!({})); + let (items, total) = crate::stage_a11y::items(&app); + assert!(items.len() >= 2 && total == items.len(), "the sample frame has a few elements: {items:?}"); + // Tab goes into the list, to the first element. + let t = key(&ctx, &mut app, egui::Key::Tab, egui::Modifiers::NONE).unwrap_or_else(|| panic!("no tree")); + let first = app.stage_nav.focused(&ctx).unwrap_or_else(|| panic!("Tab on the stage focuses an element")); + assert_eq!(first, (items[0].layer, items[0].element)); + let n = node(&t, crate::stage_a11y::node_id(first.0, first.1)).unwrap_or_else(|| panic!("the element has a node")); + assert_eq!(n.role(), Role::ListBoxOption); + assert_eq!(n.label(), Some(items[0].name.as_str())); + assert_eq!(n.is_selected(), Some(false)); + assert!(n.bounds().is_some_and(|b| b.x1 > b.x0 || b.y1 > b.y0) || items[0].bounds.is_empty(), "bounds on screen"); + assert_eq!(t.focus, crate::stage_a11y::node_id(first.0, first.1).accesskit_id(), "the reader's focus is on it"); + // The list box is the canvas's child, and its options are the list's. + let list = t.nodes.iter().find(|(_, n)| n.role() == Role::ListBox && n.children().contains(&crate::stage_a11y::node_id(first.0, first.1).accesskit_id())); + assert!(list.is_some(), "the options sit in a list box"); + let canvas = t.nodes.iter().find(|(_, n)| n.role() == Role::Canvas && n.label().is_some_and(|l| l.starts_with("Stage"))).map(|(_, n)| n); + assert!(canvas.is_some_and(|c| list.is_some_and(|(id, _)| c.children().contains(id))), "the list box is the stage's child"); + // Space selects it alone; the arrows move on without nudging; Shift+Space adds the next. + key(&ctx, &mut app, egui::Key::Space, egui::Modifiers::NONE); + assert!(app.s.selection.contains(first.0, first.1) && app.s.selection.len() == 1); + let before = crate::stage_a11y::items(&app).0.iter().map(|i| i.bounds).collect::>(); + key(&ctx, &mut app, egui::Key::ArrowRight, egui::Modifiers::NONE); + let second = app.stage_nav.focused(&ctx).unwrap_or_else(|| panic!("an element has focus")); + assert_eq!(second, (items[1].layer, items[1].element)); + assert_eq!(crate::stage_a11y::items(&app).0.iter().map(|i| i.bounds).collect::>(), before, "the arrows moved focus, not the artwork"); + key(&ctx, &mut app, egui::Key::Space, egui::Modifiers::SHIFT); + assert!(app.s.selection.contains(second.0, second.1) && app.s.selection.contains(first.0, first.1)); + let t = key(&ctx, &mut app, egui::Key::Space, egui::Modifiers::SHIFT).unwrap_or_else(|| panic!("no tree")); + assert!(!app.s.selection.contains(second.0, second.1) && app.s.selection.len() == 1, "Shift+Space again takes it out"); + assert_eq!(node(&t, crate::stage_a11y::node_id(first.0, first.1)).and_then(Node::is_selected), Some(true)); + // Left from the first wraps to the last; Enter selects it alone. + key(&ctx, &mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE); + key(&ctx, &mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE); + let last = items.last().map(|i| (i.layer, i.element)); + assert_eq!(app.stage_nav.focused(&ctx), last); + key(&ctx, &mut app, egui::Key::Enter, egui::Modifiers::NONE); + assert!(!app.playing, "Enter on an element selects, it doesn't play"); + // The sample's sky is on a locked layer: listed (unavailable), never selected. + assert!(items.last().is_some_and(|i| i.locked)); + assert!(app.s.selection.contains(first.0, first.1) && app.s.selection.len() == 1, "a locked element isn't selected"); + key(&ctx, &mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE); + key(&ctx, &mut app, egui::Key::Enter, egui::Modifiers::NONE); + let before_last = items.get(items.len() - 2).map(|i| (i.layer, i.element)); + assert!(before_last.is_some_and(|(l, e)| app.s.selection.contains(l, e)) && app.s.selection.len() == 1, "Enter selects it alone"); + // Esc goes back to the stage itself. + key(&ctx, &mut app, egui::Key::Escape, egui::Modifiers::NONE); + assert!(app.stage_nav.focused(&ctx).is_none()); + assert_eq!(focused_region(&ctx), Some(Region::Stage)); + assert_eq!(keyboard(&ctx), Keyboard::App, "the stage has the keyboard again: arrows nudge"); + } + + #[test] + fn stage_elements_and_timeline_frames_pass_the_audit() { + let (_, mut app, ctx) = tree(|_, _| {}); + focus_stage(&ctx, &mut app); + let t = key(&ctx, &mut app, egui::Key::Tab, egui::Modifiers::NONE).unwrap_or_else(|| panic!("no tree")); + assert!(t.nodes.iter().filter(|(_, n)| n.role() == Role::ListBoxOption).count() >= 2); + let found = audit(&t); + assert!(found.is_empty(), "{}", found.join("\n")); + } + #[test] fn ctrl_f6_moves_focus_through_the_panels_and_back() { let (_, mut app, ctx) = tree(|_, _| {}); diff --git a/src/app.rs b/src/app.rs index 6f3e36f3..28759769 100644 --- a/src/app.rs +++ b/src/app.rs @@ -440,6 +440,8 @@ pub struct App { heard: Option<(usize, u32)>, /// The panel Ctrl+F6 last moved focus to (where the next press continues from). pub last_panel: Option, + /// The stage's elements as keyboard stops and screen-reader nodes (ADR 0064). + pub stage_nav: crate::stage_a11y::StageNav, /// The start screen, while it is up (ADR 0059). pub start: Option, /// Files dragged over and dropped onto the window (ADR 0059). @@ -612,6 +614,7 @@ impl App { audio_clock: false, heard: None, last_panel: None, + stage_nav: Default::default(), start: None, drop: Default::default(), thumbs: Default::default(), diff --git a/src/main.rs b/src/main.rs index 7ffdd8c2..655e7479 100644 --- a/src/main.rs +++ b/src/main.rs @@ -58,6 +58,7 @@ mod scale_grid; mod sound; mod shape_hints; mod stage; +mod stage_a11y; mod start; mod test_movie; mod theme; diff --git a/src/stage.rs b/src/stage.rs index 583b6e86..50f3ede8 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -1145,6 +1145,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { ), }; crate::a11y::surface(ui, &resp, &name); + // Its elements, one by one, while it has the keyboard (ADR 0064). + crate::stage_a11y::show(app, ui, &resp, |p| to_screen(p)); } // ----- raw shapes (ADR 0031, 0041) ---------------------------------------------------------------- diff --git a/src/stage_a11y.rs b/src/stage_a11y.rs new file mode 100644 index 00000000..5f0a1233 --- /dev/null +++ b/src/stage_a11y.rs @@ -0,0 +1,376 @@ +//! The stage's elements for screen readers and the keyboard (ADR 0064). +//! +//! While the stage has keyboard focus, its canvas node gets one child: a multi-select list box, +//! "Elements on frame 12", with one option per element on the frame (layers top to bottom, each +//! front to back). An option says what the element is ("Rectangle", "Text: Hello", "hero · +//! Movie clip: Ball"), its layer, place and size, and whether it is selected; its bounds are +//! where it is on screen, so a reader's highlight lands on the artwork. +//! +//! Keys: Tab on the stage goes to the first selected element (or the first one); then Tab, +//! Shift+Tab and the arrow keys move between elements (wrapping), Enter or Space selects the +//! element alone, Shift+Enter or Shift+Space adds it to the selection or takes it out, and Esc +//! goes back to the stage itself (where the arrows nudge again). Selection goes through +//! `element.select`, so it is the same command a click, the CLI and MCP use. +//! +//! Nothing here exists while the stage doesn't have focus, so the rest of the interface keeps +//! its tab order and the tree stays small. A frame with more than [`MAX_NODES`] elements lists +//! the first ones and a summary of the rest. + +use crate::app::App; +use crate::theme::T; +use anicraft_engine::doc::{Document, Element, ElementId, ElementKind, LayerId, LayerKind, Paint, SymbolKind}; +use anicraft_engine::geom::{Path, PathCmd, Rect as GRect}; +use egui::accesskit::{Action, Role}; +use egui::{Id, Key, Modifiers, Pos2, Rect, Response, Sense, Stroke, StrokeKind, UiBuilder, Vec2}; +use serde_json::json; +use std::collections::HashMap; + +/// Most elements exposed one by one; the rest are summed up in one node. +pub const MAX_NODES: usize = 2_000; + +/// One element as a screen reader hears it. +#[derive(Clone, Debug)] +pub struct Item { + pub layer: LayerId, + pub element: ElementId, + /// What it is: "Rectangle", "Text: Hello", "hero · Movie clip: Ball". + pub name: String, + /// Where: "Layer Hills · x 120, y 80 · 200 × 40 px". + pub detail: String, + /// Bounds in the space the stage draws in (the open symbol's, while one is open). + pub bounds: GRect, + pub selected: bool, + /// On a locked layer: listed, but it can't be selected. + pub locked: bool, +} + +/// The stage's keyboard state: the element nodes made last frame, to tell which one has focus. +#[derive(Default)] +pub struct StageNav { + ids: Vec<(Id, LayerId, ElementId)>, +} + +impl StageNav { + /// The element with keyboard focus, if one has it. + pub fn focused(&self, ctx: &egui::Context) -> Option<(LayerId, ElementId)> { + let f = ctx.memory(|m| m.focused())?; + self.ids.iter().find(|(id, _, _)| *id == f).map(|(_, l, e)| (*l, *e)) + } +} + +pub fn node_id(layer: LayerId, element: ElementId) -> Id { + Id::new(("stage_element", layer.0, element.0)) +} + +/// What a path looks like it was drawn with (English, a key): the Rectangle, Oval and PolyStar +/// tools' outlines and the Line tool's segment; anything else is a shape. +pub fn shape_kind(p: &Path) -> &'static str { + let (mut moves, mut lines, mut curves, mut closes) = (0usize, 0usize, 0usize, 0usize); + let mut pts: Vec = Vec::new(); + for c in p.cmds.iter().take(64) { + match c { + PathCmd::MoveTo(v) => { + moves += 1; + pts.push(*v); + } + PathCmd::LineTo(v) => { + lines += 1; + pts.push(*v); + } + PathCmd::QuadTo(..) | PathCmd::CubicTo(..) => curves += 1, + PathCmd::Close => closes += 1, + } + } + if p.cmds.len() > 64 || moves != 1 { + return tr_noop!("Shape"); + } + let axis_aligned = || { + let mut ring = pts.clone(); + if let Some(first) = pts.first() { + ring.push(*first); + } + ring.windows(2).all(|w| matches!(w, [a, b] if (a.x - b.x).abs() < 1e-3 || (a.y - b.y).abs() < 1e-3)) + }; + match (lines, curves, closes) { + (1, 0, 0) => tr_noop!("Line"), + (3 | 4, 0, 1) if axis_aligned() => tr_noop!("Rectangle"), + // A rounded rectangle: four sides and four corners. + (4, 4, 1) => tr_noop!("Rectangle"), + (0, 4, 1) => tr_noop!("Oval"), + (n, 0, 1) if n >= 2 => tr_noop!("Polygon"), + _ => tr_noop!("Shape"), + } +} + +fn symbol_kind(k: SymbolKind) -> &'static str { + match k { + SymbolKind::Graphic => tr_noop!("Graphic"), + SymbolKind::MovieClip => tr_noop!("Movie clip"), + SymbolKind::Button => tr_noop!("Button"), + } +} + +/// The first `max` characters of `s` on one line, with "…" when cut. +fn excerpt(s: &str, max: usize) -> String { + let one: String = s.split_whitespace().collect::>().join(" "); + if one.chars().count() <= max { + return one; + } + let mut cut: String = one.chars().take(max).collect(); + cut.push('…'); + cut +} + +/// What an element is, in the interface language; its instance name (document text) first. +pub fn element_name(doc: &Document, e: &Element) -> String { + let what = match &e.kind { + ElementKind::Shape(sh) if matches!(sh.fill, Some(Paint::Bitmap { .. })) => tr!("Bitmap").to_string(), + ElementKind::Shape(sh) => crate::i18n::t(shape_kind(&sh.path)).to_string(), + ElementKind::Symbol { symbol, .. } => match doc.symbol(*symbol) { + Some(sym) => tr!("{kind}: {symbol}", kind = crate::i18n::t(symbol_kind(sym.kind)), symbol = sym.name), + None => tr!("Symbol instance").to_string(), + }, + ElementKind::Text(tb) if tb.text.trim().is_empty() => tr!("Empty text").to_string(), + ElementKind::Text(tb) => tr!("Text: {text}", text = excerpt(&tb.text, 80)), + ElementKind::Camera => tr!("Camera").to_string(), + }; + let name = excerpt(&e.name, 80); + if name.is_empty() { what } else { tr!("{name} · {what}", name = name, what = what) } +} + +/// The current frame's elements, as the list shows them, and how many there are in all. +pub fn items(app: &App) -> (Vec, usize) { + let s = &app.s; + let tl = s.timeline(); + // Bounds of every element in one pass over what the stage draws. + let mut bounds: HashMap<(LayerId, ElementId), GRect> = HashMap::new(); + for item in s.display_list().items.iter() { + let pad = item.stroke.as_ref().map_or(0.0, anicraft_engine::doc::Stroke::reach); + let r = item.path.bounds().inflate(pad).transformed(&item.transform); + let e = bounds.entry((item.layer, item.element)).or_insert(GRect::EMPTY); + *e = e.union(&r); + } + let mut out = Vec::new(); + let mut total = 0usize; + for (i, layer) in tl.layers.iter().enumerate() { + // Only what is on the stage: shown layers with artwork, not the camera. + if !layer.visible || tl.hidden_by_folder(i) || matches!(layer.kind, LayerKind::Folder | LayerKind::Camera) { + continue; + } + let locked = !s.selectable(layer.id); + let elements = s.elements_on(layer.id); + for e in elements.iter().rev().filter(|e| !matches!(e.kind, ElementKind::Camera)) { + total += 1; + if out.len() >= MAX_NODES { + continue; + } + let b = bounds.get(&(layer.id, e.id)).copied().unwrap_or_else(|| e.bounds(&s.doc)); + let detail = if b.is_empty() { + tr!("Layer {layer}", layer = layer.name) + } else { + tr!("Layer {layer} · x {x}, y {y} · {w} × {h} px", layer = layer.name, x = format!("{:.0}", b.min.x), y = format!("{:.0}", b.min.y), w = format!("{:.0}", b.width()), h = format!("{:.0}", b.height())) + }; + let detail = if locked { tr!("{detail} · locked", detail = detail) } else { detail }; + out.push(Item { layer: layer.id, element: e.id, name: element_name(&s.doc, e), detail, bounds: b, selected: s.selection.contains(layer.id, e.id), locked }); + } + } + (out, total) +} + +fn ak_rect(r: Rect) -> egui::accesskit::Rect { + egui::accesskit::Rect { x0: r.min.x.into(), y0: r.min.y.into(), x1: r.max.x.into(), y1: r.max.y.into() } +} + +/// What a key press on a focused element does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Step { + Next, + Prev, + Select, + Toggle, + Leave, +} + +fn element_keys(i: &mut egui::InputState) -> Option { + for (m, k, step) in [ + (Modifiers::SHIFT, Key::Tab, Step::Prev), + (Modifiers::NONE, Key::Tab, Step::Next), + (Modifiers::NONE, Key::ArrowRight, Step::Next), + (Modifiers::NONE, Key::ArrowDown, Step::Next), + (Modifiers::NONE, Key::ArrowLeft, Step::Prev), + (Modifiers::NONE, Key::ArrowUp, Step::Prev), + (Modifiers::SHIFT, Key::Enter, Step::Toggle), + (Modifiers::SHIFT, Key::Space, Step::Toggle), + (Modifiers::NONE, Key::Enter, Step::Select), + (Modifiers::NONE, Key::Space, Step::Select), + (Modifiers::NONE, Key::Escape, Step::Leave), + ] { + if i.consume_key(m, k) { + return Some(step); + } + } + None +} + +/// Selects `it` alone (`toggle`: adds it to the selection or takes it out) and says so. +fn select(app: &mut App, it: &Item, toggle: bool) { + let params = if toggle { json!({"ids": [it.element.0], "layer": it.layer.0, "toggle": true}) } else { json!({"ids": [it.element.0], "layer": it.layer.0}) }; + if app.run("element.select", params).is_some() { + let n = app.s.selection.len(); + let now = app.s.selection.contains(it.layer, it.element); + let what = if now { tr!("Selected {name}", name = it.name) } else { tr!("Deselected {name}", name = it.name) }; + app.status_ok(trn!("{what} · {n} element selected", "{what} · {n} elements selected", n, what = what)); + } +} + +/// The element list under the stage's node, and its keys. `to_screen` maps the stage's drawing +/// space to the screen. Call after the stage has drawn, while `stage` is its canvas response. +pub fn show(app: &mut App, ui: &mut egui::Ui, stage: &Response, to_screen: impl Fn(anicraft_engine::geom::Vec2) -> Pos2) { + let ctx = ui.ctx().clone(); + let focused = ctx.memory(|m| m.focused()); + let on_canvas = focused == Some(stage.id); + let on_element = app.stage_nav.focused(&ctx); + if !on_canvas && on_element.is_none() { + app.stage_nav.ids.clear(); + return; + } + let (mut list, mut total) = items(app); + let screen = |b: GRect| -> Rect { + if b.is_empty() { + return Rect::from_center_size(stage.rect.center(), Vec2::ZERO); + } + Rect::from_two_pos(to_screen(b.min), to_screen(b.max)) + }; + + // ---- keys ----------------------------------------------------------------------------- + let mut focus_to: Option = None; + if on_canvas && !list.is_empty() { + // Tab goes into the list: to the selection, or the first element. + let (fwd, back) = ctx.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::Tab), i.consume_key(Modifiers::SHIFT, Key::Tab))); + let pick = if fwd { + list.iter().position(|it| it.selected).or(Some(0)) + } else if back { + list.iter().rposition(|it| it.selected).or(Some(list.len() - 1)) + } else { + None + }; + if let Some(it) = pick.and_then(|i| list.get(i)) { + focus_to = Some(node_id(it.layer, it.element)); + } + } + if let Some((layer, el)) = on_element { + let at = list.iter().position(|it| it.layer == layer && it.element == el); + match (at, ctx.input_mut(element_keys)) { + // Gone from the frame (deleted, or the playhead moved): back to the stage. + (None, _) => focus_to = Some(stage.id), + (Some(i), Some(Step::Next)) => focus_to = list.get((i + 1) % list.len()).map(|it| node_id(it.layer, it.element)), + (Some(i), Some(Step::Prev)) => focus_to = list.get((i + list.len() - 1) % list.len()).map(|it| node_id(it.layer, it.element)), + (Some(i), Some(step @ (Step::Select | Step::Toggle))) => { + if let Some(it) = list.get(i).cloned() { + select(app, &it, step == Step::Toggle); + (list, total) = items(app); + } + } + (Some(_), Some(Step::Leave)) => focus_to = Some(stage.id), + (Some(_), None) => {} + } + } + // A screen reader's "click" on an option selects it, as Enter does. + let clicked = list.iter().find(|it| ctx.input(|i| i.has_accesskit_action_request(node_id(it.layer, it.element), Action::Click))).cloned(); + if let Some(it) = clicked { + select(app, &it, false); + (list, total) = items(app); + } + + // ---- nodes ---------------------------------------------------------------------------- + let child = ui.new_child(UiBuilder::new().id_salt("stage_elements").accessibility_parent(stage.id).max_rect(stage.rect).sense(Sense::hover())); + let frame = app.s.frame + 1; + ctx.accesskit_node_builder(child.unique_id(), |n| { + n.set_role(Role::ListBox); + n.set_label(trn!("{n} element on frame {frame}", "{n} elements on frame {frame}", total, frame = frame)); + n.set_multiselectable(); + n.set_bounds(ak_rect(stage.rect)); + }); + app.stage_nav.ids.clear(); + let count = list.len(); + let filter = egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true }; + for (i, it) in list.iter().enumerate() { + let id = node_id(it.layer, it.element); + let r = screen(it.bounds); + // No pointer area (the canvas takes the clicks): a focus stop with its bounds. + let resp = child.interact(Rect::from_center_size(r.center(), Vec2::ZERO), id, Sense::FOCUSABLE); + ctx.accesskit_node_builder(id, |n| { + n.set_role(Role::ListBoxOption); + n.set_label(it.name.as_str()); + n.set_description(it.detail.as_str()); + n.set_selected(it.selected); + n.set_bounds(ak_rect(r)); + n.set_position_in_set(i + 1); + n.set_size_of_set(total); + n.add_action(Action::Click); + if it.locked { + n.set_disabled(); + } + }); + if resp.has_focus() { + ctx.memory_mut(|m| m.set_focus_lock_filter(id, filter)); + // The keyboard focus, drawn on the artwork. + ui.painter().rect_stroke(r.expand(3.0), T.rc(), Stroke::new(2.0, T.accent), StrokeKind::Outside); + } + app.stage_nav.ids.push((id, it.layer, it.element)); + } + if total > count { + let id = child.unique_id().with("more"); + child.interact(Rect::from_center_size(stage.rect.center(), Vec2::ZERO), id, Sense::hover()); + ctx.accesskit_node_builder(id, |n| { + n.set_role(Role::Label); + n.set_label(trn!( + "{n} more element is not listed: pick it on the stage, or use Select All or Find", + "{n} more elements are not listed: pick them on the stage, or use Select All or Find", + total - count + )); + }); + } + if on_canvas { + // Tab goes into the list (when there is one); the arrows nudge, as before. + let tab = !list.is_empty(); + ctx.memory_mut(|m| m.set_focus_lock_filter(stage.id, egui::EventFilter { tab, horizontal_arrows: true, vertical_arrows: true, ..Default::default() })); + } + if let Some(id) = focus_to { + ctx.memory_mut(|m| m.request_focus(id)); + if id != stage.id + && let Some(it) = list.iter().find(|it| node_id(it.layer, it.element) == id) + { + // A reader says the newly focused option itself; the status bar says it for everyone. + let state = if it.selected { tr!("selected") } else { tr!("not selected") }; + app.status_ok(tr!("{name} · {state} · Enter selects, Esc goes back to the stage", name = it.name, state = state)); + } + ctx.request_repaint(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::geom::Vec2 as V; + + #[test] + fn shapes_are_named_by_the_tool_that_draws_them() { + assert_eq!(shape_kind(&Path::rect(0.0, 0.0, 10.0, 5.0)), "Rectangle"); + assert_eq!(shape_kind(&Path::rounded_rect(0.0, 0.0, 10.0, 5.0, 2.0)), "Rectangle"); + assert_eq!(shape_kind(&Path::ellipse(0.0, 0.0, 4.0, 3.0)), "Oval"); + assert_eq!(shape_kind(&Path::star(0.0, 0.0, 10.0, 4.0, 5)), "Polygon"); + assert_eq!(shape_kind(&Path::line(V::new(0.0, 0.0), V::new(3.0, 4.0))), "Line"); + // A slanted quadrilateral is a polygon, not a rectangle. + let mut p = Path::new(); + p.move_to(V::new(0.0, 0.0)).line_to(V::new(10.0, 1.0)).line_to(V::new(10.0, 6.0)).line_to(V::new(0.0, 5.0)).close(); + assert_eq!(shape_kind(&p), "Polygon"); + assert_eq!(shape_kind(&Path::new()), "Shape"); + } + + #[test] + fn long_text_is_cut_to_one_line() { + assert_eq!(excerpt("Hello\n world", 80), "Hello world"); + assert_eq!(excerpt(&"a".repeat(100), 5), "aaaaa…"); + } +} From 3f86e60414c3d4417b115bdf343ed9db9cf29c76 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:44:28 -0700 Subject: [PATCH 067/192] feat(a11y): timeline frames for screen readers; arrows move and announce the playhead and layer (M8) --- src/a11y.rs | 37 +++++++++++++++ src/app.rs | 36 ++++++++++++++- src/timeline.rs | 118 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 190 insertions(+), 1 deletion(-) diff --git a/src/a11y.rs b/src/a11y.rs index ac3cb06a..efefa8ff 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -521,6 +521,43 @@ mod tests { assert!(found.is_empty(), "{}", found.join("\n")); } + #[test] + fn the_focused_timeline_moves_and_announces_the_playhead_and_layer_and_lists_its_spans() { + let (_, mut app, ctx) = tree(|_, _| {}); + while focused_region(&ctx) != Some(Region::Timeline) { + key(&ctx, &mut app, egui::Key::F6, egui::Modifiers::COMMAND); + } + app.run("layer.select", serde_json::json!({"index": 0})); + app.tl_refocus = true; + frame(&ctx, &mut app, input(1.0)); + frame(&ctx, &mut app, input(1.0)); + let (frame0, layer0) = (app.s.frame, app.s.layer); + let t = key(&ctx, &mut app, egui::Key::ArrowRight, egui::Modifiers::NONE).unwrap_or_else(|| panic!("no tree")); + assert_eq!(app.s.frame, frame0 + 1, "Right is the next frame"); + let said = app.status.as_ref().map(|s| s.text.clone()).unwrap_or_default(); + assert!(said.starts_with(&format!("Frame {}", frame0 + 2)), "announced: {said}"); + // The active layer's spans are list items under its frame grid, the playhead's selected. + let items: Vec<&Node> = t.nodes.iter().filter(|(_, n)| n.role() == Role::ListItem).map(|(_, n)| n).collect(); + assert!(!items.is_empty(), "the active layer's spans are listed"); + assert!(items.iter().all(|n| n.label().is_some_and(|l| l.starts_with("Frame"))), "{:?}", items.iter().map(|n| n.label()).collect::>()); + assert_eq!(items.iter().filter(|n| n.is_selected() == Some(true)).count(), 1, "one span holds the playhead"); + let grid = t.nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.starts_with("Frames of")) && !n.children().is_empty()); + assert!(grid.is_some(), "the list sits under the active layer's frame grid"); + assert!(audit(&t).is_empty(), "{}", audit(&t).join("\n")); + // Left goes back; Down moves to the next layer and keeps the keyboard on the timeline. + key(&ctx, &mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert_eq!(app.s.frame, frame0); + key(&ctx, &mut app, egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_ne!(app.s.layer, layer0, "Down is the layer below"); + assert_eq!(app.s.timeline().layers.iter().position(|l| l.id == app.s.layer), Some(1)); + assert_eq!((focused_region(&ctx), keyboard(&ctx)), (Some(Region::Timeline), Keyboard::App), "the new row has the keyboard"); + key(&ctx, &mut app, egui::Key::ArrowUp, egui::Modifiers::NONE); + assert_eq!(app.s.layer, layer0); + let said = app.status.as_ref().map(|s| s.text.clone()).unwrap_or_default(); + let name = app.s.timeline().layer(layer0).map(|l| l.name.clone()).unwrap_or_default(); + assert!(said.contains(&name), "the layer is announced: {said}"); + } + #[test] fn ctrl_f6_moves_focus_through_the_panels_and_back() { let (_, mut app, ctx) = tree(|_, _| {}); diff --git a/src/app.rs b/src/app.rs index 28759769..78236a0b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -442,6 +442,10 @@ pub struct App { pub last_panel: Option, /// The stage's elements as keyboard stops and screen-reader nodes (ADR 0064). pub stage_nav: crate::stage_a11y::StageNav, + /// The layer and frame the focused timeline last announced (ADR 0064). + pub tl_heard: Option<(anicraft_engine::doc::LayerId, u32)>, + /// The arrows moved the active layer: its row takes keyboard focus when drawn. + pub tl_refocus: bool, /// The start screen, while it is up (ADR 0059). pub start: Option, /// Files dragged over and dropped onto the window (ADR 0059). @@ -615,6 +619,8 @@ impl App { heard: None, last_panel: None, stage_nav: Default::default(), + tl_heard: None, + tl_refocus: false, start: None, drop: Default::default(), thumbs: Default::default(), @@ -2169,6 +2175,10 @@ impl App { let mut play = false; let mut nudge = egui::Vec2::ZERO; let surface_focused = ctx.memory(|m| m.focused().is_some()); + // On the focused timeline the arrows move the playhead (Left, Right) and the active + // layer (Up, Down) instead of nudging artwork (ADR 0064). + let on_timeline = surface_focused && crate::a11y::focused_region(ctx) == Some(crate::a11y::Region::Timeline); + let (mut frame_step, mut layer_step) = (0i64, 0i64); ctx.input_mut(|i| { for (m, k, id) in &self.shortcuts { if i.consume_key(*m, *k) { @@ -2188,7 +2198,14 @@ impl App { // Screen pixels, as in Animate: a press moves less the further you zoom in. let step = if i.modifiers.shift { 10.0 } else { 1.0 } / self.view.zoom.max(1e-3); for (k, d) in [(Key::ArrowLeft, egui::vec2(-step, 0.0)), (Key::ArrowRight, egui::vec2(step, 0.0)), (Key::ArrowUp, egui::vec2(0.0, -step)), (Key::ArrowDown, egui::vec2(0.0, step))] { - if i.key_pressed(k) && !i.modifiers.command { + if on_timeline && i.consume_key(Modifiers::NONE, k) { + match k { + Key::ArrowLeft => frame_step -= 1, + Key::ArrowRight => frame_step += 1, + Key::ArrowUp => layer_step -= 1, + _ => layer_step += 1, + } + } else if i.key_pressed(k) && !i.modifiers.command { nudge += d; } } @@ -2224,6 +2241,22 @@ impl App { if let Some(t) = tool { self.tool = t; } + if frame_step != 0 { + self.playing = false; + let last = i64::from(self.s.frame_count().saturating_sub(1)); + let to = (i64::from(self.s.frame) + frame_step).clamp(0, last.max(0)); + self.run("timeline.goto", json!({"frame": to})); + } + if layer_step != 0 { + let layers = &self.s.timeline().layers; + if let Some(at) = layers.iter().position(|l| l.id == self.s.layer) { + let to = (at as i64 + layer_step).clamp(0, layers.len() as i64 - 1); + if to != at as i64 && self.run("layer.select", json!({"index": to})).is_some() { + // The keyboard goes with it, to the new active row. + self.tl_refocus = true; + } + } + } if play { self.toggle_play(); } @@ -2470,6 +2503,7 @@ impl App { self.glyph_check = false; } self.handle_shortcuts(&ctx); + timeline::announce(self, &ctx); // Switching away from a path tool keeps its work: a Pen path in progress is finished. if self.tool != Tool::Pen && self.pen.is_some() { pathtools::commit_pen(self, false); diff --git a/src/timeline.rs b/src/timeline.rs index 9a871832..81c18280 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -548,6 +548,13 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if is_active || r == first_row { a11y::anchor(ui, a11y::Region::Timeline, dock, &nr); } + if is_active && app.tl_refocus { + app.tl_refocus = false; + // (Asking again would reset the focus filter that keeps the arrows here.) + if !nr.has_focus() { + nr.request_focus(); + } + } for (r, id, salt, label, on) in [(eye, "layer.toggle_visible", "eye", tr!("Show {name}", name = name), layer.visible), (lock, "layer.toggle_lock", "lock", tr!("Lock {name}", name = name), layer.locked), (outl, "layer.toggle_outline", "outline", tr!("Outline {name}", name = name), layer.outline)].into_iter().take(if is_camera { 2 } else { 3 }) { let rr = ui.interact(r, ui.id().with((salt, layer.id.0)), Sense::click()); a11y::control(ui, &rr, WidgetType::Checkbox, &label, Some(on)); @@ -844,6 +851,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } let cr = ui.interact(cells, ui.id().with(("cells", layer.id.0)), a11y::pointer_only()); a11y::control(ui, &cr, WidgetType::Button, &tr!("Frames of {name}", name = layer.name), None); + if is_active { + // Its keyframes and spans, one by one, for screen readers (ADR 0064). + frame_nodes(app, ui, &cr, layer, |f| x_of(f), y); + } let shift = ui.input(|inp| inp.modifiers.shift); if cr.clicked() || cr.drag_started() || cr.secondary_clicked() { app.timeline_focus = true; @@ -1224,6 +1235,113 @@ fn frame_view_button(app: &mut App, ui: &mut egui::Ui) { } } +/// While the timeline has the keyboard, says where the playhead went (through the status bar, +/// a live region): "Frame 12 · Ball · Frames 1–24: keyframe · motion tween". Quiet while playing, +/// and on the frame the focus arrived at (Ctrl+F6 has just said the panel). +pub fn announce(app: &mut App, ctx: &egui::Context) { + let focused = ctx.memory(|m| m.focused().is_some()) && a11y::focused_region(ctx) == Some(a11y::Region::Timeline); + let now = (app.s.layer, app.s.frame); + if !focused || app.playing { + app.tl_heard = if focused { Some(now) } else { None }; + return; + } + if app.tl_heard.is_some_and(|h| h != now) { + let Some(layer) = app.s.timeline().layer(now.0) else { return }; + let what = frame_text(layer, now.1).unwrap_or_else(|| tr!("no frame").to_string()); + let msg = tr!("Frame {frame} · {layer} · {what}", frame = now.1 + 1, layer = layer.name, what = what); + app.status_ok(msg); + } + app.tl_heard = Some(now); +} + +/// Most spans of the active layer listed one by one; the rest are summed up. +pub const MAX_SPAN_NODES: usize = 1_000; + +/// What a span is, as a screen reader hears it: "Frames 1–24: keyframe · motion tween · label +/// “walk”". `next_adjacent`: the next keyframe starts where this one ends (a tween reaches it). +pub fn span_text(k: &anicraft_engine::doc::Keyframe, next_adjacent: bool) -> String { + let (a, b) = (k.start + 1, k.end()); + let frames = if k.duration <= 1 { tr!("Frame {a}", a = a) } else { tr!("Frames {a}–{b}", a = a, b = b) }; + let mut parts: Vec = vec![if k.elements.is_empty() { tr!("blank keyframe").to_string() } else { tr!("keyframe").to_string() }]; + if k.motion.is_some() { + parts.push(tr!("motion tween").to_string()); + } else if let Some(t) = k.tween { + parts.push(match (t.kind, next_adjacent) { + (_, false) => tr!("broken tween").to_string(), + (TweenKind::Shape, true) => tr!("shape tween").to_string(), + (TweenKind::Classic, true) => tr!("classic tween").to_string(), + }); + } + if !k.label.is_empty() { + parts.push(tr!("label “{label}”", label = k.label)); + } + if k.sound.is_some() { + parts.push(tr!("sound").to_string()); + } + if k.script.is_some() { + parts.push(tr!("actions").to_string()); + } + tr!("{frames}: {what}", frames = frames, what = parts.join(" · ")) +} + +/// The span of `layer` at `frame`, described (`None`: no frame there). +pub fn frame_text(layer: &Layer, frame: u32) -> Option { + let ki = layer.keyframes.iter().position(|k| k.covers(frame))?; + let k = layer.keyframes.get(ki)?; + Some(span_text(k, layer.keyframes.get(ki + 1).is_some_and(|n| n.start == k.end()))) +} + +/// The active layer's spans as a list under its frame grid's node: each says its frames, what +/// is there and its tween; the one under the playhead is selected; a reader's click moves the +/// playhead there. +fn frame_nodes(app: &mut App, ui: &mut egui::Ui, grid: &egui::Response, layer: &Layer, x_of: impl Fn(u32) -> f32, y: f32) { + use egui::accesskit::{Action, Role}; + let ctx = ui.ctx().clone(); + let child = ui.new_child(egui::UiBuilder::new().id_salt(("frame_list", layer.id.0)).accessibility_parent(grid.id).max_rect(grid.rect).sense(Sense::hover())); + let ak = |r: Rect| egui::accesskit::Rect { x0: r.min.x.into(), y0: r.min.y.into(), x1: r.max.x.into(), y1: r.max.y.into() }; + let total = layer.keyframes.len(); + ctx.accesskit_node_builder(child.unique_id(), |n| { + n.set_role(Role::List); + n.set_label(trn!("{n} keyframe span on {name}", "{n} keyframe spans on {name}", total, name = layer.name)); + n.set_bounds(ak(grid.rect)); + }); + let mut goto = None; + for (ki, k) in layer.keyframes.iter().enumerate().take(MAX_SPAN_NODES) { + let id = child.unique_id().with(("span", k.start)); + let r = Rect::from_min_max(pos2(x_of(k.start), y), pos2(x_of(k.end()), y + ROW_H)).intersect(grid.rect); + child.interact(Rect::from_center_size(r.center(), egui::Vec2::ZERO), id, Sense::hover()); + let next_adjacent = layer.keyframes.get(ki + 1).is_some_and(|n| n.start == k.end()); + let name = span_text(k, next_adjacent); + ctx.accesskit_node_builder(id, |n| { + n.set_role(Role::ListItem); + n.set_label(name); + n.set_selected(k.covers(app.s.frame)); + if r.is_positive() { + n.set_bounds(ak(r)); + } + n.set_position_in_set(ki + 1); + n.set_size_of_set(total); + n.add_action(Action::Click); + }); + if ctx.input(|i| i.has_accesskit_action_request(id, Action::Click)) { + goto = Some(k.start); + } + } + if total > MAX_SPAN_NODES { + let id = child.unique_id().with("more"); + child.interact(Rect::from_center_size(grid.rect.center(), egui::Vec2::ZERO), id, Sense::hover()); + ctx.accesskit_node_builder(id, |n| { + n.set_role(Role::Label); + n.set_label(trn!("{n} more span is not listed: go there with , and . or Home and End", "{n} more spans are not listed: go there with , and . or Home and End", total - MAX_SPAN_NODES)); + }); + } + if let Some(f) = goto { + app.playing = false; + app.run("timeline.goto", json!({"frame": f})); + } +} + + /// Engine param for an easing preset. /// A keyframe's sound over its span: the waveform from the keyframe on, repeated as the sound /// repeats, as far as the span reaches (all a stream sound plays; an event sound plays on past From cb3a084388d455bec3de7ea3621191aa18bdc054 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:54:58 -0700 Subject: [PATCH 068/192] feat(a11y): the menu bar from the keyboard: Alt, F10, arrows, access keys (M8) --- src/a11y.rs | 100 +++++++++++ src/app.rs | 9 + src/guidelines_tests.rs | 3 +- src/menus.rs | 389 +++++++++++++++++++++++++++++++++++++++- src/platform.rs | 6 + src/theme.rs | 19 ++ 6 files changed, 523 insertions(+), 3 deletions(-) diff --git a/src/a11y.rs b/src/a11y.rs index efefa8ff..b238987c 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -558,6 +558,106 @@ mod tests { assert!(said.contains(&name), "the layer is announced: {said}"); } + #[test] + fn access_keys_take_the_first_free_letter() { + let keys = crate::menus::access_keys(&["File", "Edit", "View", "Insert", "Modify", "Commands", "Control", "Window", "Help"]); + let letters: String = keys.iter().map(|k| k.map_or('-', |(_, c)| c)).collect(); + assert_eq!(letters, "FEVIMCOWH", "Control takes its O, as in Animate"); + assert_eq!(crate::menus::access_keys(&["Fichier", "Édition", "Ändern", "日本"]), vec![Some((0, 'F')), Some((1, 'D')), Some((1, 'N')), None]); + } + + #[test] + fn the_menu_bar_works_from_the_keyboard() { + if !crate::menus::MenuKeys::available() { + return; // macOS keeps its own menu conventions (ADR 0064). + } + use egui::{Key, Modifiers as M}; + let (_, mut app, ctx) = tree(|_, _| {}); + let tops = app.menu_keys.top_ids().to_vec(); + assert_eq!(tops.len(), crate::menus::TOP_MENUS.len()); + let focused = |ctx: &egui::Context| ctx.memory(|m| m.focused()); + let open = |ctx: &egui::Context, i: usize| egui::Popup::is_id_open(ctx, tops[i].with("popup")); + // F10 focuses File; the titles show their access keys. + let t = key(&ctx, &mut app, Key::F10, M::NONE).unwrap_or_else(|| panic!("no tree")); + assert_eq!(focused(&ctx), Some(tops[0])); + assert!(app.menu_keys.show_keys); + assert_eq!(node(&t, tops[0]).and_then(Node::access_key), Some("Alt+F")); + // Right: Edit; Down opens it on its first item; Down, Up and Up wrap round. + key(&ctx, &mut app, Key::ArrowRight, M::NONE); + assert_eq!(focused(&ctx), Some(tops[1])); + key(&ctx, &mut app, Key::ArrowDown, M::NONE); + frame(&ctx, &mut app, input(1.0)); + assert!(open(&ctx, 1), "Down opens Edit"); + let items = app.menu_keys.open_items(&ctx); + assert!(items.len() > 3, "Edit has items: {}", items.len()); + assert_eq!(focused(&ctx), items.first().copied(), "on its first item"); + key(&ctx, &mut app, Key::ArrowDown, M::NONE); + assert_eq!(focused(&ctx), items.get(1).copied()); + key(&ctx, &mut app, Key::ArrowUp, M::NONE); + key(&ctx, &mut app, Key::ArrowUp, M::NONE); + assert_eq!(focused(&ctx), items.last().copied(), "Up from the first wraps to the last"); + assert_eq!(keyboard(&ctx), Keyboard::Control, "the menu keeps Enter and the arrows"); + // Right on an item: the next menu, open, on its first item. + key(&ctx, &mut app, Key::ArrowRight, M::NONE); + frame(&ctx, &mut app, input(1.0)); + assert!(open(&ctx, 2) && !open(&ctx, 1), "Right goes on to View"); + assert_eq!(focused(&ctx), app.menu_keys.open_items(&ctx).first().copied()); + // Esc closes the menu, back on its title; Esc again leaves the bar. + key(&ctx, &mut app, Key::Escape, M::NONE); + assert!(!open(&ctx, 2)); + assert_eq!(focused(&ctx), Some(tops[2])); + key(&ctx, &mut app, Key::Escape, M::NONE); + assert_eq!(focused(&ctx), None, "nothing had focus before"); + assert!(!app.menu_keys.show_keys); + // Alt pressed and let go alone also focuses the bar (and again leaves it). + let mods = |m: M| { + let mut i = input(1.0); + i.events.push(egui::Event::ModifiersChanged(m)); + i + }; + frame(&ctx, &mut app, mods(M::ALT)); + frame(&ctx, &mut app, input(1.0)); + assert!(app.menu_keys.show_keys, "titles are underlined while Alt is held"); + frame(&ctx, &mut app, mods(M::NONE)); + frame(&ctx, &mut app, input(1.0)); + assert_eq!(focused(&ctx), Some(tops[0]), "an Alt tap focuses File"); + key(&ctx, &mut app, Key::Escape, M::NONE); + // Alt+H opens Help from the stage; an item chosen with Enter runs and the keyboard goes + // back to the stage. + focus_stage(&ctx, &mut app); + let stage = focused(&ctx); + key(&ctx, &mut app, Key::H, M::ALT); + frame(&ctx, &mut app, input(1.0)); + let help = crate::menus::TOP_MENUS.iter().position(|t| *t == "Help").unwrap_or(0); + assert!(open(&ctx, help), "Alt+H opens Help"); + let t = frame(&ctx, &mut app, input(1.0)).platform_output.accesskit_update.unwrap_or_else(|| panic!("no tree")); + let found = audit(&t); + assert!(found.is_empty(), "the open menu passes the audit:\n{}", found.join("\n")); + let palette = app.menu_keys.open_items(&ctx).into_iter().position(|id| node(&t, id).and_then(Node::label).is_some_and(|l| l.starts_with("Command Palette"))); + let palette = palette.unwrap_or_else(|| panic!("Help has Command Palette…")); + while app.menu_keys.open_items(&ctx).iter().position(|id| Some(*id) == focused(&ctx)) != Some(palette) { + key(&ctx, &mut app, Key::ArrowDown, M::NONE); + } + key(&ctx, &mut app, Key::Enter, M::NONE); + frame(&ctx, &mut app, input(1.0)); + assert!(app.palette.is_some(), "Enter ran the item"); + assert!(!open(&ctx, help)); + app.palette = None; + // View's first item is Zoom In: chosen with Enter, it zooms and the keyboard goes back + // to the stage. + focus_stage(&ctx, &mut app); + let stage = focused(&ctx); + let zoom = app.view.zoom; + key(&ctx, &mut app, Key::V, M::ALT); + frame(&ctx, &mut app, input(1.0)); + assert!(open(&ctx, 2), "Alt+V opens View"); + key(&ctx, &mut app, Key::Enter, M::NONE); + frame(&ctx, &mut app, input(1.0)); + assert!(app.view.zoom > zoom, "Zoom In ran"); + assert_eq!(focused(&ctx), stage, "the keyboard went back to the stage"); + assert_eq!(app.tool, crate::app::Tool::Select, "Alt+V opened View; it didn't pick the Selection tool's V"); + } + #[test] fn ctrl_f6_moves_focus_through_the_panels_and_back() { let (_, mut app, ctx) = tree(|_, _| {}); diff --git a/src/app.rs b/src/app.rs index 78236a0b..af3ef3bf 100644 --- a/src/app.rs +++ b/src/app.rs @@ -446,6 +446,8 @@ pub struct App { pub tl_heard: Option<(anicraft_engine::doc::LayerId, u32)>, /// The arrows moved the active layer: its row takes keyboard focus when drawn. pub tl_refocus: bool, + /// The menu bar from the keyboard: Alt, F10 and the arrows (ADR 0064). + pub menu_keys: menus::MenuKeys, /// The start screen, while it is up (ADR 0059). pub start: Option, /// Files dragged over and dropped onto the window (ADR 0059). @@ -621,6 +623,7 @@ impl App { stage_nav: Default::default(), tl_heard: None, tl_refocus: false, + menu_keys: Default::default(), start: None, drop: Default::default(), thumbs: Default::default(), @@ -2112,6 +2115,12 @@ impl App { if self.modal_open() || self.key_capture.is_some() { return; } + // Alt+letter opens a menu (ADR 0064), before the tool letters: egui would match those + // with Alt held too. + let alt_bound = |k: Key| self.shortcuts.iter().any(|(m, key, _)| *key == k && m.alt && !m.ctrl && !m.command && !m.shift); + let mut menu_keys = std::mem::take(&mut self.menu_keys); + menu_keys.access_key(ctx, alt_bound); + self.menu_keys = menu_keys; // Palette, shortcut sheet, preferences and quit work even while a text field has focus. // Preferences: Ctrl+U (the shortcut Animate users know) and Ctrl/⌘+, (platform norm). let (palette, sheet, prefs_key, quit) = ctx.input_mut(|i| { diff --git a/src/guidelines_tests.rs b/src/guidelines_tests.rs index f350867c..b1028ee2 100644 --- a/src/guidelines_tests.rs +++ b/src/guidelines_tests.rs @@ -1,6 +1,6 @@ //! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values. -const SOURCES: [(&str, &str); 26] = [ +const SOURCES: [(&str, &str); 27] = [ ("drop.rs", include_str!("drop.rs")), ("recent.rs", include_str!("recent.rs")), ("start.rs", include_str!("start.rs")), @@ -18,6 +18,7 @@ const SOURCES: [(&str, &str); 26] = [ ("menus.rs", include_str!("menus.rs")), ("panels.rs", include_str!("panels.rs")), ("stage.rs", include_str!("stage.rs")), + ("stage_a11y.rs", include_str!("stage_a11y.rs")), ("timeline.rs", include_str!("timeline.rs")), ("widthtool.rs", include_str!("widthtool.rs")), ("motion_editor.rs", include_str!("motion_editor.rs")), diff --git a/src/menus.rs b/src/menus.rs index 15cc5806..a1965ef1 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -11,6 +11,12 @@ pub(crate) const TOP_MENUS: [&str; 9] = [tr_noop!("File"), tr_noop!("Edit"), tr_ pub fn bar(app: &mut App, ui: &mut egui::Ui) { let cmds = commands(); + let ctx = ui.ctx().clone(); + let labels = top_labels(); + let keys = access_keys(&labels.iter().map(String::as_str).collect::>()); + app.menu_keys.before(&ctx); + let underline = app.menu_keys.show_keys; + let mut tops = Vec::with_capacity(TOP_MENUS.len()); egui::MenuBar::new().ui(ui, |ui| { // macOS: leave room for the traffic lights over the unified title bar. ui.add_space(platform::menu_inset()); @@ -32,13 +38,380 @@ pub fn bar(app: &mut App, ui: &mut egui::Ui) { }); } // Windows and Linux: no name before the menus; the window title already shows it. - for top in TOP_MENUS { - ui.menu_button(crate::i18n::t(top), |ui| { + for ((top, label), key) in TOP_MENUS.into_iter().zip(&labels).zip(&keys) { + let title = if underline { egui::WidgetText::from(crate::theme::access_key_label(label, key.map(|(i, _)| i))) } else { egui::WidgetText::from(label.as_str()) }; + let r = ui.menu_button(title, |ui| { ui.set_min_width(230.0); + // The menu's own area, which egui leaves anonymous: a menu named by its title. + ui.ctx().accesskit_node_builder(ui.layer_id().id.with("move"), |n| { + n.set_role(egui::accesskit::Role::Menu); + n.set_label(label.as_str()); + }); menu_contents(app, ui, top, &cmds); }); + if let Some((_, c)) = key + && MenuKeys::available() + { + let k = platform::shortcut_label(&format!("Alt+{c}")); + ctx.accesskit_node_builder(r.response.id, |n| n.set_access_key(k)); + } + tops.push(r.response.id); } }); + app.menu_keys.after(&ctx, tops); +} + +/// The top menus' titles in the interface language. +fn top_labels() -> Vec { + TOP_MENUS.iter().map(|t| crate::i18n::t(t).to_string()).collect() +} + +/// Each top menu's access key: `(character index, letter)`, the first letter of its title that +/// no menu before it took (word starts first); ASCII letters only, so a title without one has +/// none. +pub fn access_keys(labels: &[&str]) -> Vec> { + let mut used: Vec = Vec::new(); + labels + .iter() + .map(|l| { + let chars: Vec = l.chars().collect(); + let starts = (0..chars.len()).filter(|&i| i == 0 || chars.get(i - 1).is_some_and(|c| c.is_whitespace())); + let pick = starts.chain(0..chars.len()).find_map(|i| { + let c = chars.get(i)?.to_ascii_uppercase(); + (c.is_ascii_alphabetic() && !used.contains(&c)).then_some((i, c)) + }); + if let Some((_, c)) = pick { + used.push(c); + } + pick + }) + .collect() +} + +/// The menu bar from the keyboard (ADR 0064), as on Windows and Linux: Alt (pressed and let go +/// alone) or F10 focuses the first menu; Left and Right move between menus; Down, Enter or Space +/// opens one and goes to its first item; Up and Down move through items (wrapping), Right opens +/// a submenu (or goes on to the next menu), Left comes back; Esc closes the menu, and again +/// gives the keyboard back to where it was. Alt+letter opens a menu directly; while Alt is held, +/// or the bar has the keyboard, each title shows its letter underlined. macOS keeps its own +/// conventions (the command palette, ⌘K, reaches every menu command): nothing here runs there. +#[derive(Default)] +pub struct MenuKeys { + /// The top menu buttons, as drawn last. + tops: Vec, + alt_down: bool, + /// Alt went down with nothing else since: letting go of it is a tap. + alt_clean: bool, + /// Where the keyboard was before the bar took it. + back: Option, + /// The bar or a menu had the keyboard last frame. + engaged: bool, + focus_top: Option, + /// A menu or submenu just opened from the keyboard: its first item takes focus once drawn + /// (within the frames left). + into: Option<(egui::LayerId, u8)>, + /// Submenus entered from the keyboard: their buttons and layers, outermost first. + stack: Vec<(egui::Id, egui::LayerId)>, + /// Underline the access keys. + pub show_keys: bool, +} + +enum At { + Top(usize), + Item(egui::Id, egui::LayerId), + Elsewhere, +} + +impl MenuKeys { + /// Alt and F10 work on Windows, Linux and the web, not on a Mac (in a browser or not). + pub fn available() -> bool { + platform::menu_bar_keys() + } + + fn popup(top: egui::Id) -> egui::Id { + top.with("popup") + } + + fn layer(top: egui::Id) -> egui::LayerId { + egui::LayerId::new(egui::Order::Foreground, Self::popup(top)) + } + + fn open_top(&self, ctx: &egui::Context) -> Option { + self.tops.iter().position(|t| egui::Popup::is_id_open(ctx, Self::popup(*t))) + } + + /// Where the keyboard is: on a top menu, on an item of an open menu, or elsewhere. + fn at(&self, ctx: &egui::Context) -> At { + let Some(f) = ctx.memory(|m| m.focused()) else { return At::Elsewhere }; + if let Some(i) = self.tops.iter().position(|t| *t == f) { + return At::Top(i); + } + match ctx.read_response(f) { + Some(r) if self.open_top(ctx).is_some() && r.layer_id.order == egui::Order::Foreground => At::Item(f, r.layer_id), + _ => At::Elsewhere, + } + } + + /// The top menu buttons (tests). + #[cfg(test)] + pub fn top_ids(&self) -> &[egui::Id] { + &self.tops + } + + /// The open menu's items, top to bottom (tests). + #[cfg(test)] + pub fn open_items(&self, ctx: &egui::Context) -> Vec { + self.open_top(ctx).and_then(|i| self.tops.get(i)).map(|t| Self::items(ctx, Self::layer(*t), false)).unwrap_or_default() + } + + /// Whether the menu bar or one of its menus has the keyboard. + pub fn engaged(&self, ctx: &egui::Context) -> bool { + !matches!(self.at(ctx), At::Elsewhere) + } + + /// The items of a menu drawn in `layer`, top to bottom: from this pass (`now`) or the last. + fn items(ctx: &egui::Context, layer: egui::LayerId, now: bool) -> Vec { + let mut v: Vec<(f32, f32, egui::Id)> = ctx.viewport(|vp| { + let pass = if now { &vp.this_pass } else { &vp.prev_pass }; + // (Not the menu's own area, which egui makes clickable.) + let area = layer.id.with("move"); + pass.widgets.get_layer(layer).filter(|w| w.enabled && w.sense.is_focusable() && w.id != area).map(|w| (w.rect.top(), w.rect.left(), w.id)).collect() + }); + v.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))); + v.into_iter().map(|(_, _, id)| id).collect() + } + + fn step(&self, i: usize, forward: bool) -> usize { + let n = self.tops.len().max(1); + if forward { (i + 1) % n } else { (i + n - 1) % n } + } + + fn open(&mut self, ctx: &egui::Context, i: usize) { + if let Some(t) = self.tops.get(i).copied() { + egui::Popup::open_id(ctx, Self::popup(t)); + self.into = Some((Self::layer(t), 3)); + self.focus_top = Some(i); + self.stack.clear(); + } + } + + fn leave(&mut self, ctx: &egui::Context) { + egui::Popup::close_all(ctx); + self.stack.clear(); + self.into = None; + self.focus_top = None; + let back = self.back.take(); + ctx.memory_mut(|m| match back { + Some(id) => m.request_focus(id), + None => { + if let Some(f) = m.focused() { + m.surrender_focus(f); + } + } + }); + } + + /// Alt pressed and let go with nothing else in between. + fn alt_tap(&mut self, ctx: &egui::Context) -> bool { + let (alt, other, focused) = ctx.input(|i| { + let events = i.events.iter().any(|e| matches!(e, egui::Event::Key { .. } | egui::Event::PointerButton { .. } | egui::Event::Text(_) | egui::Event::MouseWheel { .. })); + (i.modifiers.alt, events || i.modifiers.ctrl || i.modifiers.shift || i.modifiers.mac_cmd, i.focused) + }); + let mut tap = false; + if alt && focused { + if !self.alt_down { + self.alt_clean = true; + } + if other { + self.alt_clean = false; + } + } else { + tap = self.alt_down && self.alt_clean && !other && focused; + self.alt_clean = false; + } + self.alt_down = alt && focused; + tap + } + + /// Alt+letter opens that menu, unless the shortcut table has the key (the user bound it). + /// Runs before the shortcuts: egui matches a plain "H" with Alt held too. + pub fn access_key(&mut self, ctx: &egui::Context, bound: impl Fn(egui::Key) -> bool) { + if !Self::available() || !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, modifiers, .. } if modifiers.alt))) { + return; + } + let labels = top_labels(); + for (i, k) in access_keys(&labels.iter().map(String::as_str).collect::>()).into_iter().enumerate() { + let Some(key) = k.and_then(|(_, c)| egui::Key::from_name(&c.to_string())) else { continue }; + if !bound(key) && ctx.input_mut(|inp| inp.consume_key(egui::Modifiers::ALT, key)) { + if !self.engaged(ctx) { + self.back = ctx.memory(|m| m.focused()); + } + self.open(ctx, i); + return; + } + } + } + + /// The keyboard left the bar: a chosen item closed its menu (the keyboard goes back where it + /// was), or a click went elsewhere (it stays there). + fn settle(&mut self, ctx: &egui::Context, engaged: bool) { + if self.engaged && !engaged && self.into.is_none() && self.focus_top.is_none() { + // (A closed menu's item keeps the focus until the end of the frame.) + let lost = ctx.memory(|m| m.focused()).is_none_or(|f| ctx.read_response(f).is_none_or(|r| r.layer_id.order == egui::Order::Foreground)); + if let Some(id) = self.back.take().filter(|_| lost) { + ctx.memory_mut(|m| m.request_focus(id)); + } + self.stack.clear(); + self.engaged = false; + } + } + + /// Before the bar draws: the keys that reach it. + fn before(&mut self, ctx: &egui::Context) { + use egui::{Key, Modifiers}; + if !Self::available() { + self.show_keys = false; + return; + } + let at = self.at(ctx); + let engaged = !matches!(at, At::Elsewhere); + self.settle(ctx, engaged); + let tap = self.alt_tap(ctx); + let f10 = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::F10)); + if tap || f10 { + if engaged || self.open_top(ctx).is_some() { + self.leave(ctx); + } else { + self.back = ctx.memory(|m| m.focused()); + self.focus_top = Some(0); + } + return; + } + let pressed = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); + let enter = || ctx.input(|i| i.key_pressed(Key::Enter) || i.key_pressed(Key::Space)); + match at { + At::Top(i) => { + let open = self.open_top(ctx).is_some(); + let side = if pressed(Key::ArrowLeft) { + Some(false) + } else if pressed(Key::ArrowRight) { + Some(true) + } else { + None + }; + if let Some(forward) = side { + let j = self.step(i, forward); + if open { + self.open(ctx, j); + } else { + self.focus_top = Some(j); + } + } else if pressed(Key::ArrowDown) { + self.open(ctx, i); + } else if pressed(Key::ArrowUp) { + // (Nothing above the bar.) + } else if pressed(Key::Escape) { + if open { + egui::Popup::close_all(ctx); + } else { + self.leave(ctx); + } + } else if enter() + && let Some(t) = self.tops.get(i) + { + // egui presses the button, which opens its menu: its first item comes next. + self.into = Some((Self::layer(*t), 3)); + } + } + At::Item(f, layer) => { + let items = Self::items(ctx, layer, false); + let pos = items.iter().position(|x| *x == f).unwrap_or(0); + let n = items.len().max(1); + let open = self.open_top(ctx).unwrap_or(0); + let focus = |id: Option<&egui::Id>| { + if let Some(id) = id.copied() { + ctx.memory_mut(|m| m.request_focus(id)); + } + }; + let sub = egui::LayerId::new(egui::Order::Foreground, f.with("submenu")); + if pressed(Key::ArrowDown) { + focus(items.get((pos + 1) % n)); + } else if pressed(Key::ArrowUp) { + focus(items.get((pos + n - 1) % n)); + } else if pressed(Key::ArrowRight) { + // On an open submenu's button: into it. Elsewhere: the next menu. + let inside = Self::items(ctx, sub, false); + if inside.is_empty() { + let j = self.step(open, true); + self.open(ctx, j); + } else { + self.stack.push((f, sub)); + focus(inside.first()); + } + } else if pressed(Key::ArrowLeft) { + match self.stack.last().copied() { + Some((button, l)) if l == layer => { + self.stack.pop(); + focus(Some(&button)); + } + _ => { + let j = self.step(open, false); + self.open(ctx, j); + } + } + } else if pressed(Key::Escape) { + egui::Popup::close_all(ctx); + self.stack.clear(); + self.focus_top = Some(open); + } else if enter() { + // Pressing a submenu's button opens it: go in once it shows. + self.into = Some((sub, 3)); + } + } + At::Elsewhere => {} + } + } + + /// After the bar drew: focus moves, and the arrows and Esc stay with the bar. + fn after(&mut self, ctx: &egui::Context, tops: Vec) { + self.tops = tops; + if !Self::available() { + return; + } + if let Some(i) = self.focus_top.take() + && let Some(t) = self.tops.get(i).copied() + && ctx.memory(|m| m.focused()) != Some(t) + { + ctx.memory_mut(|m| m.request_focus(t)); + } + if let Some((layer, left)) = self.into.take() { + match Self::items(ctx, layer, true).first().copied() { + Some(first) => { + let top_layer = self.tops.iter().any(|t| Self::layer(*t) == layer); + if !top_layer && let Some(button) = ctx.memory(|m| m.focused()) { + // A submenu opened with Enter: Left comes back to its button. + self.stack.push((button, layer)); + } + ctx.memory_mut(|m| m.request_focus(first)); + } + None if left > 1 => self.into = Some((layer, left - 1)), + None => {} + } + ctx.request_repaint(); + } + let engaged = self.engaged(ctx); + self.settle(ctx, engaged); + if engaged && let Some(f) = ctx.memory(|m| m.focused()) { + let filter = egui::EventFilter { tab: false, horizontal_arrows: true, vertical_arrows: true, escape: true }; + ctx.memory_mut(|m| m.set_focus_lock_filter(f, filter)); + } + self.engaged = engaged || self.focus_top.is_some() || self.into.is_some(); + let show = engaged || ctx.input(|i| i.modifiers.alt && !i.modifiers.ctrl); + if show != self.show_keys { + ctx.request_repaint(); + } + self.show_keys = show; + } } fn enabled(app: &App, id: &str) -> bool { @@ -98,11 +471,21 @@ fn item(app: &mut App, ui: &mut egui::Ui, spec: &CommandSpec) { None => r, }; if r.clicked() { + pressed(ui); app.invoke(spec.id); ui.close(); } } +/// An item was pressed: the Enter or Space that pressed it from the keyboard is used up, so it +/// doesn't also reach what the item opens (the command palette's field, a dialog's button). +fn pressed(ui: &egui::Ui) { + ui.input_mut(|i| { + i.consume_key(egui::Modifiers::NONE, egui::Key::Enter); + i.consume_key(egui::Modifiers::NONE, egui::Key::Space); + }); +} + /// A registry command as a menu item (label and shortcut from the registry); used by context /// menus so every surface shows the same names and keys. pub fn cmd_item(app: &mut App, ui: &mut egui::Ui, id: &str) { @@ -117,6 +500,7 @@ pub fn check_item(ui: &mut egui::Ui, label: &str, checked: bool, enabled: bool) let label = if checked { format!("✔ {label}") } else { format!(" {label}") }; let clicked = ui.add_enabled(enabled, egui::Button::new(label)).clicked(); if clicked { + pressed(ui); ui.close(); } clicked @@ -131,6 +515,7 @@ fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option }; let clicked = ui.add(egui::Button::new(label_text).shortcut_text(text(Type::Key, platform::shortcut_label(shortcut)))).clicked(); if clicked { + pressed(ui); ui.close(); } clicked diff --git a/src/platform.rs b/src/platform.rs index 4ea33149..de4833fc 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -69,6 +69,12 @@ fn keys_os() -> Os { if OS == Os::Web && WEB_ON_MAC.load(Ordering::Relaxed) { Os::Mac } else { OS } } +/// Whether Alt and F10 reach the menu bar (ADR 0064): on Windows, Linux and the web, as their +/// applications do, but not on a Mac (in a browser or not), whose menu conventions differ. +pub fn menu_bar_keys() -> bool { + keys_os() != Os::Mac +} + pub fn set_mac_glyphs(available: bool) { MAC_GLYPHS.store(available, Ordering::Relaxed); } diff --git a/src/theme.rs b/src/theme.rs index d85351b3..ac8c45a7 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -478,6 +478,25 @@ pub fn color(t: Type) -> Color32 { } } +/// A menu title with its access key underlined (ADR 0064), as Windows and Linux show it while +/// Alt is held or the menu bar has the keyboard. `at`: the character (not byte) to underline. +pub fn access_key_label(s: &str, at: Option) -> egui::text::LayoutJob { + let mut job = egui::text::LayoutJob::default(); + let plain = egui::TextFormat { font_id: font(Type::Body), color: Color32::PLACEHOLDER, ..Default::default() }; + let marked = egui::TextFormat { underline: Stroke::new(1.0, T.text), ..plain.clone() }; + let cut = |n: usize| s.char_indices().nth(n).map_or(s.len(), |(b, _)| b); + match at { + Some(i) if i < s.chars().count() => { + let (a, b) = (cut(i), cut(i + 1)); + job.append(s.get(..a).unwrap_or(""), 0.0, plain.clone()); + job.append(s.get(a..b).unwrap_or(""), 0.0, marked); + job.append(s.get(b..).unwrap_or(""), 0.0, plain); + } + _ => job.append(s, 0.0, plain), + } + job +} + /// Text in a role: font, size, colour (and weight for titles and headings). pub fn text(t: Type, s: impl Into) -> egui::RichText { let rt = egui::RichText::new(s).font(font(t)).color(color(t)); From 880bf0ea3ce8dc2bb7dbcde0cea3f017be4e225a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:59:40 -0700 Subject: [PATCH 069/192] =?UTF-8?q?feat(a11y):=20follow=20the=20system's?= =?UTF-8?q?=20contrast=20setting;=20Preferences=20=E2=80=BA=20Theme=20?= =?UTF-8?q?=E2=80=BA=20Follow=20system=20(M8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 1 + Cargo.toml | 7 ++++- src/a11y.rs | 22 ++++++++++++-- src/app.rs | 80 +++++++++++++++++++++++++++++++++++++++++++++++-- src/dialogs.rs | 19 +++++++++++- src/platform.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++ src/prefs.rs | 45 +++++++++++++++++++++++++++- 7 files changed, 238 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6c8a91ff..84701058 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -239,6 +239,7 @@ dependencies = [ "wasm-bindgen-futures", "web-sys", "web-time", + "winreg", "winresource", ] diff --git a/Cargo.toml b/Cargo.toml index 505b6d07..11446bca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -124,6 +124,11 @@ cpal = { version = "0.18", optional = true } [target.'cfg(target_os = "macos")'.dependencies] fmv-macos-events = "=0.1.0" +# The system's high-contrast setting (ADR 0064): one registry value. MIT, already in the tree +# through craft-update. +[target.'cfg(windows)'.dependencies] +winreg = "0.55" + # The web build (ADR 0036, docs/web.md). The window draws with WebGL2 (glow): every current # browser has it, the stage is drawn on the CPU there, and leaving wgpu out keeps the download # smaller. The browser glue is wasm-bindgen's (MIT OR Apache-2.0), already under eframe's web @@ -135,7 +140,7 @@ wasm-bindgen-futures = "0.4" js-sys = "0.3" # In the browser the page's language (navigator.languages) is the system's. sys-locale = { version = "0.3", features = ["js"] } -web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] } +web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "MediaQueryList", "Navigator", "Storage", "Url", "Window", "console"] } [build-dependencies] # Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets. diff --git a/src/a11y.rs b/src/a11y.rs index b238987c..945e5ba7 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -622,10 +622,9 @@ mod tests { frame(&ctx, &mut app, input(1.0)); assert_eq!(focused(&ctx), Some(tops[0]), "an Alt tap focuses File"); key(&ctx, &mut app, Key::Escape, M::NONE); - // Alt+H opens Help from the stage; an item chosen with Enter runs and the keyboard goes - // back to the stage. + // Alt+H opens Help from the stage; an item chosen with Enter runs (and its Enter goes no + // further than the item). focus_stage(&ctx, &mut app); - let stage = focused(&ctx); key(&ctx, &mut app, Key::H, M::ALT); frame(&ctx, &mut app, input(1.0)); let help = crate::menus::TOP_MENUS.iter().position(|t| *t == "Help").unwrap_or(0); @@ -658,6 +657,23 @@ mod tests { assert_eq!(app.tool, crate::app::Tool::Select, "Alt+V opened View; it didn't pick the Selection tool's V"); } + #[test] + fn the_palette_follows_the_system_contrast_setting_in_the_same_frame() { + let (_, mut app, ctx) = tree(|_, _| {}); + app.set_system_contrast(&ctx, Some(true)); + let followed = crate::theme::palette(); + app.set_system_contrast(&ctx, Some(false)); + let back = crate::theme::palette(); + // Chosen by hand: the system's setting no longer changes it. + let mut p = app.prefs.clone(); + p.theme_follows_system = Some(false); + app.set_prefs(&ctx, p); + app.set_system_contrast(&ctx, Some(true)); + let manual = crate::theme::palette(); + crate::theme::apply_palette(&egui::Context::default(), crate::theme::Palette::Graphite); + assert_eq!((followed, back, manual), (crate::theme::Palette::HighContrast, crate::theme::Palette::Graphite, crate::theme::Palette::Graphite)); + } + #[test] fn ctrl_f6_moves_focus_through_the_panels_and_back() { let (_, mut app, ctx) = tree(|_, _| {}); diff --git a/src/app.rs b/src/app.rs index af3ef3bf..32a84290 100644 --- a/src/app.rs +++ b/src/app.rs @@ -448,6 +448,12 @@ pub struct App { pub tl_refocus: bool, /// The menu bar from the keyboard: Alt, F10 and the arrows (ADR 0064). pub menu_keys: menus::MenuKeys, + /// What the system last said about contrast (ADR 0064): `None` until it has, or if it + /// can't. Screenshot runs never ask, so they look the same everywhere. + pub system_contrast: Option, + /// The system's contrast setting being read off the UI thread, and when it last was. + contrast_probe: Option>>, + contrast_asked: Option, /// The start screen, while it is up (ADR 0059). pub start: Option, /// Files dragged over and dropped onto the window (ADR 0059). @@ -456,6 +462,9 @@ pub struct App { pub thumbs: crate::recent::Thumbs, } +/// How often (seconds) the system's contrast setting is asked again (ADR 0064). +const SYSTEM_CONTRAST_EVERY: f64 = 4.0; + /// How finished this version is, shown next to the version number (docs/release.md). English: /// translated where the interface shows it (`--version` prints it as is). pub const RELEASE_STAGE: &str = tr_noop!("early alpha"); @@ -624,6 +633,9 @@ impl App { tl_heard: None, tl_refocus: false, menu_keys: Default::default(), + system_contrast: None, + contrast_probe: None, + contrast_asked: None, start: None, drop: Default::default(), thumbs: Default::default(), @@ -718,7 +730,7 @@ impl App { crate::i18n::set_language(&self.prefs.language); ctx.request_repaint(); ctx.set_zoom_factor(self.prefs.ui_scale); - theme::apply_palette(ctx, self.prefs.theme); + theme::apply_palette(ctx, self.prefs.palette(self.system_contrast)); crate::onion::refresh_colors(self); self.keymap = keymap::Keymap::new(&self.prefs.shortcuts); self.shortcuts = self.keymap.table(); @@ -758,7 +770,10 @@ impl App { return; } let mut p = self.prefs.clone(); - p.theme = theme.unwrap_or(p.theme); + if let Some(t) = theme { + p.theme = t; + p.theme_follows_system = Some(false); + } p.ui_scale = scale.unwrap_or(p.ui_scale); self.prefs = p.sanitized(); self.apply_prefs(ctx); @@ -784,6 +799,66 @@ impl App { } } + /// Follows the system's contrast setting (ADR 0064): asks it on a worker now and then (at + /// start, every few seconds, and when the window comes back to the front), and switches the + /// palette in the same frame the answer changes, while Preferences says "Follow system". + fn follow_system_contrast(&mut self, ctx: &egui::Context) { + if self.shot.is_some() { + return; + } + if let Some(rx) = &self.contrast_probe { + match rx.try_recv() { + Ok(v) => { + self.contrast_probe = None; + self.set_system_contrast(ctx, v); + } + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => self.contrast_probe = None, + } + } + let (now, came_back) = ctx.input(|i| (i.time, i.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(true))))); + let due = self.contrast_asked.is_none_or(|t| now - t >= SYSTEM_CONTRAST_EVERY || came_back); + if !due { + return; + } + self.contrast_asked = Some(now); + let (tx, rx) = std::sync::mpsc::channel(); + #[cfg(not(target_arch = "wasm32"))] + let started = { + let ctx2 = ctx.clone(); + std::thread::Builder::new() + .name("anicraft-contrast".into()) + .spawn(move || { + let _ = tx.send(platform::system_high_contrast()); + ctx2.request_repaint(); + }) + .is_ok() + }; + // (No threads in a browser: the media query answers at once.) + #[cfg(target_arch = "wasm32")] + let started = tx.send(platform::system_high_contrast()).is_ok(); + if started { + self.contrast_probe = Some(rx); + } + // Ask again later even if nothing else happens. + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SYSTEM_CONTRAST_EVERY)); + } + + /// What the system says about contrast: the palette follows at once, if it follows. + pub fn set_system_contrast(&mut self, ctx: &egui::Context, v: Option) { + if v == self.system_contrast { + return; + } + let before = self.prefs.palette(self.system_contrast); + self.system_contrast = v; + let after = self.prefs.palette(v); + if after != before { + theme::apply_palette(ctx, after); + crate::onion::refresh_colors(self); + ctx.request_repaint(); + } + } + /// Starts scanning installed fonts on a background thread (once). pub fn scan_system_fonts(&mut self) { if self.system_fonts.is_some() || self.fonts_rx.is_some() { @@ -2498,6 +2573,7 @@ impl App { } self.handle_screenshot(&ctx); self.poll_font_scan(&ctx); + self.follow_system_contrast(&ctx); if let Some(p) = platform::picked_file() { self.open_picked(p); } diff --git a/src/dialogs.rs b/src/dialogs.rs index 254c7d50..c2ca405e 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -417,11 +417,28 @@ fn preferences(app: &mut App, ctx: &egui::Context) { ui.add_space(4.0); form_row(ui, LW, tr!("Theme"), |ui| { ui.vertical(|ui| { + // Follow system (ADR 0064), then each palette by hand. + let was = if p.follows_system() { None } else { Some(p.theme) }; + let mut choice = was; + crate::theme::radio_value(ui, &mut choice, None, text(Type::Body, tr!("Follow system"))); + let says = match app.system_contrast { + Some(true) => tr!("High contrast while the system asks for more contrast (it does now), graphite otherwise."), + Some(false) => tr!("High contrast while the system asks for more contrast (it doesn't now), graphite otherwise."), + None => tr!("High contrast while the system asks for more contrast, graphite otherwise. This system doesn't say, so it is graphite."), + }; + form_note(ui, toggle_indent, text(Type::Caption, says)); + ui.add_space(2.0); for (palette, name, tip) in crate::theme::Palette::ALL { - crate::theme::radio_value(ui, &mut p.theme, palette, text(Type::Body, crate::i18n::t(name))); + crate::theme::radio_value(ui, &mut choice, Some(palette), text(Type::Body, crate::i18n::t(name))); form_note(ui, toggle_indent, text(Type::Caption, crate::i18n::t(tip))); ui.add_space(2.0); } + if choice != was { + p.theme_follows_system = Some(choice.is_none()); + if let Some(t) = choice { + p.theme = t; + } + } }); }); ui.add_space(4.0); diff --git a/src/platform.rs b/src/platform.rs index de4833fc..53db3e8b 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -53,6 +53,64 @@ pub fn system_locale() -> Option { sys_locale::get_locale().filter(|l| !l.is_empty() && l.len() <= 64) } +/// Whether the system asks for more contrast (ADR 0064): Windows' contrast themes (high +/// contrast), macOS' Increase Contrast, the desktop portal's contrast setting on Linux (GNOME's +/// High Contrast where there is no portal), the browser's `prefers-contrast: more`. `None`: +/// this system doesn't say. Can block for a moment (it may ask another process): call it off +/// the UI thread. +pub fn system_high_contrast() -> Option { + #[cfg(windows)] + { + // HIGHCONTRAST's flags as the system keeps them; bit 0 is HCF_HIGHCONTRASTON. + let key = winreg::RegKey::predef(winreg::enums::HKEY_CURRENT_USER).open_subkey(r"Control Panel\Accessibility\HighContrast").ok()?; // i18n-exempt: a registry path + let flags: String = key.get_value("Flags").ok()?; // i18n-exempt: a registry value name + flags.trim().parse::().ok().map(|f| f & 1 == 1) + } + #[cfg(target_os = "macos")] + { + // Missing until the user first changes it: off. + let out = std::process::Command::new("defaults").args(["read", "com.apple.universalaccess", "increaseContrast"]).output().ok()?; // i18n-exempt: a command line + Some(String::from_utf8_lossy(&out.stdout).trim() == "1") + } + #[cfg(target_arch = "wasm32")] + { + web_sys::window()?.match_media("(prefers-contrast: more)").ok()??.matches().into() // i18n-exempt: a media query + } + #[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))] + { + portal_contrast().or_else(gnome_high_contrast) + } +} + +/// The XDG desktop portal's `org.freedesktop.appearance contrast` (1: high), through `gdbus`. +#[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))] +fn portal_contrast() -> Option { + let out = std::process::Command::new("gdbus") // i18n-exempt: a command line + .args(["call", "--session", "--timeout", "1", "--dest", "org.freedesktop.portal.Desktop", "--object-path", "/org/freedesktop/portal/desktop", "--method", "org.freedesktop.portal.Settings.ReadOne", "org.freedesktop.appearance", "contrast"]) // i18n-exempt: a command line + .output() + .ok() + .filter(|o| o.status.success())?; + parse_portal_uint(&String::from_utf8_lossy(&out.stdout)).map(|v| v == 1) +} + +/// GNOME's own switch, for desktops without the portal setting. +#[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))] +fn gnome_high_contrast() -> Option { + let out = std::process::Command::new("gsettings").args(["get", "org.gnome.desktop.a11y.interface", "high-contrast"]).output().ok().filter(|o| o.status.success())?; // i18n-exempt: a command line + match String::from_utf8_lossy(&out.stdout).trim() { + "true" => Some(true), + "false" => Some(false), + _ => None, + } +} + +/// The number in a `gdbus` reply such as `(<>,)` or `(,)`. +#[cfg_attr(any(windows, target_os = "macos", target_arch = "wasm32"), allow(dead_code))] +fn parse_portal_uint(reply: &str) -> Option { + let rest = reply.split("uint32").nth(1)?; + rest.trim_start().split(|c: char| !c.is_ascii_digit()).next()?.parse().ok() +} + /// Whether the active fonts can draw ⌘ ⇧ ⌥ ⌃ (set once fonts are installed). static MAC_GLYPHS: AtomicBool = AtomicBool::new(false); @@ -604,6 +662,20 @@ mod tests { assert!(is_system_argument("-psn_0_8194") && !is_system_argument("walk.anicraft")); } + #[test] + fn portal_replies_parse() { + assert_eq!(parse_portal_uint("(<>,)"), Some(1)); + assert_eq!(parse_portal_uint("(,) +"), Some(0)); + assert_eq!(parse_portal_uint("Error: no such key"), None); + } + + #[test] + fn the_system_contrast_setting_can_be_read_without_panicking() { + // Whatever this machine says (or doesn't), asking never fails loudly. + let _ = system_high_contrast(); + } + #[test] fn renderer_override() { assert_eq!(forced_renderer(Some("gl")), Some(eframe::Renderer::Glow)); diff --git a/src/prefs.rs b/src/prefs.rs index 2df1ac48..1b6a1cd8 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -63,8 +63,13 @@ pub struct Prefs { pub language: String, pub ui_font: FontChoice, pub data_font: FontChoice, - /// Graphite or high contrast (ADR 0022). + /// Graphite or high contrast (ADR 0022), when chosen by hand. pub theme: crate::theme::Palette, + /// Follow the system's contrast setting (ADR 0064): high contrast while the system asks for + /// more contrast, graphite otherwise. `None` (files from before): it follows, unless the + /// file chose high contrast. + #[serde(skip_serializing_if = "Option::is_none")] + pub theme_follows_system: Option, /// Interface scale (1.0 = 100%). pub ui_scale: f32, pub render_mode: RenderMode, @@ -150,6 +155,7 @@ impl Default for Prefs { ui_font: FontChoice::Bundled, data_font: FontChoice::Bundled, theme: crate::theme::Palette::Graphite, + theme_follows_system: None, ui_scale: 1.0, render_mode: RenderMode::Auto, stage_renderer: StageRenderer::Gpu, @@ -192,6 +198,21 @@ pub const SCALE_RANGE: std::ops::RangeInclusive = 0.75..=2.0; pub const GAP_RANGE: std::ops::RangeInclusive = 0.0..=48.0; impl Prefs { + /// Whether the theme follows the system's contrast setting ("Follow system", the default). + pub fn follows_system(&self) -> bool { + self.theme_follows_system.unwrap_or(self.theme != crate::theme::Palette::HighContrast) + } + + /// The palette to draw with, given what the system says about contrast (`None`: it + /// doesn't say, or hasn't yet). + pub fn palette(&self, system_high_contrast: Option) -> crate::theme::Palette { + match (self.follows_system(), system_high_contrast) { + (true, Some(true)) => crate::theme::Palette::HighContrast, + (true, _) => crate::theme::Palette::Graphite, + (false, _) => self.theme, + } + } + pub fn sanitized(mut self) -> Prefs { self.ui_scale = if self.ui_scale.is_finite() { self.ui_scale.clamp(*SCALE_RANGE.start(), *SCALE_RANGE.end()) } else { 1.0 }; self.timeline_start_gap = if self.timeline_start_gap.is_finite() { self.timeline_start_gap.clamp(*GAP_RANGE.start(), *GAP_RANGE.end()) } else { 0.0 }; @@ -281,6 +302,28 @@ impl SystemFonts { mod tests { use super::*; + #[test] + fn the_theme_follows_the_system_unless_one_was_chosen() { + use crate::theme::Palette; + // New installs, and files from before ADR 0064 that kept the default, follow the system. + for p in [Prefs::default(), Prefs::from_json(r#"{"theme": "Graphite"}"#)] { + assert!(p.follows_system()); + assert_eq!(p.palette(Some(true)), Palette::HighContrast); + assert_eq!(p.palette(Some(false)), Palette::Graphite); + assert_eq!(p.palette(None), Palette::Graphite, "a system that doesn't say: graphite"); + } + // A file that chose high contrast keeps it whatever the system says. + let hc = Prefs::from_json(r#"{"theme": "HighContrast"}"#); + assert!(!hc.follows_system()); + assert_eq!(hc.palette(Some(false)), Palette::HighContrast); + // Graphite chosen by hand stays graphite; the choice survives a round trip. + let manual = Prefs { theme_follows_system: Some(false), ..Prefs::default() }; + assert_eq!(manual.palette(Some(true)), Palette::Graphite); + let back = Prefs::from_json(&serde_json::to_string(&manual).unwrap_or_default()); + assert_eq!(back.theme_follows_system, Some(false)); + assert!(!serde_json::to_string(&Prefs::default()).unwrap_or_default().contains("theme_follows_system"), "nothing new written until chosen"); + } + #[test] fn system_font_scan_is_safe_and_loads_a_face() { // Machine-dependent (CI containers may have no fonts); must never panic. From af2f8141a445a046c4860ae0fe3a16d3eb801c7b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:00:40 -0700 Subject: [PATCH 070/192] fix(a11y): clippy (M8) --- src/a11y.rs | 2 +- src/stage.rs | 2 +- src/timeline.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/a11y.rs b/src/a11y.rs index 945e5ba7..a1fdf087 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -449,7 +449,7 @@ mod tests { } } - fn node<'a>(t: &'a TreeUpdate, id: egui::Id) -> Option<&'a Node> { + fn node(t: &TreeUpdate, id: egui::Id) -> Option<&Node> { t.nodes.iter().find(|(n, _)| *n == id.accesskit_id()).map(|(_, n)| n) } diff --git a/src/stage.rs b/src/stage.rs index 50f3ede8..92674571 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -1146,7 +1146,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { }; crate::a11y::surface(ui, &resp, &name); // Its elements, one by one, while it has the keyboard (ADR 0064). - crate::stage_a11y::show(app, ui, &resp, |p| to_screen(p)); + crate::stage_a11y::show(app, ui, &resp, to_screen); } // ----- raw shapes (ADR 0031, 0041) ---------------------------------------------------------------- diff --git a/src/timeline.rs b/src/timeline.rs index 81c18280..3ad31531 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -853,7 +853,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { a11y::control(ui, &cr, WidgetType::Button, &tr!("Frames of {name}", name = layer.name), None); if is_active { // Its keyframes and spans, one by one, for screen readers (ADR 0064). - frame_nodes(app, ui, &cr, layer, |f| x_of(f), y); + frame_nodes(app, ui, &cr, layer, x_of, y); } let shift = ui.input(|inp| inp.modifiers.shift); if cr.clicked() || cr.drag_started() || cr.secondary_clicked() { From ddc6ea856ef297c26521156e1c8d670d2a5f45da Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:01:53 -0700 Subject: [PATCH 071/192] feat(shell): screenshot states for the stage and menu bar keyboard (M8) --- src/app.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/app.rs b/src/app.rs index 32a84290..48b73428 100644 --- a/src/app.rs +++ b/src/app.rs @@ -451,6 +451,9 @@ pub struct App { /// What the system last said about contrast (ADR 0064): `None` until it has, or if it /// can't. Screenshot runs never ask, so they look the same everywhere. pub system_contrast: Option, + /// Keys to press, a few frames apart (screenshots of keyboard states). + pub key_script: std::collections::VecDeque<(Key, Modifiers)>, + key_script_wait: u8, /// The system's contrast setting being read off the UI thread, and when it last was. contrast_probe: Option>>, contrast_asked: Option, @@ -634,6 +637,8 @@ impl App { tl_refocus: false, menu_keys: Default::default(), system_contrast: None, + key_script: Default::default(), + key_script_wait: 0, contrast_probe: None, contrast_asked: None, start: None, @@ -799,6 +804,28 @@ impl App { } } + /// Presses `keys` once the window has settled, a few frames apart. + fn script_keys(&mut self, keys: impl IntoIterator) { + self.key_script.extend(keys); + self.key_script_wait = 10; + } + + /// The next scripted key press, once the frames before it have settled. + fn press_scripted_key(&mut self, ctx: &egui::Context) { + if self.key_script.is_empty() { + return; + } + ctx.request_repaint(); + if self.key_script_wait > 0 { + self.key_script_wait -= 1; + return; + } + if let Some((key, modifiers)) = self.key_script.pop_front() { + ctx.input_mut(|i| i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers })); + self.key_script_wait = 3; + } + } + /// Follows the system's contrast setting (ADR 0064): asks it on a worker now and then (at /// start, every few seconds, and when the window comes back to the front), and switches the /// palette in the same frame the answer changes, while Preferences says "Follow system". @@ -907,7 +934,11 @@ impl App { } pub fn open_panel(&mut self, which: Option<&str>) { + use egui::{Key as K, Modifiers as M}; match which { + // Keyboard states for screenshots (ADR 0064): keys pressed a few frames apart. + Some("stagekeys") => self.script_keys([(K::F6, M::COMMAND), (K::Tab, M::NONE), (K::Space, M::NONE), (K::ArrowRight, M::NONE)]), + Some("menukeys") => self.script_keys([(K::F10, M::NONE), (K::ArrowRight, M::NONE), (K::ArrowDown, M::NONE), (K::ArrowDown, M::NONE)]), Some("palette") => self.palette = Some(dialogs::Palette { query: "key".into(), selected: 0 }), Some("shortcuts") => self.show_shortcuts = true, Some("lastscene") => { @@ -2587,6 +2618,7 @@ impl App { platform::set_mac_glyphs(ok); self.glyph_check = false; } + self.press_scripted_key(&ctx); self.handle_shortcuts(&ctx); timeline::announce(self, &ctx); // Switching away from a path tool keeps its work: a Pen path in progress is finished. From 6876a837eedc382752505aca06d3e2768c6aae64 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:03:22 -0700 Subject: [PATCH 072/192] docs: ADR 0064 accessibility second pass, guide, roadmap, changelog (M8) --- CHANGELOG.md | 25 ++++ docs/accessibility.md | 105 ++++++++++++--- docs/adr/0064-accessibility-second-pass.md | 146 +++++++++++++++++++++ docs/adr/README.md | 1 - docs/legal/compliance.md | 7 + docs/roadmap.md | 6 +- 6 files changed, 267 insertions(+), 23 deletions(-) create mode 100644 docs/adr/0064-accessibility-second-pass.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e517961..becdc221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ ## Unreleased +* **Accessibility, second pass** (ADR 0064, M8). + * **Select on the stage from the keyboard.** With the stage focused (Ctrl+F6), Tab goes to + its elements, and a ring shows the focused one on the artwork. + * Tab, Shift+Tab and the arrows move between elements. + * Enter or Space selects one; Shift+Enter or Shift+Space adds it to the selection or + takes it out. + * Esc goes back to the stage. + * **Screen readers hear what is on the stage.** While the stage has focus, its elements are + a list ("Rectangle", "Text: Hello", "ball · Graphic: Ball"), each with its layer, place, + size, on-screen bounds and whether it is selected. + * **The active layer's frames are a list too.** Each item reads "Frames 1–24: keyframe · + motion tween · label “walk”", and activating one moves the playhead there. + * **The timeline from the keyboard.** On the focused timeline, the arrows move the playhead + and the active layer, and each move is announced. + * **The menu bar from the keyboard** on Windows and Linux. + * Press and let go of Alt, or press F10. Then the arrows, Enter and Esc work as in other + applications. + * Alt+F, Alt+E and the rest open a menu directly. While Alt is held, each title shows its + letter underlined. + * **Follow system** is the new default theme. AniCraft switches to high contrast while + Windows uses a contrast theme, macOS has Increase Contrast on, the Linux desktop asks for + high contrast, or the browser prefers more contrast. Choosing Graphite or High contrast + keeps that palette. + * Headless: `element.select` takes `toggle`. + * **Test Movie in its own window, and opening documents on macOS** (ADR 0062, M8). * **Control › Test Movie** (Ctrl+Enter) now opens in a **window of its own** on the desktop, as in Animate. It is sized to the stage at 100 % (smaller if that wouldn't fit the diff --git a/docs/accessibility.md b/docs/accessibility.md index 456e0d23..e1e7ead3 100644 --- a/docs/accessibility.md +++ b/docs/accessibility.md @@ -2,7 +2,8 @@ AniCraft aims to be usable with the keyboard alone, with a screen reader, at large interface sizes and in high contrast. This page says what works today, how to check it, and what doesn't -work yet. Design decisions are in ADR 0022; the rules for contributors are in +work yet. Design decisions are in ADR 0022 (first pass) and ADR 0064 (stage elements, timeline +frames, the keyboard menu bar, the system's contrast setting); the rules for contributors are in `docs/ui-guidelines.md`. ## What is supported @@ -29,9 +30,32 @@ work yet. Design decisions are in ADR 0022; the rules for contributors are in the selected items at the centre of the view on the active layer (sounds on its keyframe at the playhead), as dragging them onto the stage does; F2 renames and Delete deletes. Place on Stage is also a button under the list and in each row's right-click menu. -* Frames are reached with `,` and `.` (previous and next), Home and End, F5/F6/F7 to insert, - and Shift+`,`/`.`; layers with the layer rows (Tab from the timeline anchor) and the - Up/Down buttons under them. +* **Select on the stage without a pointer** (ADR 0064). With the stage focused (Ctrl+F6), + press **Tab**: focus goes to the first selected element, or the first one, and a ring shows + it on the artwork. + * **Tab**, **Shift+Tab** and the **arrow keys** move between elements, layers top to bottom + and each front to back, wrapping. + * **Enter** or **Space** selects the focused element alone. **Shift+Enter** or + **Shift+Space** adds it to the selection or takes it out, as Shift-click does. + * The other shortcuts keep working: select with Space, then Delete, F8 (Convert to Symbol) + or Ctrl+D. + * **Esc** goes back to the stage itself, where the arrows nudge the selection again. + * Elements on locked layers are listed, but can't be selected. +* **The timeline from the keyboard.** With the timeline focused, **Left** and **Right** move + the playhead a frame, and **Up** and **Down** move to the layer above or below. + * Each move is announced: "Frame 12 · Ball · Frames 1–24: keyframe · motion tween". + * `,` `.` Home and End go to frames as always, F5/F6/F7 insert, and Shift+`,`/`.` extend. +* **The menu bar from the keyboard** (Windows and Linux, ADR 0064). Press **Alt** alone (press + and let go) or **F10**: File gets focus, and each menu title shows its letter underlined. + * **Left** and **Right** move between menus. **Down**, **Enter** or **Space** opens one. + * **Up** and **Down** move through its items, wrapping. + * **Right** goes into a submenu (or on to the next menu), and **Left** comes back. + * **Enter** runs an item, and the keyboard returns to where it was. + * **Esc** closes the menu; press it again (or Alt, or F10) to leave the bar. + * **Alt+letter** opens a menu directly: Alt+F File, Alt+E Edit, Alt+V View, Alt+I Insert, + Alt+M Modify, Alt+C Commands, Alt+O Control, Alt+W Window, Alt+H Help. An Alt+letter you + have bound in the shortcut sheet keeps your binding. + * On macOS the menus stay as they are: ⌘K (the command palette) reaches every menu command. ### Screen readers @@ -45,14 +69,44 @@ UI Automation on Windows, NSAccessibility on macOS, AT-SPI on Linux. * Number fields say what they are and what they hold: "Position X, spin button, 120". * The stage is announced as a canvas with the tool in hand, the frame and the selection: "Stage · Selection tool · frame 12 · 1 element selected". +* **While the stage has focus, its elements are a list** under it: "5 elements on frame 1". + * Each element is an option with a name: the instance name first, then what it is, such as + "Rectangle", "Oval", "Polygon", "Line", "Bitmap", "Text: Hello" or "ball · Graphic: Ball". + * Its description gives the layer, place and size ("Layer Hills · x 120, y 80 · 200 × 40 + px"). + * It says whether it is selected, and its position in the list. Its bounds are where it is + on screen. + * A reader's "click" (activate) on an option selects it. + * A frame with more than 2,000 elements lists the first 2,000, and says how many more there + are. +* **The active layer's frames are a list** under its frame grid, one item per keyframe span: + "Frames 1–24: keyframe · motion tween · label “walk” · sound · actions". + * The span under the playhead is marked selected. + * Activating a span moves the playhead to it. * The status bar is a live region: after an action a screen reader reads its result ("Deleted layer — Ctrl+Z to undo") without moving focus. -* A test (`a11y::tests`) runs the whole interface without a window in 23 states and fails if - any interactive control has no name or no role. +* A test (`a11y::tests`) runs the whole interface without a window and fails if any + interactive control has no name or no role. It covers 23 states, plus the stage list with an + element focused, the timeline's span list and an open menu. Other tests drive the keyboard: + stage selection, the timeline arrows, and the menu bar. ### High contrast -Preferences › Appearance › Theme › **High contrast**: white text on black, yellow for focus, +Preferences › Appearance › Theme › **Follow system** is the default: AniCraft switches to high +contrast while the system asks for more contrast, and back when it doesn't, within a few +seconds. It reads: + +* **Windows:** a contrast theme (Settings › Accessibility › Contrast themes, or Left Alt + + Left Shift + Print Screen). +* **macOS:** Increase Contrast (System Settings › Accessibility › Display). +* **Linux:** the desktop's contrast setting, through the XDG desktop portal, or GNOME's High + Contrast where there is no portal. +* **The web:** the browser's `prefers-contrast: more`. + +The note under the choice says what the system says now. Choosing **Graphite** or **High +contrast** keeps that palette whatever the system says. + +Theme › **High contrast**: white text on black, yellow for focus, selection and the active tool, a visible outline on every button and field, brighter timeline blocks with black marks. Every text colour reads at 7:1 or more on its background (WCAG AAA); controls, focus rings and timeline blocks at 3:1 or more. The default Graphite theme meets WCAG @@ -74,7 +128,9 @@ Run from a checkout: cargo run # as you use it cargo run -- --theme high-contrast --scale 200 # high contrast at 200 %, not saved cargo run -- --theme high-contrast --open prefs --screenshot shots/hc.png -cargo test --bin anicraft a11y # the AccessKit audit and panel focus +cargo test --bin anicraft a11y # the AccessKit audit, panel focus, stage, timeline and menu keys +cargo run -- --open stagekeys --screenshot shots/s.png # an element focused on the stage +cargo run -- --open menukeys --screenshot shots/m.png # the menu bar from the keyboard cargo test --bin anicraft palette # the contrast checks ``` @@ -88,7 +144,11 @@ cargo test --bin anicraft palette # the contrast checks 3. **Tab** through the tools and Properties: every control is read with a name, number fields with their value ("Stage width, 1280 px"). 4. Press **Delete** with something selected: Narrator reads the status message. -5. Accessibility Insights for Windows (free, from Microsoft) shows the UI Automation tree if you +5. On the stage, press **Tab**: Narrator reads the element ("star · Graphic: Star, not + selected, 2 of 5"). Use the arrows to move, and **Space** to select. Narrator's scan mode + (Caps Lock+Space) also walks the list. +6. Press **Alt**, then the arrows: Narrator reads each menu and item. +7. Accessibility Insights for Windows (free, from Microsoft) shows the UI Automation tree if you want to inspect names and roles directly. ### macOS: VoiceOver @@ -107,20 +167,23 @@ cargo test --bin anicraft palette # the contrast checks ## Known gaps -* **Elements on the stage are not exposed one by one.** A screen reader hears the stage, the - tool and how many elements are selected, not each shape. Select with the keyboard - (Ctrl+A, Tab through Properties) and edit values in Properties. -* **Single frames are not exposed.** Each layer's frames are one clickable area; the keyboard - route is `,` `.` Home End and F5/F6/F7 at the playhead. +* **Stage elements are named by what they look like.** A shape is a rectangle, oval, polygon + or line only when its outline is one; a brush or pencil stroke is a "Shape". Give an + instance a name in Properties to hear it. Moving or transforming the focused element uses + the nudge keys (after Esc) or the Properties fields. +* **Only the active layer's frames are listed**, as spans (a keyframe and the frames after + it), not one item per frame. Up and Down on the focused timeline change the active layer. +* **Menus have no per-item letters.** Inside an open menu, use the arrows. While a menu is + open, single-letter tool shortcuts still work. * **The Motion Editor graph is pointer only.** Its values are editable in the property list beside it, and so are the eases (the Ease menu). * **Adding a point in Edit Envelope takes a click.** Each point is named for screen readers ("Point 2 of 4, Left channel: 80 % at 0.400 s"), and the selected point's time and levels are fields that take typed values; the Effect menu sets any preset from the keyboard. -* **The system's high-contrast or "increase contrast" setting is not followed automatically.** - Choose High contrast in Preferences. -* **The menu bar can't be opened from the keyboard** (no Alt or F10 yet). Every menu command is - in the command palette (Ctrl+K) and most have a shortcut. +* **The system's light or dark setting is not followed**: AniCraft has one standard (dark) + palette. Windows' white contrast themes get the black high-contrast palette. +* **macOS has no keyboard route to AniCraft's own menu row**: use ⌘K, which lists every menu + command. * **Tab order across panels** follows how the window is built (menu bar, edit bar, tools, right-hand panels, timeline, stage). Ctrl+F6 gives the panel order listed above. * **Scroll bars inside lists** have no name (egui doesn't offer one). @@ -129,4 +192,8 @@ cargo test --bin anicraft palette # the contrast checks pseudo-locale too and fails on a name that stayed English. Document text (layer and symbol names) is announced as written. * **Manual passes with Narrator, VoiceOver and Orca** are still to do on real machines for each - platform. The automated audit checks names and roles, not how each reader phrases them. + platform. **What has been verified (ADR 0064):** the AccessKit tree AniCraft publishes, by + automated tests on Windows: names, roles, selected states, bounds, focus, the list box under + the stage canvas and the span list under the frame grid. Screenshots show the keyboard + states. No live screen reader has been run against the second pass yet, so how each reader + phrases the stage options and announces the status bar is still to check. diff --git a/docs/adr/0064-accessibility-second-pass.md b/docs/adr/0064-accessibility-second-pass.md new file mode 100644 index 00000000..edaddf6d --- /dev/null +++ b/docs/adr/0064-accessibility-second-pass.md @@ -0,0 +1,146 @@ +# ADR 0064: Accessibility, second pass: stage elements, timeline frames, keyboard menu bar, system contrast + +* Status: accepted (2026-11-11) +* Relates to: ADR 0022 (first pass), ADR 0004 (no modal interruptions), ADR 0006 (platforms), + ADR 0040 (translatable interface), ADR 0044 (selection across layers); `docs/accessibility.md` + is the user guide + +## Context + +The first pass (ADR 0022) named every control, added Ctrl+F6 panel focus, a high-contrast +palette and a 200 % scale. Its known gaps were the parts of the window where the work happens, +plus two platform conventions: + +* The stage was one canvas node. A screen reader heard "Stage · Selection tool · frame 12 · + 1 element selected" and nothing about what was on it. Selecting anything took a pointer + (or Ctrl+A). +* Each layer's frames were one clickable area: a screen reader couldn't hear what was at a + frame (keyframe, tween, label), and the arrow keys on the focused timeline nudged artwork. +* The menu bar couldn't be reached from the keyboard. On Windows and Linux Alt and F10 do that + in every application. +* Windows' contrast themes, macOS' Increase Contrast and the GNOME/portal contrast switch were + ignored. High contrast had to be chosen in Preferences. + +egui 0.36 publishes its widgets through AccessKit but has no API for nodes that aren't +widgets, and no keyboard navigation of its menu bar. + +## Decisions + +1. **Stage elements are a list box under the stage, only while the stage has the keyboard** + (`src/stage_a11y.rs`). The canvas node gets one child, a multi-select `ListBox` "12 elements + on frame 4". It has one `ListBoxOption` per element on the current frame: layers top to + bottom, each front to back (picking order). An option carries: + * its **name**: the instance name first (document text), then what the element is. + Shapes are named by their outline: "Rectangle" (axis-aligned four sides, or rounded), + "Oval" (four curves), "Polygon", "Line", else "Shape". The rest are "Bitmap", + "Movie clip: Ball", "Text: Hello…" (one line, 80 characters). + * its **description**: the layer, position and size in pixels. + * its **bounds** on screen, so the reader's highlight lands on the artwork. + * **selected**, its place in the set, **disabled** on a locked layer, and a Click action. + + The tree stays the size it was while the stage isn't focused, and the rest of the window + keeps its tab order. **At most 2,000 options**; beyond that one label says how many more + there are and how to reach them (picking, Select All, Find). Options are egui widgets with a + zero-size interaction rect: keyboard focus stops with the right AccessKit focus, but no + pointer area over the canvas. Their parent is set with `UiBuilder::accessibility_parent`. + The bounds of all elements come from one pass over the display list, not one per element. + Rejected: options for every element at all times (thousands of nodes and Tab stops in every + frame), and patching AccessKit's tree after egui (no API; it would fight egui's ids). + +2. **Keyboard selection on the stage.** Tab on the focused stage goes to the first selected + element, or the first one. From there Tab, Shift+Tab and the arrows move between elements, + wrapping (a composite widget, like a grid). Enter or Space selects the element alone; + Shift+Enter or Shift+Space adds it to the selection or takes it out (Shift-click). Esc goes + back to the stage itself, where the arrows nudge again, and Ctrl+F6 leaves the panel. + * The focused element has a 2 px accent ring on the artwork, and the status bar (a live + region) says its name and state. + * Selection runs `element.select`, the command a click, the CLI and MCP use. It gains + `toggle?: bool` for Shift+Space. A locked layer's element is listed but refuses, as a + click does. + * Other shortcuts keep working on a focused element: select with Space, then Delete, + F8 or Ctrl+D. + +3. **Timeline frames.** The active layer's frame grid gets a `List` of its keyframe spans. + Each item says "Frames 1–24: keyframe · motion tween · label “walk” · sound · actions" + (blank keyframe; classic, shape, motion or broken tween). The span under the playhead is + selected, and a reader's Click moves the playhead there. At most 1,000 items, then a + summary. On the **focused timeline** Left/Right move the playhead a frame and Up/Down move + the active layer (keyboard focus follows the row), instead of nudging artwork. Moves made + while the timeline has the keyboard (arrows, `,` `.` Home End) are announced through the + status bar: "Frame 12 · Ball · Frames 1–24: keyframe · motion tween". Nothing is announced + during playback. + +4. **The menu bar from the keyboard, Windows and Linux conventions** (`menus::MenuKeys`). + * **Alt** pressed and let go alone, or **F10**, focuses File; again (or Esc) gives the + keyboard back to where it was. + * Left/Right move between menus (and keep a menu open if one was). Down, Enter or Space + opens one and focuses its first enabled item. + * In a menu, Up/Down wrap. Right enters an open submenu, or else goes on to the next menu. + Left comes back out of a submenu, or else goes to the previous menu. + * Esc closes the menu, back on its title. An item chosen with Enter runs, and the keyboard + returns to where it was before the bar. + * **Alt+letter** opens a menu directly, and titles show their letter underlined while Alt + is held or the bar has the keyboard. The letters are computed from the titles in the + interface language: the first free letter, word starts first, ASCII only (File, Edit, + View, Insert, Modify, Commands, c**O**ntrol, Window, Help). They are also each title's + AccessKit access key. + * Access keys run **before** the shortcut table because egui matches a plain "V" with Alt + held. An Alt+letter the user has bound in the shortcut editor keeps its binding. + * The Enter or Space that pressed an item is used up there, so it can't also press a button + in what the item opens (the command palette's field). + * Navigation reads each menu's focusable widgets from egui's widget list for that popup + layer, sorted top to bottom. egui's own arrow navigation is geometric across the whole + window and would leave the menu. + * **macOS is unchanged.** Its conventions differ (Ctrl+F2 reaches the system menu bar, and + Option isn't a menu key), and ⌘K reaches every menu command. `platform::menu_bar_keys` + makes the choice, and a browser on a Mac follows the Mac. + +5. **Following the system's contrast setting** (`platform::system_high_contrast`), each system + read without `unsafe`: + * Windows: the `HighContrast` `Flags` value in the user's registry (`HCF_HIGHCONTRASTON`), + through `winreg` (MIT, already in the tree through craft-update). + * macOS: `defaults read com.apple.universalaccess increaseContrast`. + * Linux and the BSDs: the XDG desktop portal's `org.freedesktop.appearance contrast` through + `gdbus` (1 s timeout), else GNOME's `high-contrast` through `gsettings`. + * The web: `matchMedia("(prefers-contrast: more)")`. + + The app asks on a worker thread at start, every 4 s and when the window comes back to the + front. A changed answer switches the palette in the same frame. Screenshot runs and tests + never ask, so they look the same on every machine. + + **Preferences › Theme** gains **Follow system**, the default: high contrast while the system + asks for it, graphite otherwise. Its note says what the system says now. The choice is + `theme_follows_system: Option`. `None` (every file from before) follows the system, + unless the file had chosen high contrast, which keeps it. `--theme` turns following off for + the run. + + Rejected: a D-Bus crate for Linux (another dependency tree for one value; `zbus` is in the + tree only async, under AccessKit), and a native API on each system (each needs `unsafe`). + +6. **Light themes are not followed.** AniCraft has one standard palette (dark, as Animate's + default). The system's light/dark setting has nothing to map to until a light palette + exists. Windows' white contrast themes get our black high-contrast palette. + +## Consequences + +* The AccessKit audit now also covers the stage list with an element focused, the active + layer's span list, and an open menu (egui's menu area node is named as a `Menu`, which the + audit had never seen open). +* New tests drive the window headless: + * keyboard selection on the stage (Tab, arrows, wrap, Space, Shift+Space, Enter, a locked + element, Esc); + * timeline arrows with announcements and layer focus; + * menu bar navigation (F10, an Alt tap, Alt+letter, arrows, wrap, Esc twice, Enter running + an item and focus returning); + * the palette following the system; + * old preference files. +* `--open stagekeys` and `--open menukeys` replay key presses for screenshots of those states. +* Not in this slice: + * element names beyond the outline heuristic (a pencil stroke is a "Shape"); + * moving or transforming the focused element with keys other than nudge (Free Transform's + fields do that); + * per-item access keys inside menus; + * a light palette; + * Windows' white contrast theme as a white palette; + * live screen-reader passes on real machines (`docs/accessibility.md` says what was + verified). diff --git a/docs/adr/README.md b/docs/adr/README.md index 7bdad542..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0064 | m8/accessibility-2 | Accessibility, second pass: stage elements, frames, keyboard menu bar, system contrast | diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index b48b98f6..9bda10f2 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -76,6 +76,13 @@ Apache-2.0) and `aho-corasick` (Unlicense OR MIT), built with only the `std`, `p `unicode-case` and `unicode-perl` features. They match Find and Replace's patterns in linear time with size limits. No new licence. +### System contrast setting (2026-11-11, ADR 0064) + +New direct dependency on Windows only: `winreg` 0.55 (MIT, crates.io), already in the tree +through `craft-update`. It reads one registry value, the high-contrast flag. The web build +turns on web-sys's `MediaQueryList` feature (same crate, same licence). macOS and Linux ask +system tools (`defaults`, `gdbus`, `gsettings`), so nothing is linked. No new licence. + ### Interface languages (2026-11-10, ADR 0040) New crate: `sys-locale` 0.3 (MIT OR Apache-2.0, crates.io), which reads the system's interface diff --git a/docs/roadmap.md b/docs/roadmap.md index c3221216..c846bc4b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -24,7 +24,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. | | Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. **Opening documents on macOS** (ADR 0062): a double-click in Finder, a drop on the Dock icon or Open With opens the document, at launch or while running (the open-documents Apple Event through `platform.rs`, by `fmv-macos-events`, so no `unsafe` of ours), through the unsaved-changes guard; the Dock's Quit asks to save too; Windows and Linux command-line hand-over covered by a test. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, AppImage desktop integration, portable mode, store listings, video export inside the Flatpak. | | Languages | **First slice** (ADR 0040, `docs/localisation.md`): every shell string goes through `tr!`/`trn!` (keyed by its English; placeholders; CLDR plurals for whole numbers), menus translate the registry's labels when drawn (ids, CLI, MCP and the file format stay English), screen-reader names too. Catalogs are craft-i18n's TSV, read by our own parser and embedded from `CRAFT_I18N_DIR` (fallback app → shared → base language → English). Preferences › Appearance › Language (system language by default) and `--lang`. A **pseudo-locale** (`--lang pseudo`: accented, a third longer, bracketed) tests layout; checked by a source guideline test and a pseudo-locale accessibility audit; `scripts/i18n-extract.sh` writes the translators' template and per-locale coverage. Not yet: a real language (craft-i18n has no `anicraft.tsv` yet), engine messages and confirmation bodies (`@msg`), default document names, right to left (needs bidi and shaping in egui upstream), CJK and Georgian (need a font), shaped scripts. | -| Accessibility | **First pass** (ADR 0022, `docs/accessibility.md`): AccessKit (via eframe) gives every control a name and role, checked by a headless test that walks the tree in 23 interface states (custom-painted tools, layer rows and toggles, icon buttons, Library rows, every Properties field, the Motion Editor, every dialog; the stage is a named canvas; the status bar a polite live region). **Ctrl+F6 / Ctrl+Shift+F6** move focus between Stage, Timeline, Properties, Library and Tools (rebindable); focused controls keep Enter/Space/arrows while other shortcuts still work; pointer-only surfaces are not Tab stops. **High contrast** palette (Preferences › Theme) from the same roles, text ≥ 7:1, controls and focus ≥ 3:1; both palettes checked by the contrast test (the graphite one now meets AA everywhere). **Interface scale** 75–200 % holds up (stage refits, tools and timeline header scroll, status truncates). Not yet: stage elements and single frames exposed one by one, keyboard menu bar, following the OS contrast setting, manual passes with Narrator, VoiceOver and Orca. | +| Accessibility | **First pass** (ADR 0022, `docs/accessibility.md`): AccessKit (via eframe) gives every control a name and role, checked by a headless test that walks the tree in 23 interface states (custom-painted tools, layer rows and toggles, icon buttons, Library rows, every Properties field, the Motion Editor, every dialog; the stage is a named canvas; the status bar a polite live region). **Ctrl+F6 / Ctrl+Shift+F6** move focus between Stage, Timeline, Properties, Library and Tools (rebindable); focused controls keep Enter/Space/arrows while other shortcuts still work; pointer-only surfaces are not Tab stops. **High contrast** palette (Preferences › Theme) from the same roles, text ≥ 7:1, controls and focus ≥ 3:1; both palettes checked by the contrast test (the graphite one now meets AA everywhere). **Interface scale** 75–200 % holds up (stage refits, tools and timeline header scroll, status truncates). **Second pass** (ADR 0064): while the stage has focus its elements are a list box under the canvas (name from the instance name and outline or kind, layer, place and size, bounds, selected; 2,000 at most plus a summary); **Tab, arrows, Enter/Space and Shift+Space select on the stage** through `element.select` (new `toggle`); the active layer's keyframe spans are a list (frames, tween, label, sound, actions; activating one moves the playhead); on the focused timeline the arrows move the playhead and layer, announced through the status bar; **the menu bar from the keyboard** on Windows and Linux (Alt tap or F10, arrows, submenus, Esc, Alt+letter with underlined access keys); **Follow system** (the default theme) switches to high contrast with Windows' contrast themes, macOS' Increase Contrast, the portal/GNOME contrast setting and `prefers-contrast` in browsers. Not yet: names beyond the outline heuristic, per-item menu letters, a light palette, a keyboard route to the menu row on macOS (⌘K covers it), manual passes with Narrator, VoiceOver and Orca. | | Stage rendering & build | **Tiled stage** (ADR 0007): 512 px cached tiles, batched per frame with one scene evaluation per frame, look-ahead ring and playback prefetch, scaled older tiles instead of blank areas, pixel-aligned (no seams). **Space-biased build**: debug build 6.9 GB → 1.04 GB, fresh build 44 s, edit rebuild 4–6 s (`docs/development.md`). | | Scale & performance | Pulled forward from M2: persistent document with snapshot undo (memory-budgeted history, save-point dirty tracking, History panel), background render worker with frame cache and playback look-ahead, band-parallel renderer with culling, compact streaming file format v2, `anicraft-cli bench`. Measured numbers are in `docs/performance.md`. Memory, sharing, file-size and culling budgets are a test on every PR; timing budgets are `anicraft-cli bench --check yes` (all met; the 1080p render is 15.3–15.8 ms against 16.7 ms). | @@ -40,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | -| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. | +| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), next: live screen-reader passes on each platform, a light palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. | ## Releases @@ -61,7 +61,7 @@ titled with its milestone. | M5 | Audio layers: import, waveform, playback sync | timeline, layers | | M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | -| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); next: the accessibility follow-ups | `.anicraft` format, session, AccessKit in eframe | +| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and ActionScript (on M6's plug-in host). From 6d1cf79be16a691152aeab5354779a78b7a35875 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:03:33 -0700 Subject: [PATCH 073/192] docs: credit the WAI-ARIA patterns and the portal spec (M8) --- ATTRIBUTION.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index aab3a22c..ffe2106c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -82,6 +82,8 @@ OR Apache-2.0) is noted in the table. | Tile binning on the GPU: count, prefix sum, scatter, per-tile lists | `crates/gpu/src/gpu_binning.rs`, `crates/gpu/src/bin.wgsl`, `crates/gpu/src/scan.wgsl` | The binning stages described for *Vello* (above) and Patrick Walton's *Pathfinder* (, Apache-2.0 OR MIT) design posts; the work-efficient scan of G. E. Blelloch, *Prefix Sums and Their Applications* (CMU-CS-90-190, 1990) | Our own arrangement (one invocation per row of a fill's tiles, no atomics) written from the public descriptions; no code or shaders copied (ADR 0048). | | Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). | | Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), , Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. | +| Stage elements as a multi-select list box; menu bar keyboard model (Alt/F10, arrows, access keys) | `src/stage_a11y.rs`, `src/menus.rs` | W3C *WAI-ARIA Authoring Practices Guide*, Listbox and Menubar patterns, (W3C Software and Document License) | Keyboard behaviour learned from the published patterns; no code or text copied. | +| Reading the desktop's contrast setting | `src/platform.rs` | *XDG Desktop Portal*, Settings interface, `org.freedesktop.appearance` `contrast` key, (LGPL documentation, read only; nothing bundled or linked) | One value read through the `gdbus` tool. | | Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). | | Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | | | Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. | From 3650437454d324263b0bb1797bbf6eb2c012ff15 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 18:48:58 -0700 Subject: [PATCH 074/192] docs: reserve ADR 0065 for templates and timeline drops (M8) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..20f3fcf8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0065 | (M8 templates and drops) | Templates, SVG into the Library, drops on the timeline | From bc574026c99c9072949ef479b61f5cd6dc8d2e87 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:00:11 -0700 Subject: [PATCH 075/192] feat(engine): built-in and user templates, SVG into the Library as a graphic symbol, drops on a layer's frame (M8) --- crates/doc/src/lib.rs | 1 + crates/doc/src/templates.rs | 314 +++++++++++++++++++++++ crates/engine/src/cmds_drop.rs | 105 +++++++- crates/engine/src/cmds_file.rs | 83 +++++- crates/engine/src/cmds_sound.rs | 8 +- crates/engine/src/cmds_template.rs | 195 ++++++++++++++ crates/engine/src/confirm.rs | 16 +- crates/engine/src/drop_tests.rs | 21 +- crates/engine/src/lib.rs | 5 + crates/engine/src/template_tests.rs | 153 +++++++++++ crates/engine/src/timeline_drop_tests.rs | 163 ++++++++++++ 11 files changed, 1043 insertions(+), 21 deletions(-) create mode 100644 crates/doc/src/templates.rs create mode 100644 crates/engine/src/cmds_template.rs create mode 100644 crates/engine/src/template_tests.rs create mode 100644 crates/engine/src/timeline_drop_tests.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d0a08c6c..5e72f8e8 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -24,6 +24,7 @@ pub mod stroke_style; pub mod player; pub mod publish; pub mod sample; +pub mod templates; pub mod sound; pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; diff --git a/crates/doc/src/templates.rs b/crates/doc/src/templates.rs new file mode 100644 index 00000000..e40e4d67 --- /dev/null +++ b/crates/doc/src/templates.rs @@ -0,0 +1,314 @@ +//! The templates AniCraft ships with (ADR 0065): small documents built by code, so nothing +//! binary is committed and every line of them is original work. Each sets up a stage size and +//! frame rate, named layers ready to draw on, and guides on a locked guide layer (shown while +//! editing, never in output). They open as new, untitled documents (`file.new_from_template`). + +use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_geom::{Affine, Path, Vec2}; +use std::sync::Arc; + +/// A built-in template: its id (for commands), name and category (English; the shell +/// translates them where they are drawn), what it is for, and how it is built. +pub struct Template { + pub id: &'static str, + pub name: &'static str, + pub category: &'static str, + pub description: &'static str, + pub build: fn() -> Document, +} + +/// Every built-in template, in the order the start screen shows them. +pub static TEMPLATES: [Template; 6] = [ + Template { id: "banner-728x90", name: "Leaderboard banner", category: "Advertising", description: "A 728 × 90 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer", build: banner_728x90 }, + Template { id: "banner-300x250", name: "Rectangle banner", category: "Advertising", description: "A 300 × 250 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer", build: banner_300x250 }, + Template { id: "social-square", name: "Social square", category: "Social", description: "A 1080 × 1080 post at 30 fps, 15 seconds long, with a safe margin and thirds on a guide layer", build: social_square }, + Template { id: "storyboard", name: "Storyboard 16:9", category: "Storyboard", description: "Six 2-second panels at 1920 × 1080, labelled Panel 1 to 6, with action- and title-safe areas", build: storyboard }, + Template { id: "character-turnaround", name: "Character turnaround", category: "Character", description: "Front, three-quarter, side and back views side by side, on head-height guides eight heads tall", build: turnaround }, + Template { id: "lip-sync", name: "Lip-sync mouth chart", category: "Character", description: "A Mouth graphic symbol with ten labelled mouth shapes to redraw, placed on a face guide", build: lip_sync }, +]; + +/// The built-in template with this id. +pub fn find(id: &str) -> Option<&'static Template> { + TEMPLATES.iter().find(|t| t.id == id) +} + +/// The colour guides are drawn in (the guide layer's colour too, so the stage shows them alike). +const GUIDE: u32 = 0x4fa3ff; +/// A second, quieter guide colour for secondary lines. +const GUIDE_SOFT: u32 = 0x9cc8ff; + +fn blank(width: u32, height: u32, fps: f32) -> Document { + let mut d = Document { stage: Stage { width, height, fps, background: Rgba::WHITE }, ..Document::default() }; + d.timeline_mut(0).layers.clear(); + d +} + +fn element(d: &mut Document, name: &str, transform: Affine, shape: Shape) -> Arc { + Arc::new(Element { id: ElementId(d.alloc_id()), name: name.into(), transform, color: ColorEffect::default(), kind: ElementKind::Shape(shape) }) +} + +/// A stroked line from `a` to `b`. +fn line(d: &mut Document, name: &str, a: (f32, f32), b: (f32, f32), color: u32, width: f32) -> Arc { + let mut p = Path::new(); + p.move_to(Vec2::new(a.0, a.1)).line_to(Vec2::new(b.0, b.1)); + element(d, name, Affine::IDENTITY, Shape { path: Arc::new(p), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false }) +} + +/// A stroked rectangle outline. +fn outline(d: &mut Document, name: &str, x: f32, y: f32, w: f32, h: f32, color: u32, width: f32) -> Arc { + element(d, name, Affine::IDENTITY, Shape { path: Arc::new(Path::rect(x, y, w, h)), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false }) +} + +/// A layer holding `elements` in one keyframe `frames` long. +fn layer(d: &mut Document, name: &str, kind: LayerKind, color: u32, frames: u32, elements: Vec>) -> Arc { + let mut l = Layer::new(LayerId(d.alloc_id()), name); + l.kind = kind; + l.color = Rgba::hex(color); + // Guides stay put while drawing over them. + l.locked = kind == LayerKind::Guide; + let mut k = Keyframe::new(0, frames.max(1)); + k.elements = elements; + l.keyframes = vec![Arc::new(k)]; + Arc::new(l) +} + +/// Drawing layers, empty, top first. +fn drawing_layers(d: &mut Document, names: &[&str], frames: u32) -> Vec> { + let palette = [0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; + names.iter().enumerate().map(|(i, n)| layer(d, n, LayerKind::Normal, palette[i % palette.len()], frames, Vec::new())).collect() +} + +/// A banner: the safe area (inset by a tenth of the short edge) and the edge on a guide layer, +/// layers for the call to action, text and artwork, and a soft background. +fn banner(width: u32, height: u32) -> Document { + const FRAMES: u32 = 24 * 15; + let mut d = blank(width, height, 24.0); + let (w, h) = (width as f32, height as f32); + let m = (w.min(h) * 0.1).round(); + let guides = vec![outline(&mut d, "Safe area", m, m, w - 2.0 * m, h - 2.0 * m, GUIDE, 1.0), outline(&mut d, "Edge", 0.5, 0.5, w - 1.0, h - 1.0, GUIDE_SOFT, 1.0)]; + let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)]; + layers.extend(drawing_layers(&mut d, &["Call to action", "Text", "Artwork"], FRAMES)); + let bg = element(&mut d, "background", Affine::IDENTITY, Shape::filled(Path::rect(0.0, 0.0, w, h), Paint::Solid(Rgba::hex(0xeef2f7)))); + let mut back = layer(&mut d, "Background", LayerKind::Normal, 0x7e57c2, FRAMES, vec![bg]); + Arc::make_mut(&mut back).locked = true; + layers.push(back); + d.timeline_mut(0).layers = layers; + d +} + +fn banner_728x90() -> Document { + banner(728, 90) +} + +fn banner_300x250() -> Document { + banner(300, 250) +} + +/// A square post: a safe margin, the thirds and the centre on a guide layer. +fn social_square() -> Document { + const FRAMES: u32 = 30 * 15; + let mut d = blank(1080, 1080, 30.0); + let s = 1080.0; + let m = 60.0; + let mut guides = vec![outline(&mut d, "Safe margin", m, m, s - 2.0 * m, s - 2.0 * m, GUIDE, 2.0)]; + for (i, t) in [s / 3.0, s * 2.0 / 3.0].into_iter().enumerate() { + guides.push(line(&mut d, &format!("Third {}", i + 1), (t, 0.0), (t, s), GUIDE_SOFT, 1.0)); + guides.push(line(&mut d, &format!("Third {}", i + 3), (0.0, t), (s, t), GUIDE_SOFT, 1.0)); + } + guides.push(line(&mut d, "Centre", (s / 2.0 - 20.0, s / 2.0), (s / 2.0 + 20.0, s / 2.0), GUIDE, 2.0)); + guides.push(line(&mut d, "Centre", (s / 2.0, s / 2.0 - 20.0), (s / 2.0, s / 2.0 + 20.0), GUIDE, 2.0)); + let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)]; + layers.extend(drawing_layers(&mut d, &["Text", "Artwork", "Background"], FRAMES)); + d.timeline_mut(0).layers = layers; + d +} + +/// A storyboard for 16:9: the action-safe (93 %) and title-safe (90 %) areas and the centre on a +/// guide layer, and a Panels layer of six labelled 2-second keyframes (an animatic as it plays). +fn storyboard() -> Document { + const PANEL: u32 = 48; + const PANELS: u32 = 6; + let mut d = blank(1920, 1080, 24.0); + let (w, h) = (1920.0, 1080.0); + let safe = |d: &mut Document, name: &str, keep: f32, color: u32| { + let (mx, my) = (w * (1.0 - keep) / 2.0, h * (1.0 - keep) / 2.0); + outline(d, name, mx, my, w - 2.0 * mx, h - 2.0 * my, color, 2.0) + }; + let guides = vec![ + safe(&mut d, "Action safe", 0.93, GUIDE), + safe(&mut d, "Title safe", 0.90, GUIDE_SOFT), + line(&mut d, "Centre", (w / 2.0 - 30.0, h / 2.0), (w / 2.0 + 30.0, h / 2.0), GUIDE, 2.0), + line(&mut d, "Centre", (w / 2.0, h / 2.0 - 30.0), (w / 2.0, h / 2.0 + 30.0), GUIDE, 2.0), + ]; + let total = PANEL * PANELS; + let guide = layer(&mut d, "Safe areas", LayerKind::Guide, GUIDE, total, guides); + let notes = layer(&mut d, "Notes", LayerKind::Normal, 0xffd54a, total, Vec::new()); + let mut panels = Layer::new(LayerId(d.alloc_id()), "Panels"); + panels.color = Rgba::hex(0xff6b4a); + panels.keyframes = (0..PANELS) + .map(|i| { + let mut k = Keyframe::new(i * PANEL, PANEL); + k.label = format!("Panel {}", i + 1); + Arc::new(k) + }) + .collect(); + d.timeline_mut(0).layers = vec![guide, notes, Arc::new(panels)]; + d +} + +/// A turnaround: five views side by side (a centre line each) on horizontal lines a head +/// apart, eight heads from the top of the head to the ground, and a layer per view. +fn turnaround() -> Document { + let mut d = blank(1920, 1080, 24.0); + let (left, right, top, ground) = (60.0, 1860.0, 120.0, 960.0); + let head = (ground - top) / 8.0; + let mut guides = Vec::new(); + for i in 0..=8 { + let y = top + head * i as f32; + let (color, width) = if i == 0 || i == 8 { (GUIDE, 2.0) } else { (GUIDE_SOFT, 1.0) }; + let name = match i { + 0 => "Top of head".to_string(), + 8 => "Ground".to_string(), + n => format!("Head {n}"), + }; + guides.push(line(&mut d, &name, (left, y), (right, y), color, width)); + } + let views = ["Front", "Three-quarter", "Side", "Three-quarter back", "Back"]; + let col = (right - left) / views.len() as f32; + for (i, v) in views.iter().enumerate() { + let x = left + col * (i as f32 + 0.5); + guides.push(line(&mut d, v, (x, top - 30.0), (x, ground + 30.0), GUIDE, 1.5)); + } + let mut layers = vec![layer(&mut d, "Turnaround guides", LayerKind::Guide, GUIDE, 1, guides)]; + layers.extend(drawing_layers(&mut d, &views, 1)); + d.timeline_mut(0).layers = layers; + d +} + +/// The mouth shapes of a lip-sync chart, as frame labels and placeholder shapes to redraw. +pub const MOUTHS: [&str; 10] = ["Rest", "AI", "E", "O", "U", "CDGKNRSThYZ", "FV", "L", "MBP", "WQ"]; + +/// A lip-sync chart: a Mouth graphic symbol with a labelled keyframe per mouth shape (each with +/// a simple placeholder), placed at Single Frame on a face guide, so each keyframe of the Mouth +/// layer picks a shape by its first frame. +fn lip_sync() -> Document { + const FRAMES: u32 = 24; + let mut d = blank(1280, 720, 24.0); + let lips = Rgba::hex(0x8e3b46); + let mouth = |path: Path| Shape::filled(path, Paint::Solid(lips)).with_stroke(Rgba::hex(0x5a1f28), 3.0); + let shapes = [ + mouth(Path::rounded_rect(-50.0, -4.0, 100.0, 8.0, 4.0)), + mouth(Path::ellipse(0.0, 0.0, 55.0, 35.0)), + mouth(Path::ellipse(0.0, 0.0, 60.0, 20.0)), + mouth(Path::ellipse(0.0, 0.0, 35.0, 40.0)), + mouth(Path::ellipse(0.0, 0.0, 22.0, 26.0)), + mouth(Path::rounded_rect(-55.0, -14.0, 110.0, 28.0, 12.0)), + mouth(Path::rounded_rect(-50.0, -10.0, 100.0, 20.0, 8.0)), + mouth(Path::ellipse(0.0, 0.0, 45.0, 30.0)), + mouth(Path::rounded_rect(-50.0, -3.0, 100.0, 6.0, 3.0)), + mouth(Path::ellipse(0.0, 0.0, 18.0, 20.0)), + ]; + let sym_id = SymbolId(d.alloc_id()); + let mut inner = Layer::new(LayerId(d.alloc_id()), "Mouth"); + inner.color = Rgba::hex(0xff6b4a); + let mut keys = Vec::with_capacity(shapes.len()); + for (i, (label, shape)) in MOUTHS.iter().zip(shapes).enumerate() { + let mut k = Keyframe::new(i as u32, 1); + k.label = (*label).to_string(); + k.elements = vec![element(&mut d, &format!("{label} mouth"), Affine::IDENTITY, shape)]; + keys.push(Arc::new(k)); + } + inner.keyframes = keys; + d.library.push(Arc::new(Symbol { id: sym_id, name: "Mouth".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, scale_grid_kept: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + let (cx, cy) = (640.0, 340.0); + let face = element(&mut d, "Head", Affine::IDENTITY, Shape { path: Arc::new(Path::ellipse(cx, cy, 200.0, 250.0)), fill: None, stroke: Some(Stroke::new(Rgba::hex(GUIDE), 2.0)), fill_rule: Default::default(), merge: false }); + let guides = vec![ + face, + line(&mut d, "Eye line", (cx - 200.0, cy), (cx + 200.0, cy), GUIDE_SOFT, 1.0), + line(&mut d, "Centre line", (cx, cy - 250.0), (cx, cy + 250.0), GUIDE_SOFT, 1.0), + line(&mut d, "Mouth line", (cx - 120.0, cy + 130.0), (cx + 120.0, cy + 130.0), GUIDE_SOFT, 1.0), + ]; + let instance = Arc::new(Element { + id: ElementId(d.alloc_id()), + name: "mouth".into(), + transform: Affine::translate(cx, cy + 130.0), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: crate::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, + }); + let layers = vec![ + layer(&mut d, "Face guide", LayerKind::Guide, GUIDE, FRAMES, guides), + layer(&mut d, "Mouth", LayerKind::Normal, 0xff6b4a, FRAMES, vec![instance]), + layer(&mut d, "Head", LayerKind::Normal, 0x66bb6a, FRAMES, Vec::new()), + ]; + d.timeline_mut(0).layers = layers; + d +} + +/// A copy of `doc` with its guide layers drawn as artwork: a template's picture shows its +/// guides, which output never does. +pub fn with_guides_shown(doc: &Document) -> Document { + let show = |tl: &mut Timeline| { + for l in &mut tl.layers { + if l.kind == LayerKind::Guide { + Arc::make_mut(l).kind = LayerKind::Normal; + } + } + }; + let mut d = doc.clone(); + for scene in &mut d.scenes { + show(&mut Arc::make_mut(scene).timeline); + } + for sym in &mut d.library { + show(&mut Arc::make_mut(sym).timeline); + } + d +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_template_builds_a_consistent_document() { + let mut ids = std::collections::HashSet::new(); + for t in &TEMPLATES { + assert!(ids.insert(t.id), "{} is listed once", t.id); + assert!(find(t.id).is_some_and(|f| std::ptr::eq(f, t))); + let d = (t.build)(); + assert!(d.stage.width > 0 && d.stage.height > 0 && d.stage.fps > 0.0, "{}", t.id); + let tl = d.timeline(0); + assert!(tl.layers.len() >= 3, "{}: named layers to draw on", t.id); + assert!(tl.layers.iter().any(|l| l.kind == LayerKind::Guide && l.locked), "{}: a locked guide layer", t.id); + // Ids are unique and below `next_id`, so editing never reuses one. + let mut seen = std::collections::HashSet::new(); + let mut check = |id: u64| assert!(id < d.next_id && seen.insert(id), "{}: id {id}", t.id); + for l in &tl.layers { + check(l.id.0); + l.keyframes.iter().flat_map(|k| k.elements.iter()).for_each(|e| check(e.id.0)); + } + for s in &d.library { + check(s.id.0); + } + // Guides never render; the picture with them shown is not blank. + assert!(crate::evaluate(&d, 0).items.iter().all(|i| i.guide || tl.layer(i.layer).is_some_and(|l| l.kind != LayerKind::Guide))); + assert!(crate::evaluate(&with_guides_shown(&d), 0).items.iter().any(|i| !i.guide), "{}", t.id); + } + // The sizes the task asks for. + let size = |id: &str| find(id).map(|t| (t.build)().stage).map(|s| (s.width, s.height, s.fps)); + assert_eq!(size("banner-728x90"), Some((728, 90, 24.0))); + assert_eq!(size("banner-300x250"), Some((300, 250, 24.0))); + assert_eq!(size("social-square"), Some((1080, 1080, 30.0))); + assert_eq!(size("storyboard"), Some((1920, 1080, 24.0))); + } + + #[test] + fn the_storyboard_and_mouth_chart_are_labelled() { + let d = storyboard(); + let panels = d.timeline(0).layers.iter().find(|l| l.name == "Panels").map(|l| l.keyframes.iter().map(|k| k.label.clone()).collect::>()); + assert_eq!(panels.map(|p| p.len()), Some(6)); + assert_eq!(d.timeline(0).frame_count(), 6 * 48); + let d = lip_sync(); + let labels: Vec = d.library.first().map(|s| s.timeline.layers.iter().flat_map(|l| l.keyframes.iter().map(|k| k.label.clone())).collect()).unwrap_or_default(); + assert_eq!(labels, MOUTHS.map(str::to_string).to_vec()); + } +} diff --git a/crates/engine/src/cmds_drop.rs b/crates/engine/src/cmds_drop.rs index aeb097b8..52823213 100644 --- a/crates/engine/src/cmds_drop.rs +++ b/crates/engine/src/cmds_drop.rs @@ -1,7 +1,10 @@ //! Files dropped onto the window (ADR 0059). What a file is, and where it was dropped, decide //! what happens: documents open (`file.open`, which asks first over unsaved work); drawings, //! images and sounds dropped on the stage go onto the active layer at the playhead at the drop -//! point, and dropped on the Library go into the Library (into the folder under the pointer). +//! point, and dropped on the Library go into the Library (into the folder under the pointer; +//! an SVG as a graphic symbol, ADR 0065). Dropped on a layer's frame in the timeline, a sound +//! goes onto the keyframe there and a drawing or image onto that layer at that frame, in a +//! keyframe made there if there is none (ADR 0065). //! The routing is a pure function the shell and tests share; `file.drop` does the import, so a //! drop of several files is one undo step however many it brings in. @@ -34,6 +37,8 @@ pub enum DropKind { pub enum DropTarget { Stage, Library, + /// A layer's frame in the timeline. + Timeline, /// Anywhere else on the window (panels, the timeline, the menu bar). Window, } @@ -47,6 +52,8 @@ pub enum DropAction { ImportToStage, /// `file.drop` with `to: "library"`. ImportToLibrary, + /// `file.drop` with `to: "timeline"`. + ImportToTimeline, /// Nothing; the message (English, translated where it is shown) says why. Refuse(&'static str), } @@ -73,21 +80,24 @@ pub fn route(kind: DropKind, target: DropTarget) -> DropAction { match (kind, target) { (DropKind::Document, _) => DropAction::Open, (DropKind::Unsupported, _) => DropAction::Refuse(UNSUPPORTED), - (DropKind::Drawing, DropTarget::Library) => DropAction::Refuse("SVG drawings import to the stage: drop it there"), (_, DropTarget::Library) => DropAction::ImportToLibrary, + (_, DropTarget::Timeline) => DropAction::ImportToTimeline, (_, DropTarget::Stage) => DropAction::ImportToStage, - // Not over the stage or the Library: drop it on one of them. - (_, DropTarget::Window) => DropAction::Refuse("Drop drawings, images and sounds on the stage to place them, or on the Library to add them"), + // Not over the stage, the timeline or the Library: drop it on one of them. + (_, DropTarget::Window) => DropAction::Refuse(ELSEWHERE), } } +/// The message for media dropped where nothing takes them. +pub const ELSEWHERE: &str = "Drop drawings, images and sounds on the stage or a layer's frame to place them, or on the Library to add them"; + pub fn specs() -> Vec { vec![CommandSpec { id: "file.drop", label: "Import Dropped Files", menu: "", shortcut: None, - params: "{paths: [..] (or path; SVG, PNG, JPEG, WAV, OGG, MP3; at most 64), to: stage | library, x?, y? (stage: the drop point in the edited space, default the stage centre), folder? (library: a folder id)} → {elements, items, layers}: on the stage each drawing, image and sound goes onto the active layer's keyframe at the playhead, centred on the drop point (a drawing with several layers or masks gets its own layers, as Import to Stage); in the Library images and sounds are added, into `folder`. One undo step", + params: "{paths: [..] (or path; SVG, PNG, JPEG, WAV, OGG, MP3; at most 64), to: stage | library | timeline, x?, y? (stage and timeline: the point in the edited space to centre on, default the stage centre), folder? (library: a folder id), layer, frame (timeline: a layer id and a frame, from 0)} → {elements, items, layers}: on the stage each drawing, image and sound goes onto the active layer's keyframe at the playhead, centred on the drop point (a drawing with several layers or masks gets its own layers, as Import to Stage); in the Library images and sounds are added, and drawings become graphic symbols, into `folder`; on the timeline the playhead goes to the frame, a sound goes onto the layer's keyframe there (one sound per drop) and drawings and images onto the layer in a keyframe starting at that frame (made if needed, keeping what the frame showed; a drawing with several layers or masks goes in as a graphic symbol). One undo step", mutates: true, run: drop, }] @@ -113,14 +123,15 @@ fn drop(s: &mut Session, p: &Value) -> Result { let target = match str_req(p, "to")? { "stage" => DropTarget::Stage, "library" => DropTarget::Library, - other => return Err(EngineError::Param(format!("param 'to' must be stage or library, not '{other}'"))), + "timeline" => DropTarget::Timeline, + other => return Err(EngineError::Param(format!("param 'to' must be stage, library or timeline, not '{other}'"))), }; // Everything is checked before anything is imported (the command is atomic anyway). for f in &files { match route(kind_of(f), target) { DropAction::Open => return Err(EngineError::Param(format!("{} is a document: open it with file.open", f.display()))), DropAction::Refuse(why) => return Err(EngineError::Param(format!("{}: {why}", f.display()))), - DropAction::ImportToStage | DropAction::ImportToLibrary => {} + DropAction::ImportToStage | DropAction::ImportToLibrary | DropAction::ImportToTimeline => {} } } let folder = match opt_u64(p, "folder")? { @@ -139,14 +150,18 @@ fn drop(s: &mut Session, p: &Value) -> Result { if !(x.is_finite() && y.is_finite()) || x.abs() > 1.0e6 || y.abs() > 1.0e6 { return Err(EngineError::Param("'x' and 'y' must be within a million pixels of the origin".into())); } + if target == DropTarget::Timeline { + return onto_timeline(s, p, &files, x, y); + } let (mut elements, mut items, mut layers) = (Vec::new(), Vec::new(), 0u64); for f in &files { let path = f.display().to_string(); if target == DropTarget::Library { let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; - let item = match (v["bitmap"].as_u64(), v["sound"].as_u64()) { - (Some(b), _) => LibraryItem::Bitmap(anicraft_doc::BitmapId(b)), - (None, Some(snd)) => LibraryItem::Sound(anicraft_doc::SoundId(snd)), + let item = match (v["bitmap"].as_u64(), v["sound"].as_u64(), v["symbol"].as_u64()) { + (Some(b), _, _) => LibraryItem::Bitmap(anicraft_doc::BitmapId(b)), + (None, Some(snd), _) => LibraryItem::Sound(anicraft_doc::SoundId(snd)), + (None, None, Some(sym)) => LibraryItem::Symbol(anicraft_doc::SymbolId(sym)), _ => return Err(EngineError::State(format!("{path} added nothing to the Library"))), }; if let Some(folder) = folder { @@ -195,3 +210,73 @@ fn drop(s: &mut Session, p: &Value) -> Result { } Ok(json!({"elements": elements.iter().map(|e| e.0).collect::>(), "items": items, "layers": layers, "files": files.len()})) } + +/// A drop on a layer's frame in the timeline (ADR 0065). +fn onto_timeline(s: &mut Session, p: &Value, files: &[PathBuf], x: f32, y: f32) -> Result { + let layer = anicraft_doc::LayerId(opt_u64(p, "layer")?.ok_or_else(|| EngineError::Param("a drop on the timeline names its 'layer' (an id)".into()))?); + let frame = opt_u32(p, "frame")?.ok_or_else(|| EngineError::Param("a drop on the timeline names its 'frame' (from 0)".into()))?; + if frame > crate::MAX_FRAME { + return Err(EngineError::Param(format!("'frame' must be at most {}", crate::MAX_FRAME))); + } + let tl = s.timeline(); + let l = tl.layer(layer).ok_or_else(|| EngineError::State(format!("no layer with id {} here", layer.0)))?; + let refuse = match l.kind { + anicraft_doc::LayerKind::Folder => Some("is a folder: drop on one of its layers"), + anicraft_doc::LayerKind::Camera => Some("is the camera layer: drop on a layer below it"), + anicraft_doc::LayerKind::Armature => Some("holds an armature, posed by its bones: drop on another layer"), + _ if l.locked || tl.locked_by_folder(layer) => Some("is locked: unlock it to drop onto it"), + _ => None, + }; + if let Some(why) = refuse { + return Err(EngineError::State(format!("“{}” {why}", l.name))); + } + if files.iter().filter(|f| kind_of(f) == DropKind::Sound).count() > 1 { + return Err(EngineError::Param("a keyframe holds one sound: drop sounds one at a time, or on different layers".into())); + } + s.layer = layer; + s.frame = frame; + // Artwork goes into a keyframe starting at the frame: made there when the frame is inside + // another's span (keeping what it showed, as Insert Keyframe does). + let artwork = files.iter().any(|f| kind_of(f) != DropKind::Sound); + let made = artwork && s.timeline().layer(layer).is_some_and(|l| l.keyframe_starting_at(frame).is_none()); + if made { + crate::cmds_timeline::insert_keyframe_at(s.layer_mut(Some(layer))?, frame, true)?; + } + let (mut elements, mut items) = (Vec::new(), Vec::new()); + let placed_ids = |v: &Value| -> Vec { v["elements"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(anicraft_doc::ElementId).collect() }; + for f in files { + let path = f.display().to_string(); + let nothing = || EngineError::State(format!("{path} added nothing to the Library")); + match kind_of(f) { + DropKind::Drawing if crate::cmds_file::one_layer(&crate::cmds_file::read_svg(f)?) => { + crate::cmds_file::import_to_stage(s, &json!({"path": path, "cx": x, "cy": y, "layer": "active"}))?; + elements.extend(s.selection.ids()); + } + DropKind::Drawing => { + // Its layers can't all go on one layer: a graphic symbol holding them goes there. + let v = crate::cmds_file::import_svg_symbol(s, f, None)?; + let sym = v["symbol"].as_u64().ok_or_else(nothing)?; + items.push(json!({"symbol": sym})); + elements.extend(placed_ids(&crate::cmds_draw::place(s, &json!({"symbol": sym, "x": x, "y": y}))?)); + } + DropKind::Sound => { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let snd = v["sound"].as_u64().ok_or_else(nothing)?; + items.push(json!({"sound": snd})); + // Onto the keyframe the frame is in (one is made past the layer's end), as long + // as the sound when it is the layer's last. + crate::cmds_sound::place(s, &json!({"sound": snd, "layer": layer.0, "frame": frame, "extend": true}))?; + } + _ => { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let b = v["bitmap"].as_u64().ok_or_else(nothing)?; + items.push(json!({"bitmap": b})); + elements.extend(placed_ids(&crate::cmds_draw::place(s, &json!({"bitmap": b, "x": x, "y": y}))?)); + } + } + } + if !elements.is_empty() { + s.select_only(elements.iter().copied()); + } + Ok(json!({"elements": elements.iter().map(|e| e.0).collect::>(), "items": items, "layers": 0, "files": files.len(), "layer": layer.0, "frame": frame, "keyframe_made": made})) +} diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 7aa7fa93..c858d5c9 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -10,7 +10,7 @@ use std::path::PathBuf; use std::sync::Arc; pub fn specs() -> Vec { - vec![ + let mut v = vec![ CommandSpec { id: "file.new", label: "New", menu: "File", shortcut: Some("Ctrl+N"), params: "{width?, height?, fps?}", mutates: false, run: new_doc }, CommandSpec { id: "file.new_sample", label: "New from Sample", menu: "File", shortcut: None, params: "{which?: demo (default) | interactive (a menu with a Play button, for Test Movie)}", mutates: false, run: new_sample }, CommandSpec { id: "file.open", label: "Open…", menu: "File", shortcut: Some("Ctrl+O"), params: "{path, unsaved? (opens it as unsaved work: a restored copy), untitled? (with no file name, so Save asks for one)}", mutates: false, run: open }, @@ -122,7 +122,19 @@ pub fn specs() -> Vec { run: set_stage, }, CommandSpec { id: "doc.info", label: "Document Info", menu: "", shortcut: None, params: "{}", mutates: false, run: |s, _| Ok(s.info()) }, - ] + ]; + // In the File menu as in Animate: New from Template under New, Save as Template under + // Save As (ADR 0065). + for t in crate::cmds_template::specs() { + let after = match t.id { + "file.new_from_template" => "file.new_sample", + "file.save_as_template" => "file.save_as", + _ => "doc.info", + }; + let at = v.iter().position(|c| c.id == after).map_or(v.len(), |i| i + 1); + v.insert(at, t); + } + v } fn stage_edge(p: &Value, key: &str, default: u32) -> Result { @@ -410,6 +422,73 @@ pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { })) } +/// An SVG drawing read from `path` (size-checked), with at least one shape. +pub(crate) fn read_svg(path: &std::path::Path) -> Result { + if crate::vfs::len(path)? > MAX_IMPORT_BYTES { + return Err(EngineError::Format(format!("{} is too large to import", path.display()))); + } + let drawing = anicraft_svg::import(&crate::vfs::read(path)?).map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?; + if drawing.is_empty() { + return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary()))); + } + Ok(drawing) +} + +/// Whether a drawing fits on one layer (one run of artwork, nothing masked). +pub(crate) fn one_layer(d: &anicraft_svg::SvgImport) -> bool { + d.layers.len() == 1 && d.layers.iter().all(|l| l.mask.is_none()) +} + +/// Import to Library with an SVG (ADR 0065): a graphic symbol named after the file (a free +/// name at the Library's top level) holding the drawing's shapes, its registration point at +/// the drawing's centre. Clips and masks keep their mask layers inside the symbol. +pub(crate) fn import_svg_symbol(s: &mut Session, path: &std::path::Path, name: Option<&str>) -> Result { + use anicraft_doc::{Layer, LayerId, LayerKind, Symbol, SymbolId, SymbolKind, Timeline}; + let drawing = read_svg(path)?; + let stem: String = path.file_stem().map_or_else(|| "Drawing".into(), |n| n.to_string_lossy().chars().take(128).collect()); + let name = s.doc.unique_name(None, name.map_or(stem.as_str(), str::trim)); + let place = anicraft_geom::Affine::translate(-drawing.width * 0.5, -drawing.height * 0.5); + let elements = |s: &mut Session, list: Vec| -> Vec> { + list.into_iter() + .map(|e| Arc::new(anicraft_doc::Element { id: anicraft_doc::ElementId(s.doc.alloc_id()), name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect::opacity(e.alpha), kind: e.kind })) + .collect() + }; + let one_key = |els: Vec>| { + let mut k = anicraft_doc::Keyframe::new(0, 1); + k.elements = els; + vec![Arc::new(k)] + }; + let count = drawing.elements().count(); + let (width, height, report) = (drawing.width, drawing.height, drawing.report); + let runs = drawing.layers.len(); + // Top first: the drawing lists its runs in paint order (bottom first). + let mut layers: Vec> = Vec::new(); + for (n, l) in drawing.layers.into_iter().enumerate().rev() { + let mut parent = None; + if let Some(mask) = l.mask { + let mut ml = Layer::new(LayerId(s.doc.alloc_id()), if mask.name.is_empty() { "Mask".to_string() } else { mask.name.clone() }); + ml.kind = LayerKind::Mask; + ml.locked = true; + ml.keyframes = one_key(elements(s, mask.elements)); + parent = Some(ml.id); + layers.push(Arc::new(ml)); + } + let mut cl = Layer::new(LayerId(s.doc.alloc_id()), if runs == 1 { "Layer 1".to_string() } else { format!("Layer {}", n + 1) }); + cl.parent = parent; + cl.keyframes = one_key(elements(s, l.elements)); + layers.push(Arc::new(cl)); + } + let mut timeline = Timeline { layers }; + timeline.repair_masks(); + let id = SymbolId(s.doc.alloc_id()); + s.doc.library.push(Arc::new(Symbol { id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, scale_grid_kept: None, timeline })); + Ok(json!({"symbol": id.0, "name": name, "elements": count, "layers": timeline_len(s, id), "width": width, "height": height, "report": report.summary(), "skipped": report.skipped})) +} + +fn timeline_len(s: &Session, id: anicraft_doc::SymbolId) -> usize { + s.doc.library.iter().find(|x| x.id == id).map_or(0, |x| x.timeline.layers.len()) +} + /// A PNG or JPEG as a bitmap in the document, and the one shape that shows it: a rectangle of /// the image's size filled with it. JPEGs are kept as PNG (lossless, so nothing degrades). fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec) -> Result { diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index a5fb286f..abef14ef 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Import to Library…", "File/Import", None, - "{path (.wav, .ogg or .mp3 sound; .png or .jpg image), name?}", + "{path (.wav, .ogg or .mp3 sound; .png or .jpg image; .svg drawing: a graphic symbol named after the file holding its shapes), name?}", true, import_to_library as crate::RunFn, ), @@ -115,7 +115,11 @@ pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result { s.doc.bitmaps.push(Arc::new(bitmap)); return Ok(json!({"bitmap": id.0, "width": w, "height": h})); } - Err(EngineError::Param("Import to Library reads WAV, Ogg Vorbis and MP3 sounds, and PNG and JPEG images".into())) + if ext.as_deref() == Some("svg") { + // A drawing becomes a graphic symbol holding its shapes (ADR 0065). + return crate::cmds_file::import_svg_symbol(s, &path, opt_str(p, "name")?); + } + Err(EngineError::Param("Import to Library reads WAV, Ogg Vorbis and MP3 sounds, PNG and JPEG images, and SVG drawings (as a graphic symbol)".into())) } /// Import to Stage with a sound: into the library, and onto a new layer named after the file, diff --git a/crates/engine/src/cmds_template.rs b/crates/engine/src/cmds_template.rs new file mode 100644 index 00000000..4dfe2199 --- /dev/null +++ b/crates/engine/src/cmds_template.rs @@ -0,0 +1,195 @@ +//! Templates (ADR 0065): new documents from the templates AniCraft ships with +//! (`anicraft_doc::templates`, built by code) and from the user's own, which File › Save as +//! Template keeps as plain `.anicraft` files with a picture beside them: +//! `//.anicraft` and `.png`. The shell passes the folder (its +//! settings folder's `Templates`); the engine never looks for it, as with recent files. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session, format}; +use anicraft_doc::templates::{self, TEMPLATES}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Longest template or category name, in characters. +pub const MAX_NAME_CHARS: usize = 64; +/// Most categories and templates listed (a folder with more is not one we made). +const MAX_CATEGORIES: usize = 64; +const MAX_TEMPLATES: usize = 500; +/// The category a template is saved in when none is given. +pub const DEFAULT_CATEGORY: &str = "My Templates"; + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "file.new_from_template", + label: "New from Template…", + menu: "File", + shortcut: None, + params: "{template? (a built-in template's id, from file.templates) | path? (a template file: any .anicraft opens as a new, untitled document)}", + mutates: false, + run: new_from_template, + }, + CommandSpec { + id: "file.templates", + label: "List Templates", + menu: "", + shortcut: None, + params: "{folder? (the user templates folder)} → {builtin: [{id, name, category, description, width, height, fps, frames}], user: [{name, category, path, thumbnail}]}", + mutates: false, + run: list, + }, + CommandSpec { + id: "file.save_as_template", + label: "Save as Template…", + menu: "File", + shortcut: None, + params: "{folder (the user templates folder), name, category? (default “My Templates”), confirm? (to replace a template of that name)} → {path, thumbnail}: the document as it is, kept as //.anicraft with a picture of its first frame; the open document is unchanged", + mutates: false, + run: save_as_template, + }, + CommandSpec { id: "file.delete_template", label: "Delete Template", menu: "", shortcut: None, params: "{folder, name, category?, confirm}: removes a user template and its picture (cannot be undone)", mutates: false, run: delete_template }, + ] +} + +/// A name usable as a file or folder name on every system, or why not. +fn clean_name(raw: &str, what: &str) -> Result { + let name = raw.trim(); + if name.is_empty() { + return Err(EngineError::Param(format!("give the {what} a name"))); + } + if name.chars().count() > MAX_NAME_CHARS { + return Err(EngineError::Param(format!("a {what} name has at most {MAX_NAME_CHARS} characters"))); + } + if name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) { + return Err(EngineError::Param(format!("a {what} name can't use / \\ : * ? \" < > |"))); + } + if name.starts_with('.') || name.ends_with('.') { + return Err(EngineError::Param(format!("a {what} name can't start or end with a dot"))); + } + // Names Windows keeps for devices, with or without an extension. + let stem = name.split('.').next().unwrap_or(name).trim().to_ascii_uppercase(); + let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || ((stem.starts_with("COM") || stem.starts_with("LPT")) && stem.len() == 4 && stem.ends_with(|c: char| c.is_ascii_digit())); + if reserved { + return Err(EngineError::Param(format!("“{name}” is a name the system keeps for itself: pick another {what} name"))); + } + Ok(name.to_string()) +} + +/// Where a user template of this category and name is kept. +pub fn template_path(folder: &Path, category: &str, name: &str) -> Result { + let category = clean_name(category, "category")?; + let name = clean_name(name, "template")?; + Ok(folder.join(category).join(format!("{name}.anicraft"))) +} + +/// The picture kept beside a template file. +pub fn thumbnail_path(template: &Path) -> PathBuf { + template.with_extension("png") +} + +/// A user template found in the folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UserTemplate { + pub name: String, + pub category: String, + pub path: PathBuf, + /// Its picture, when there is one. + pub thumbnail: Option, +} + +/// The user's templates, by category then name (ignoring case). +pub fn user_templates(folder: &Path) -> Vec { + let mut out = Vec::new(); + for dir in crate::vfs::list(folder, MAX_CATEGORIES).into_iter().filter(|d| crate::vfs::is_dir(d)) { + let Some(category) = dir.file_name().map(|n| n.to_string_lossy().into_owned()) else { continue }; + for f in crate::vfs::list(&dir, MAX_TEMPLATES) { + if out.len() >= MAX_TEMPLATES { + break; + } + let is_template = f.extension().is_some_and(|e| e.eq_ignore_ascii_case("anicraft")) && crate::vfs::is_file(&f); + let Some(name) = f.file_stem().map(|n| n.to_string_lossy().into_owned()).filter(|_| is_template) else { continue }; + let thumb = thumbnail_path(&f); + out.push(UserTemplate { name, category: category.clone(), thumbnail: crate::vfs::is_file(&thumb).then_some(thumb), path: f }); + } + } + out.sort_by_key(|t| (t.category.to_lowercase(), t.name.to_lowercase())); + out +} + +fn new_from_template(s: &mut Session, p: &Value) -> Result { + let (doc, name) = match (opt_str(p, "template")?, opt_str(p, "path")?) { + (Some(id), None) => { + let t = templates::find(id).ok_or_else(|| EngineError::Param(format!("no template '{id}' (file.templates lists them)")))?; + ((t.build)(), t.name.to_string()) + } + (None, Some(path)) => { + let path = PathBuf::from(path); + if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("anicraft")) { + return Err(EngineError::Param("a template is an .anicraft document".into())); + } + let name = path.file_stem().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + (format::load(&path)?, name) + } + _ => return Err(EngineError::Param("name a built-in 'template' or a template file's 'path'".into())), + }; + // A new document: untitled, so Save asks for a name and never writes over the template. + s.replace_document(doc, None); + let mut info = s.info(); + info["template"] = json!(name); + Ok(info) +} + +fn list(_: &mut Session, p: &Value) -> Result { + let builtin: Vec = TEMPLATES + .iter() + .map(|t| { + let d = (t.build)(); + json!({"id": t.id, "name": t.name, "category": t.category, "description": t.description, "width": d.stage.width, "height": d.stage.height, "fps": d.stage.fps, "frames": d.frame_count()}) + }) + .collect(); + let user: Vec = match opt_str(p, "folder")? { + Some(f) => user_templates(Path::new(f)).into_iter().map(|t| json!({"name": t.name, "category": t.category, "path": t.path.display().to_string(), "thumbnail": t.thumbnail.map(|p| p.display().to_string())})).collect(), + None => Vec::new(), + }; + Ok(json!({"builtin": builtin, "user": user})) +} + +fn category(p: &Value) -> Result<&str> { + Ok(opt_str(p, "category")?.filter(|c| !c.trim().is_empty()).unwrap_or(DEFAULT_CATEGORY)) +} + +/// The template file the params name. +pub(crate) fn target(p: &Value) -> Result { + template_path(Path::new(str_req(p, "folder")?), category(p)?, str_req(p, "name")?) +} + +fn save_as_template(s: &mut Session, p: &Value) -> Result { + let path = target(p)?; + if let Some(dir) = path.parent() { + crate::vfs::create_dir_all(dir)?; + } + format::save(&s.doc, &path)?; + // Its picture shows the guides too (they are much of what a template is). + let thumb = thumbnail_path(&path); + let picture = crate::cmds_recent::thumbnail_png(&templates::with_guides_shown(&s.doc)).and_then(|png| Ok(crate::vfs::write(&thumb, png)?)); + Ok(json!({"path": path.display().to_string(), "thumbnail": picture.is_ok().then(|| thumb.display().to_string())})) +} + +fn delete_template(_: &mut Session, p: &Value) -> Result { + let path = target(p)?; + if !crate::vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no template “{}” in “{}”", str_req(p, "name")?.trim(), category(p)?.trim()))); + } + crate::vfs::remove_file(&path)?; + let thumb = thumbnail_path(&path); + if crate::vfs::is_file(&thumb) { + crate::vfs::remove_file(&thumb)?; + } + // An emptied category goes with its last template. + if let Some(dir) = path.parent() + && crate::vfs::list(dir, 1).is_empty() + { + let _ = std::fs::remove_dir(dir); + } + Ok(json!({"deleted": path.display().to_string()})) +} diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index cee96054..39bb549d 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -98,7 +98,21 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: true, }) } - "file.new" | "file.new_sample" | "file.open" | "file.open_recent" | "file.recover" if s.is_dirty() => Some(Confirmation { + "file.save_as_template" => { + let path = crate::cmds_template::target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Saving the template")) + } + "file.delete_template" => { + let path = crate::cmds_template::target(p).ok()?; + let name = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + Some(Confirmation { + title: "Delete template?".into(), + message: format!("The template “{name}” and its picture will be deleted from your templates. This cannot be undone."), + action: "Delete Template".into(), + irreversible: true, + }) + } + "file.new" | "file.new_sample" | "file.new_from_template" | "file.open" | "file.open_recent" | "file.recover" if s.is_dirty() => Some(Confirmation { title: "Discard unsaved changes?".into(), message: format!("“{}” has changes that are not saved. They will be lost, and its undo history is cleared.", doc_name(s)), action: "Discard Changes".into(), diff --git a/crates/engine/src/drop_tests.rs b/crates/engine/src/drop_tests.rs index a323ce0b..8f5b9d68 100644 --- a/crates/engine/src/drop_tests.rs +++ b/crates/engine/src/drop_tests.rs @@ -61,11 +61,13 @@ fn drops_route_by_file_type_and_target() { } for kind in [DropKind::Drawing, DropKind::Image, DropKind::Sound] { assert_eq!(route(kind, Stage), ImportToStage); - assert!(matches!(route(kind, Window), Refuse(_)), "only the stage and the Library take media"); + assert!(matches!(route(kind, Window), Refuse(_)), "only the stage, the timeline and the Library take media"); + // The Library takes drawings too, as graphic symbols (ADR 0065); a layer's frame takes all. + assert_eq!(route(kind, Library), ImportToLibrary); + assert_eq!(route(kind, Timeline), ImportToTimeline); } - assert_eq!(route(DropKind::Image, Library), ImportToLibrary); - assert_eq!(route(DropKind::Sound, Library), ImportToLibrary); - assert!(matches!(route(DropKind::Drawing, Library), Refuse(m) if m.contains("stage"))); + assert!(matches!(route(DropKind::Unsupported, Timeline), Refuse(_))); + assert_eq!(route(DropKind::Document, Timeline), Open); } #[test] @@ -116,9 +118,16 @@ fn media_dropped_on_the_library_go_into_the_folder_under_the_pointer() { // At the top level without a folder. run(&mut s, "file.drop", json!({"path": png, "to": "library"})); assert_eq!(s.doc.bitmaps.len(), 3); - // A drawing can't go into the Library; nothing is imported when one file is refused. + // A drawing goes in as one graphic symbol named after the file (ADR 0065), into the folder. + let symbols = s.doc.library.len(); + let v = run(&mut s, "file.drop", json!({"paths": [svg], "to": "library", "folder": folder})); + assert_eq!(s.doc.library.len(), symbols + 1, "{v}"); + let sym = s.doc.library.last().unwrap(); + assert_eq!((sym.name.as_str(), sym.kind), ("badge", anicraft_doc::SymbolKind::Graphic)); + assert!(s.doc.folder_contents(anicraft_doc::FolderId(folder)).contains(&anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Symbol(sym.id)))); + // Nothing is imported when one file is refused. let before = s.doc.clone(); - assert!(s.execute("file.drop", &json!({"paths": [svg], "to": "library"})).is_err()); + assert!(s.execute("file.drop", &json!({"paths": [png.clone(), dir.join("notes.txt").display().to_string()], "to": "library"})).is_err()); assert!(s.doc == before); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 58142abf..5683b62f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ pub mod cmds_raw; pub mod cmds_rawsub; mod cmds_rawpoints; pub mod cmds_recent; +pub mod cmds_template; mod cmds_recovery; mod cmds_script; pub mod cmds_plugin; @@ -1023,3 +1024,7 @@ mod selection_tests; mod scale_grid_tests; #[cfg(test)] mod drop_tests; +#[cfg(test)] +mod template_tests; +#[cfg(test)] +mod timeline_drop_tests; diff --git a/crates/engine/src/template_tests.rs b/crates/engine/src/template_tests.rs new file mode 100644 index 00000000..d7f8f33b --- /dev/null +++ b/crates/engine/src/template_tests.rs @@ -0,0 +1,153 @@ +//! Templates (ADR 0065): every built-in template opens as a new untitled document and saves, +//! and Save as Template keeps the document with a picture in the user's folder, round trip. + +use super::*; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-templates-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// `panic_hunt_every_command` leaves `file.*` out (they touch the disk): the template commands +/// and timeline drops get hostile params here, with every folder inside a temporary one. +#[test] +fn template_and_timeline_drop_commands_never_panic_on_hostile_params() { + let dir = temp_dir("fuzz"); + let folder = dir.display().to_string(); + let junk = [ + Value::Null, + json!([]), + json!("x"), + json!({}), + json!({"folder": folder}), + json!({"folder": folder, "name": 7}), + json!({"folder": folder, "name": "a", "category": ["x"]}), + json!({"folder": folder, "name": "\u{0}", "category": "\u{202e}"}), + json!({"folder": folder, "name": "é".repeat(64), "category": "ü".repeat(65)}), + json!({"folder": 3, "name": "a"}), + json!({"folder": folder, "name": "ok", "confirm": "yes"}), + json!({"template": 3}), + json!({"template": ""}), + json!({"path": ""}), + json!({"path": dir.join("nope.anicraft").display().to_string()}), + json!({"path": folder, "confirm": true}), + json!({"paths": ["a.png"], "to": "timeline", "layer": -1, "frame": 1e30}), + json!({"paths": ["a.wav"], "to": "timeline", "layer": "x", "frame": "y"}), + json!({"paths": ["a.svg"], "to": "timeline", "layer": 1, "frame": 0, "x": f64::NAN}), + ]; + for id in ["file.templates", "file.new_from_template", "file.save_as_template", "file.delete_template", "file.drop"] { + for p in &junk { + let mut s = Session::new(anicraft_doc::sample::demo()); + let _ = s.execute(id, p); + let mut confirmed = p.clone(); + if let Some(o) = confirmed.as_object_mut() { + o.insert("confirm".into(), json!(true)); + } + let _ = s.execute(id, &confirmed); + } + } +} + +#[test] +fn every_built_in_template_opens_untitled_and_survives_a_save() { + let dir = temp_dir("builtin"); + let list = run(&mut Session::default(), "file.templates", json!({})); + let builtin = list["builtin"].as_array().unwrap(); + assert_eq!(builtin.len(), anicraft_doc::templates::TEMPLATES.len()); + assert!(list["user"].as_array().unwrap().is_empty()); + for t in builtin { + let id = t["id"].as_str().unwrap(); + let mut s = Session::new(anicraft_doc::sample::demo()); + s.path = Some(dir.join("was.anicraft")); + let v = run(&mut s, "file.new_from_template", json!({"template": id})); + assert_eq!(v["template"], t["name"]); + assert!(s.path.is_none() && !s.is_dirty(), "{id}: a new, untitled document"); + assert_eq!((u64::from(s.doc.stage.width), u64::from(s.doc.stage.height)), (t["width"].as_u64().unwrap(), t["height"].as_u64().unwrap())); + // Drawing works straight away on a drawing layer, and it saves and opens again. + let target = s.timeline().layers.iter().find(|l| l.kind == anicraft_doc::LayerKind::Normal && !l.locked).map(|l| l.id).unwrap(); + s.layer = target; + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20})); + let path = dir.join(format!("{id}.anicraft")); + run(&mut s, "file.save_as", json!({"path": path.display().to_string()})); + let saved = s.doc.clone(); + run(&mut s, "file.open", json!({"path": path.display().to_string()})); + assert!(s.doc == saved, "{id}: round trip"); + // Thumbnails render (the shell draws these on the start screen). + let png = crate::cmds_recent::thumbnail_png(&anicraft_doc::templates::with_guides_shown(&s.doc)).unwrap(); + assert!(png.len() > 100); + } + let mut s = Session::default(); + assert!(s.execute("file.new_from_template", &json!({"template": "nope"})).is_err()); + assert!(s.execute("file.new_from_template", &json!({})).is_err()); + assert!(s.execute("file.new_from_template", &json!({"template": "storyboard", "path": "x.anicraft"})).is_err()); + // Over unsaved work it asks first, like New. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + assert!(s.confirmation("file.new_from_template", &json!({"template": "storyboard"})).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.new_from_template", &json!({"template": "storyboard"})).is_err()); + run(&mut s, "file.new_from_template", json!({"template": "storyboard", "confirm": true})); + assert_eq!(s.doc.stage.width, 1920); +} + +#[test] +fn save_as_template_keeps_the_document_and_a_picture_and_opens_as_new() { + let dir = temp_dir("user"); + let folder = dir.display().to_string(); + let mut s = Session::new(anicraft_doc::sample::demo()); + let mine = dir.join("walk.anicraft"); + run(&mut s, "file.save_as", json!({"path": mine.display().to_string()})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + let doc = s.doc.clone(); + let v = run(&mut s, "file.save_as_template", json!({"folder": folder, "name": " Walk cycle ", "category": "Characters"})); + let path = dir.join("Characters").join("Walk cycle.anicraft"); + assert_eq!(v["path"].as_str(), Some(path.display().to_string().as_str())); + assert!(path.is_file() && path.with_extension("png").is_file(), "{v}"); + assert_eq!(s.path.as_deref(), Some(mine.as_path()), "the open document keeps its own file"); + assert!(s.is_dirty(), "and its unsaved changes"); + // Listed, with its picture; a default category when none is given. + run(&mut s, "file.save_as_template", json!({"folder": folder, "name": "Blank"})); + let list = run(&mut s, "file.templates", json!({"folder": folder})); + let user: Vec<(String, String, bool)> = list["user"].as_array().unwrap().iter().map(|t| (t["category"].as_str().unwrap().to_string(), t["name"].as_str().unwrap().to_string(), t["thumbnail"].is_string())).collect(); + assert_eq!(user, [("Characters".to_string(), "Walk cycle".to_string(), true), (crate::cmds_template::DEFAULT_CATEGORY.to_string(), "Blank".to_string(), true)]); + // Opened from the template: the same document, new and untitled. + let mut other = Session::default(); + run(&mut other, "file.new_from_template", json!({"path": path.display().to_string()})); + assert!(other.doc == doc && other.path.is_none() && !other.is_dirty()); + assert!(other.recent.is_empty(), "a template is not a recent file"); + // The same name again replaces it only when confirmed. + let again = json!({"folder": folder, "name": "Walk cycle", "category": "Characters"}); + assert!(s.confirmation("file.save_as_template", &again).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.save_as_template", &again).is_err()); + let mut confirmed = again.clone(); + confirmed["confirm"] = json!(true); + run(&mut s, "file.save_as_template", confirmed); + // Names that can't be file names are refused before anything is written. + for (name, category) in [("", "x"), (" ", "x"), ("a/b", "x"), ("a", "..\\up"), ("CON", "x"), ("ok", "lpt1"), (".hidden", "x"), ("x", "dot."), ("tab\there", "x")] { + let p = json!({"folder": folder, "name": name, "category": category}); + assert!(s.execute("file.save_as_template", &p).is_err(), "{p}"); + } + let long = "x".repeat(crate::cmds_template::MAX_NAME_CHARS + 1); + assert!(s.execute("file.save_as_template", &json!({"folder": folder, "name": long})).is_err()); + // Deleting always confirms, and takes the picture and the emptied category with it. + let del = json!({"folder": folder, "name": "Walk cycle", "category": "Characters"}); + assert!(s.execute("file.delete_template", &del).is_err()); + assert!(path.is_file()); + let mut del = del; + del["confirm"] = json!(true); + run(&mut s, "file.delete_template", del.clone()); + assert!(!path.exists() && !path.with_extension("png").exists() && !dir.join("Characters").exists()); + assert!(s.execute("file.delete_template", &del).is_err(), "gone already"); + assert_eq!(run(&mut s, "file.templates", json!({"folder": folder}))["user"].as_array().map(Vec::len), Some(1)); + // A folder that isn't there lists nothing, and a non-template file doesn't open. + assert_eq!(run(&mut s, "file.templates", json!({"folder": dir.join("nope").display().to_string()}))["user"].as_array().map(Vec::len), Some(0)); + assert!(s.execute("file.new_from_template", &json!({"path": dir.join("x.png").display().to_string(), "confirm": true})).is_err()); +} diff --git a/crates/engine/src/timeline_drop_tests.rs b/crates/engine/src/timeline_drop_tests.rs new file mode 100644 index 00000000..8e26b9de --- /dev/null +++ b/crates/engine/src/timeline_drop_tests.rs @@ -0,0 +1,163 @@ +//! SVG into the Library and drops on the timeline (ADR 0065): a drawing becomes one graphic +//! symbol; media dropped on a layer's frame land there, in one undo step, and layers that can't +//! take them refuse without changing anything. + +use super::*; +use serde_json::json; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-tldrop-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A 4 × 2 PNG, a 40 × 20 one-rectangle SVG, a short WAV and a masked SVG in `dir`. +fn media(dir: &Path) -> (String, String, String, String) { + let png = dir.join("photo.png"); + std::fs::write(&png, anicraft_render::encode_png(4, 2, &[255u8; 4 * 2 * 4]).unwrap()).unwrap(); + let svg = dir.join("badge.svg"); + std::fs::write(&svg, r##""##).unwrap(); + let wav = dir.join("beep.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &[0.25; 4000])).unwrap(); + let masked = dir.join("masked.svg"); + std::fs::write(&masked, r##""##).unwrap(); + let s = |p: std::path::PathBuf| p.display().to_string(); + (s(png), s(svg), s(wav), s(masked)) +} + +#[test] +fn an_svg_imported_to_the_library_is_one_graphic_symbol_centred_on_its_registration_point() { + let dir = temp_dir("svgsym"); + let (_, svg, _, masked) = media(&dir); + let mut s = Session::default(); + let history = s.history_len(); + let v = run(&mut s, "file.import_to_library", json!({"path": svg})); + assert_eq!(s.history_len(), history + 1, "one undo step"); + assert_eq!((s.doc.library.len(), v["name"].as_str()), (1, Some("badge"))); + let sym = s.doc.library[0].clone(); + assert_eq!(sym.kind, anicraft_doc::SymbolKind::Graphic); + assert_eq!(sym.timeline.layers.len(), 1); + // The 40 × 20 drawing sits around the registration point. + let k = &sym.timeline.layers[0].keyframes[0]; + let b = k.elements.iter().fold(anicraft_geom::Rect::EMPTY, |r, e| match &e.kind { + anicraft_doc::ElementKind::Shape(sh) => r.union(&sh.path.bounds().transformed(&e.transform)), + _ => r, + }); + assert!(b.center().x.abs() < 0.01 && b.center().y.abs() < 0.01 && (b.width() - 40.0).abs() < 0.01, "{b:?}"); + assert!(s.timeline().layers.iter().all(|l| l.keyframes.iter().all(|k| k.elements.is_empty())), "nothing on the stage"); + // Again: a free name. A masked drawing keeps its mask layer inside the symbol. + assert_eq!(run(&mut s, "file.import_to_library", json!({"path": svg}))["name"], "badge 2"); + run(&mut s, "file.import_to_library", json!({"path": masked})); + let m = s.doc.library.last().unwrap(); + assert!(m.timeline.layers.iter().any(|l| l.kind == anicraft_doc::LayerKind::Mask) && m.timeline.layers.len() == 2, "{:?}", m.timeline.layers.iter().map(|l| (&l.name, l.kind)).collect::>()); + // Placed, it shows. + run(&mut s, "library.place", json!({"symbol": sym.id.0, "x": 100, "y": 100})); + assert!(!anicraft_doc::evaluate(&s.doc, 0).items.is_empty()); + let empty = dir.join("empty.svg"); + std::fs::write(&empty, r#""#).unwrap(); + let before = s.doc.clone(); + assert!(s.execute("file.import_to_library", &json!({"path": empty.display().to_string()})).is_err(), "a drawing with no shapes adds nothing"); + assert!(s.doc == before); +} + +/// A session whose one layer has a keyframe at 0, 12 frames long, holding a rectangle. +fn timeline_session() -> (Session, anicraft_doc::LayerId) { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_frame", json!({"count": 11})); + let layer = s.layer; + (s, layer) +} + +#[test] +fn an_image_dropped_on_a_layers_frame_goes_into_a_keyframe_there_in_one_step() { + let dir = temp_dir("tlimg"); + let (png, svg, _, _) = media(&dir); + let (mut s, layer) = timeline_session(); + let above = run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png, svg], "to": "timeline", "layer": layer.0, "frame": 5, "x": 200, "y": 100})); + assert_eq!(s.history_len(), history + 1, "one undo step for the whole drop"); + assert_eq!((s.layer, s.frame, v["keyframe_made"].as_bool()), (layer, 5, Some(true)), "the playhead and layer go to the drop"); + let l = s.timeline().layer(layer).unwrap(); + let k = l.keyframe_at(5).unwrap(); + assert_eq!(k.start, 5, "a keyframe starting at the frame"); + assert_eq!(k.elements.len(), 3, "what the frame showed, the image and the drawing"); + assert_eq!(l.keyframe_at(0).unwrap().elements.len(), 1, "the frames before are untouched"); + assert_eq!(s.selection.len(), 2, "what was dropped is selected"); + for id in s.selection.ids().collect::>() { + let b = s.element_bounds(id); + assert!((b.center().x - 200.0).abs() < 0.01 && (b.center().y - 100.0).abs() < 0.01, "{b:?}"); + } + assert!(s.timeline().layer(anicraft_doc::LayerId(above)).unwrap().keyframes.iter().all(|k| k.elements.is_empty()), "the layer active before the drop is untouched"); + run(&mut s, "edit.undo", json!({})); + let l = s.timeline().layer(layer).unwrap(); + assert!(l.keyframe_starting_at(5).is_none() && s.doc.bitmaps.is_empty()); + // On a keyframe's first frame, no new keyframe: the image joins it. + let v = run(&mut s, "file.drop", json!({"paths": [media(&dir).0], "to": "timeline", "layer": layer.0, "frame": 0})); + assert_eq!(v["keyframe_made"].as_bool(), Some(false)); + assert_eq!(s.timeline().layer(layer).unwrap().keyframes.len(), 1); +} + +#[test] +fn a_sound_dropped_on_a_frame_goes_onto_the_keyframe_holding_it() { + let dir = temp_dir("tlsnd"); + let (_, _, wav, _) = media(&dir); + let (mut s, layer) = timeline_session(); + let v = run(&mut s, "file.drop", json!({"path": wav, "to": "timeline", "layer": layer.0, "frame": 7})); + assert_eq!(v["keyframe_made"].as_bool(), Some(false)); + let l = s.timeline().layer(layer).unwrap(); + assert_eq!(l.keyframes.len(), 1, "no keyframe made for a sound"); + assert!(l.keyframes[0].sound.is_some(), "onto the keyframe the frame is in"); + // Past the layer's end, a keyframe is made there for it. + run(&mut s, "file.drop", json!({"path": media(&dir).2, "to": "timeline", "layer": layer.0, "frame": 30})); + let l = s.timeline().layer(layer).unwrap(); + assert!(l.keyframe_at(30).is_some_and(|k| k.start == 30 && k.sound.is_some())); +} + +#[test] +fn drops_on_the_timeline_refuse_layers_that_cant_take_them_and_change_nothing() { + let dir = temp_dir("tlbad"); + let (png, _, wav, masked) = media(&dir); + let (mut s, layer) = timeline_session(); + let folder = run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap(); + let layers = s.timeline().layers.len(); + // A drawing with masks can't go on one layer: a graphic symbol holding it goes there. + run(&mut s, "file.drop", json!({"path": masked, "to": "timeline", "layer": layer.0, "frame": 2})); + assert_eq!(s.timeline().layers.len(), layers, "no layers added"); + let k = s.timeline().layer(layer).unwrap().keyframe_at(2).unwrap(); + assert!(k.elements.iter().any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { .. }))); + assert_eq!(s.doc.library.len(), 1); + let before = s.doc.clone(); + let wav2 = dir.join("beep2.wav"); + std::fs::copy(&wav, &wav2).unwrap(); + for p in [ + json!({"path": png.clone(), "to": "timeline", "layer": folder, "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": u64::MAX, "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0}), + json!({"path": png.clone(), "to": "timeline", "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0, "frame": u64::MAX}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0, "frame": -1}), + json!({"paths": [wav.clone(), wav2.display().to_string()], "to": "timeline", "layer": layer.0, "frame": 0}), + json!({"paths": [png.clone(), dir.join("gone.png").display().to_string()], "to": "timeline", "layer": layer.0, "frame": 4}), + ] { + assert!(s.execute("file.drop", &p).is_err(), "{p}"); + assert!(s.doc == before, "{p} changed the document"); + } + s.layer = layer; + run(&mut s, "layer.toggle_lock", json!({})); + let before = s.doc.clone(); + for f in [png, wav] { + let e = s.execute("file.drop", &json!({"path": f, "to": "timeline", "layer": layer.0, "frame": 1})).unwrap_err(); + assert!(e.to_string().contains("locked"), "{e}"); + assert!(s.doc == before); + } +} From d2af0270a8ede2d62f83bf7a4ea4b947daa3f13b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:10:07 -0700 Subject: [PATCH 076/192] feat(shell): templates on the start screen, Save as Template, timeline drop highlight, footer fits every language (M8) --- crates/doc/src/templates.rs | 27 +- crates/engine/src/cmds_template.rs | 14 +- crates/engine/src/template_tests.rs | 6 +- src/a11y.rs | 2 +- src/app.rs | 43 +++- src/drop.rs | 170 ++++++++++--- src/i18n/tests.rs | 4 +- src/main.rs | 1 + src/platform.rs | 16 +- src/start.rs | 14 +- src/templates.rs | 367 ++++++++++++++++++++++++++++ src/timeline.rs | 29 ++- 12 files changed, 631 insertions(+), 62 deletions(-) create mode 100644 src/templates.rs diff --git a/crates/doc/src/templates.rs b/crates/doc/src/templates.rs index e40e4d67..1e2a6bf8 100644 --- a/crates/doc/src/templates.rs +++ b/crates/doc/src/templates.rs @@ -244,13 +244,28 @@ fn lip_sync() -> Document { d } -/// A copy of `doc` with its guide layers drawn as artwork: a template's picture shows its -/// guides, which output never does. -pub fn with_guides_shown(doc: &Document) -> Document { +/// A copy of `doc` with its guide layers drawn as artwork, their lines `widen` times as wide: a +/// template's picture shows its guides (which output never does), and a small picture needs +/// them wider to see them. +pub fn with_guides_shown(doc: &Document, widen: f32) -> Document { + let widen = if widen.is_finite() { widen.clamp(1.0, 16.0) } else { 1.0 }; let show = |tl: &mut Timeline| { for l in &mut tl.layers { - if l.kind == LayerKind::Guide { - Arc::make_mut(l).kind = LayerKind::Normal; + if l.kind != LayerKind::Guide { + continue; + } + let l = Arc::make_mut(l); + l.kind = LayerKind::Normal; + for k in &mut l.keyframes { + for e in &mut Arc::make_mut(k).elements { + if let ElementKind::Shape(sh) = &e.kind + && let Some(st) = &sh.stroke + { + let mut sh = sh.clone(); + sh.stroke = Some(Stroke { width: st.width * widen, ..st.clone() }); + Arc::make_mut(e).kind = ElementKind::Shape(sh); + } + } } } }; @@ -291,7 +306,7 @@ mod tests { } // Guides never render; the picture with them shown is not blank. assert!(crate::evaluate(&d, 0).items.iter().all(|i| i.guide || tl.layer(i.layer).is_some_and(|l| l.kind != LayerKind::Guide))); - assert!(crate::evaluate(&with_guides_shown(&d), 0).items.iter().any(|i| !i.guide), "{}", t.id); + assert!(crate::evaluate(&with_guides_shown(&d, 4.0), 0).items.iter().any(|i| !i.guide), "{}", t.id); } // The sizes the task asks for. let size = |id: &str| find(id).map(|t| (t.build)().stage).map(|s| (s.width, s.height, s.fps)); diff --git a/crates/engine/src/cmds_template.rs b/crates/engine/src/cmds_template.rs index 4dfe2199..881eb2ba 100644 --- a/crates/engine/src/cmds_template.rs +++ b/crates/engine/src/cmds_template.rs @@ -116,6 +116,14 @@ pub fn user_templates(folder: &Path) -> Vec { out } +/// A template's picture: its first frame fitting the recent files' thumbnail size, guides +/// drawn, their lines widened to stay visible at that size. +pub fn picture_png(doc: &anicraft_doc::Document) -> Result> { + let (w, h) = (doc.stage.width.max(1) as f32, doc.stage.height.max(1) as f32); + let scale = (crate::cmds_recent::THUMB_W as f32 / w).min(crate::cmds_recent::THUMB_H as f32 / h).min(1.0); + crate::cmds_recent::thumbnail_png(&templates::with_guides_shown(doc, 1.5 / scale.max(1e-3))) +} + fn new_from_template(s: &mut Session, p: &Value) -> Result { let (doc, name) = match (opt_str(p, "template")?, opt_str(p, "path")?) { (Some(id), None) => { @@ -134,6 +142,10 @@ fn new_from_template(s: &mut Session, p: &Value) -> Result { }; // A new document: untitled, so Save asks for a name and never writes over the template. s.replace_document(doc, None); + // Ready to draw: the top layer that takes artwork is active (not a locked guide). + if let Some(l) = s.timeline().layers.iter().find(|l| l.kind == anicraft_doc::LayerKind::Normal && !l.locked) { + s.layer = l.id; + } let mut info = s.info(); info["template"] = json!(name); Ok(info) @@ -171,7 +183,7 @@ fn save_as_template(s: &mut Session, p: &Value) -> Result { format::save(&s.doc, &path)?; // Its picture shows the guides too (they are much of what a template is). let thumb = thumbnail_path(&path); - let picture = crate::cmds_recent::thumbnail_png(&templates::with_guides_shown(&s.doc)).and_then(|png| Ok(crate::vfs::write(&thumb, png)?)); + let picture = picture_png(&s.doc).and_then(|png| Ok(crate::vfs::write(&thumb, png)?)); Ok(json!({"path": path.display().to_string(), "thumbnail": picture.is_ok().then(|| thumb.display().to_string())})) } diff --git a/crates/engine/src/template_tests.rs b/crates/engine/src/template_tests.rs index d7f8f33b..c14f0678 100644 --- a/crates/engine/src/template_tests.rs +++ b/crates/engine/src/template_tests.rs @@ -74,8 +74,8 @@ fn every_built_in_template_opens_untitled_and_survives_a_save() { assert!(s.path.is_none() && !s.is_dirty(), "{id}: a new, untitled document"); assert_eq!((u64::from(s.doc.stage.width), u64::from(s.doc.stage.height)), (t["width"].as_u64().unwrap(), t["height"].as_u64().unwrap())); // Drawing works straight away on a drawing layer, and it saves and opens again. - let target = s.timeline().layers.iter().find(|l| l.kind == anicraft_doc::LayerKind::Normal && !l.locked).map(|l| l.id).unwrap(); - s.layer = target; + let active = s.active_layer().unwrap(); + assert!(active.kind == anicraft_doc::LayerKind::Normal && !active.locked, "{id}: the active layer takes drawing"); run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20})); let path = dir.join(format!("{id}.anicraft")); run(&mut s, "file.save_as", json!({"path": path.display().to_string()})); @@ -83,7 +83,7 @@ fn every_built_in_template_opens_untitled_and_survives_a_save() { run(&mut s, "file.open", json!({"path": path.display().to_string()})); assert!(s.doc == saved, "{id}: round trip"); // Thumbnails render (the shell draws these on the start screen). - let png = crate::cmds_recent::thumbnail_png(&anicraft_doc::templates::with_guides_shown(&s.doc)).unwrap(); + let png = crate::cmds_template::picture_png(&s.doc).unwrap(); assert!(png.len() > 100); } let mut s = Session::default(); diff --git a/src/a11y.rs b/src/a11y.rs index 6c57a9ca..b1356a41 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -361,7 +361,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062): its controls, named in that window. diff --git a/src/app.rs b/src/app.rs index 6f3e36f3..edd5ff1f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -446,6 +446,8 @@ pub struct App { pub drop: crate::drop::DropState, /// Recent files' pictures for the start screen. pub thumbs: crate::recent::Thumbs, + /// Templates: their pictures, the user's list and the Save as Template dialog (ADR 0065). + pub templates: crate::templates::Templates, } /// How finished this version is, shown next to the version number (docs/release.md). English: @@ -615,6 +617,7 @@ impl App { start: None, drop: Default::default(), thumbs: Default::default(), + templates: Default::default(), }; app.apply_prefs(ctx); app.decode_sounds(); @@ -837,6 +840,14 @@ impl App { crate::recent::sample_entries(self); } } + Some("templates") => { + // File › New from Template: the start screen on its templates, with two sample + // templates of the user's own. + self.invoke("file.new_from_template"); + crate::templates::sample_user(self); + } + Some("savetemplate") => crate::templates::open_save(self), + Some("droptimeline") => self.drop.preview = Some((vec![PathBuf::from("whoosh.wav")], crate::drop::PreviewAt::Timeline)), // i18n-exempt: a sample file name Some("drop") => self.drop.preview = Some((vec![PathBuf::from("sunset.png")], crate::drop::PreviewAt::Stage)), // i18n-exempt: a sample file name Some("droplibrary") => { self.run("library.new_folder", json!({"name": "Backgrounds"})); // i18n-exempt: a sample folder name @@ -1611,7 +1622,7 @@ impl App { /// Any modal (prompt, confirmation, close guard) is open: global shortcuts pause. pub fn modal_open(&self) -> bool { - self.prompt.is_some() || self.convert.is_some() || self.confirm.is_some() || self.close_dialog || self.plugin_dialog.is_some() + self.prompt.is_some() || self.convert.is_some() || self.confirm.is_some() || self.close_dialog || self.plugin_dialog.is_some() || self.templates.save.is_some() } /// The single entry point for user-initiated commands: asks first when the engine says the @@ -1656,11 +1667,10 @@ impl App { /// new document resets. `selected` is how many elements were selected before it ran. pub(crate) fn announce(&mut self, id: &str, v: &Value, selected: usize) { match id { - "file.new" | "file.new_sample" | "file.open" | "file.open_recent" => { + "file.new" | "file.new_sample" | "file.new_from_template" | "file.open" | "file.open_recent" => { // The document is here: the start screen has done its job (ADR 0059). self.start = None; - if id != "file.new" - && id != "file.new_sample" + if !id.starts_with("file.new") && let Some(path) = self.s.path.clone().or_else(|| v["imported"].as_str().map(PathBuf::from)) { crate::recent::captured_on_open(self, &path); @@ -1672,7 +1682,10 @@ impl App { // An imported file: say what came across and what didn't, and that saving // makes a new .anicraft document. Some(r) => self.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)), - None => self.status_ok(if id == "file.open" || id == "file.open_recent" { tr!("Opened") } else { tr!("New document") }), + None => match v["template"].as_str() { + Some(t) => self.status_ok(tr!("New document from the template “{name}”", name = crate::i18n::t_dyn(t))), + None => self.status_ok(if id == "file.open" || id == "file.open_recent" { tr!("Opened") } else { tr!("New document") }), + }, } } "file.recover" => { @@ -1714,7 +1727,13 @@ impl App { tr!("{name} ({secs} s) is in the Library. Select a keyframe and pick it under Sound in Properties.", name = name, secs = secs) }); } + "file.import_to_library" if v.get("symbol").is_some() => { + // A drawing: a graphic symbol (ADR 0065), the Library's current item. + self.library_sel = v["symbol"].as_u64().map(|id| LibraryItem::Symbol(anicraft_engine::doc::SymbolId(id))); + self.status_ok(tr!("Added the graphic symbol “{name}” to the Library. Drag it to the stage to place it.", name = v["name"].as_str().unwrap_or(""))); + } "file.import_to_library" => self.status_ok(tr!("Image added to the Library")), + "file.save_as_template" | "file.delete_template" => crate::templates::announce(self, id, v), "file.export_audio" => { let n = v["sounds"].as_u64().unwrap_or(0); let (path, secs) = (v["written"].as_str().unwrap_or(""), format!("{:.2}", v["seconds"].as_f64().unwrap_or(0.0))); @@ -1862,6 +1881,19 @@ impl App { crate::start::open(self); return; } + if id == "file.new_from_template" { + // The start screen, on its templates (ADR 0065). + crate::start::open(self); + if let Some(st) = self.start.as_mut() { + st.show_templates = true; + } + self.status_ok(tr!("Pick a template to start a new document from. Esc goes back to the document.")); + return; + } + if id == "file.save_as_template" { + crate::templates::open_save(self); + return; + } if id == "tween.add_hint" { crate::shape_hints::add(self); return; @@ -2529,6 +2561,7 @@ impl App { crate::drop::frame(self, &ctx); self.prompt_window(&ctx); crate::convert_symbol::window(self, &ctx); + crate::templates::save_window(self, &ctx); crate::layer_props::window(self, &ctx); self.about_window(&ctx); dialogs::show_all(self, &ctx); diff --git a/src/drop.rs b/src/drop.rs index e13eda97..1ba316f1 100644 --- a/src/drop.rs +++ b/src/drop.rs @@ -1,21 +1,23 @@ //! Files dropped onto the window from the desktop or a browser (ADR 0059). Documents open (the //! unsaved-changes guard as with File › Open); drawings, images and sounds dropped on the stage -//! go onto the active layer at the playhead where they were dropped, and dropped on the Library -//! go into it, into the folder under the pointer. While files are dragged over the window a -//! highlight shows where they will land. The routing is `anicraft_engine::cmds_drop::route`; +//! go onto the active layer at the playhead where they were dropped, dropped on the Library +//! go into it, into the folder under the pointer (an SVG as a graphic symbol), and dropped on a +//! layer's frame in the timeline go onto that layer at that frame (ADR 0065). While files are +//! dragged over the window a highlight shows where they will land. The routing is `anicraft_engine::cmds_drop::route`; //! the import is the `file.drop` command, one undo step. //! //! Where a drop lands needs the pointer. Browsers report it while dragging (our own `dragover` //! listener, `web::drag_pos`), but winit 0.30 gives no position with dragged files, and Windows //! and macOS send no pointer moves during a drag. So a drop waits a moment for the pointer's //! first move after it (the system sends one as the drag ends); without one it lands at the -//! centre of the view, and says so. +//! centre of the view, and says so. (winit 0.30.13, which eframe 0.36 and 0.37 both use, still +//! has no drag position; ADR 0065.) use crate::app::App; use crate::theme::{T, Type, color, font}; use anicraft_engine::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; -use anicraft_engine::doc::FolderId; -use egui::{Pos2, Rect, Stroke, StrokeKind, vec2}; +use anicraft_engine::doc::{FolderId, LayerId, LayerKind}; +use egui::{Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; use serde_json::json; use std::path::{Path, PathBuf}; @@ -39,6 +41,30 @@ impl StageGeo { } } +/// Where the timeline's rows and frames were drawn this frame (set by `timeline::show`). +#[derive(Clone, Debug, Default)] +pub struct TimelineGeo { + /// Each visible row (the layer column and its frames), and its layer. + pub rows: Vec<(Rect, LayerId)>, + /// Where the frame cells start (left of it is the layer column). + pub cells_left: f32, + /// The screen x of frame 0's left edge, and a frame's width. + pub x0: f32, + pub cell_w: f32, +} + +impl TimelineGeo { + /// The layer and frame under `p` (over the layer column: the playhead's frame), and the + /// frame's cell. + pub fn at(&self, p: Pos2, playhead: u32) -> Option<(LayerId, u32, Rect)> { + let (row, layer) = *self.rows.iter().find(|(r, _)| r.contains(p))?; + let cw = self.cell_w.max(1.0); + let frame = if p.x >= self.cells_left { ((p.x - self.x0) / cw).floor().clamp(0.0, anicraft_engine::MAX_FRAME as f32) as u32 } else { playhead }; + let left = self.x0 + frame as f32 * cw; + Some((layer, frame, Rect::from_min_max(pos2(left.max(self.cells_left), row.top()), pos2((left + cw).max(self.cells_left), row.bottom())))) + } +} + /// Where a drop at a point lands. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Spot { @@ -46,6 +72,8 @@ pub enum Spot { Stage(f32, f32), /// On the Library, into this folder (`None`: the top level). Library(Option), + /// On a layer's frame in the timeline. + Timeline(LayerId, u32), /// Somewhere else on the window. Window, /// The start screen is up: documents open, nothing imports. @@ -67,12 +95,11 @@ pub struct Plan { } /// Why a file can't go there, in the interface language. -fn refusal(kind: DropKind, to: DropTarget, start: bool) -> String { +fn refusal(kind: DropKind, start: bool) -> String { match kind { DropKind::Unsupported => tr!("AniCraft opens .anicraft, .fla and .xfl documents, and imports SVG drawings, PNG and JPEG images, and WAV, Ogg and MP3 sounds").into(), _ if start => tr!("Open or create a document first, then drop drawings, images and sounds on its stage").into(), - DropKind::Drawing if to == DropTarget::Library => tr!("SVG drawings import to the stage: drop it there").into(), - _ => tr!("Drop drawings, images and sounds on the stage to place them, or on the Library to add them").into(), + _ => tr!("Drop drawings, images and sounds on the stage or a layer's frame to place them, or on the Library to add them").into(), } } @@ -89,6 +116,7 @@ pub fn plan(files: &[PathBuf], spot: Spot) -> Plan { } let to = match spot { Spot::Library(_) => DropTarget::Library, + Spot::Timeline(..) => DropTarget::Timeline, // Without a position, the stage (at the centre of the view). Spot::Stage(..) | Spot::Unknown => DropTarget::Stage, Spot::Window | Spot::Start => DropTarget::Window, @@ -96,9 +124,9 @@ pub fn plan(files: &[PathBuf], spot: Spot) -> Plan { for f in files { let kind = kind_of(f); match route(kind, to) { - DropAction::ImportToStage | DropAction::ImportToLibrary => out.import.push(f.clone()), + DropAction::ImportToStage | DropAction::ImportToLibrary | DropAction::ImportToTimeline => out.import.push(f.clone()), DropAction::Open => {} - DropAction::Refuse(_) => out.left_out.push((f.clone(), refusal(kind, to, spot == Spot::Start))), + DropAction::Refuse(_) => out.left_out.push((f.clone(), refusal(kind, spot == Spot::Start))), } } if !out.import.is_empty() { @@ -121,6 +149,8 @@ struct Waiting { pub struct DropState { /// Where the stage was drawn this frame (set by `stage::show`). pub stage: Option, + /// Where the timeline's rows were drawn this frame (set by `timeline::show`). + pub timeline: Option, waiting: Option, /// The pointer moved while files were dragged over the window: its position is current. tracked: bool, @@ -135,6 +165,7 @@ pub struct DropState { pub enum PreviewAt { Stage, Library, + Timeline, } /// Where a drop at `p` lands, from this frame's layout. @@ -146,6 +177,9 @@ pub fn spot_at(app: &App, p: Option) -> Spot { if let Some(folder) = app.library.drop_zone.folder_at(p) { return Spot::Library(folder); } + if let Some((layer, frame, _)) = app.drop.timeline.as_ref().and_then(|t| t.at(p, app.s.frame)) { + return Spot::Timeline(layer, frame); + } match app.drop.stage { Some(g) if g.canvas.contains(p) => { let (x, y) = g.to_stage(p); @@ -158,6 +192,7 @@ pub fn spot_at(app: &App, p: Option) -> Spot { /// Before the panels draw: forget last frame's targets (a hidden panel takes nothing). pub fn begin_frame(app: &mut App) { app.drop.stage = None; + app.drop.timeline = None; app.library.drop_zone = Default::default(); } @@ -305,6 +340,20 @@ pub fn run(app: &mut App, files: &[PathBuf], spot: Spot) { } }) } + (DropTarget::Timeline, Spot::Timeline(layer, frame)) => { + // Centred in the view, in the edited space, as Paste puts things. + let c = view_centre(app); + let v = app.run("file.drop", json!({"paths": paths, "to": "timeline", "layer": layer.0, "frame": frame, "x": c.0, "y": c.1})); + v.map(|v| { + let name = app.s.timeline().layer(layer).map(|l| l.name.clone()).unwrap_or_default(); + let (frame, undo) = (frame + 1, app.undo_key()); + if v["keyframe_made"].as_bool() == Some(true) { + trn!("Placed {n} file on {layer} at frame {frame}, in a new keyframe — {undo} to undo", "Placed {n} files on {layer} at frame {frame}, in a new keyframe — {undo} to undo", n, layer = name, frame = frame, undo = undo) + } else { + trn!("Placed {n} file on {layer} at frame {frame} — {undo} to undo", "Placed {n} files on {layer} at frame {frame} — {undo} to undo", n, layer = name, frame = frame, undo = undo) + } + }) + } _ => { let geo = app.drop.stage; if geo.is_some_and(|g| g.paused) { @@ -313,14 +362,7 @@ pub fn run(app: &mut App, files: &[PathBuf], spot: Spot) { } let (centred, (x, y)) = match spot { Spot::Stage(x, y) => (false, (x, y)), - _ => { - let c = app.view_center_stage(); - let c = match app.s.edit_view() { - Some(v) if v.scale.abs() > 1e-6 => ((c.x - v.origin.x) / v.scale, (c.y - v.origin.y) / v.scale), - _ => (c.x, c.y), - }; - (true, c) - } + _ => (true, view_centre(app)), }; let v = app.run("file.drop", json!({"paths": paths, "to": "stage", "x": x, "y": y})); v.map(|_| { @@ -352,7 +394,29 @@ pub fn open_from_system(app: &mut App, files: &[PathBuf]) { app.playing = false; run(app, &files, Spot::Window); } else if let Some(f) = files.first() { - app.status_err(tr!("Can't open {file}: {why}", file = crate::recent::display_name(f), why = refusal(DropKind::Unsupported, DropTarget::Window, false))); + app.status_err(tr!("Can't open {file}: {why}", file = crate::recent::display_name(f), why = refusal(DropKind::Unsupported, false))); + } +} + +/// The middle of what the stage shows, in the edited space. +fn view_centre(app: &App) -> (f32, f32) { + let c = app.view_center_stage(); + match app.s.edit_view() { + Some(v) if v.scale.abs() > 1e-6 => ((c.x - v.origin.x) / v.scale, (c.y - v.origin.y) / v.scale), + _ => (c.x, c.y), + } +} + +/// Why a layer can't take a drop (the engine refuses the same), in the interface language. +fn layer_refusal(app: &App, layer: LayerId) -> Option { + let tl = app.s.timeline(); + let l = tl.layer(layer)?; + match l.kind { + LayerKind::Folder => Some(tr!("{layer} is a folder: drop on one of its layers", layer = l.name)), + LayerKind::Camera => Some(tr!("{layer} is the camera layer: drop on a layer below it", layer = l.name)), + LayerKind::Armature => Some(tr!("{layer} holds an armature: drop on another layer", layer = l.name)), + _ if l.locked || tl.locked_by_folder(layer) => Some(tr!("{layer} is locked: unlock it to drop onto it", layer = l.name)), + _ => None, } } @@ -374,6 +438,11 @@ fn preview_point(app: &App, at: PreviewAt) -> Option { match at { PreviewAt::Stage => app.drop.stage.map(|g| g.canvas.center() + vec2(-g.canvas.width() * 0.12, -g.canvas.height() * 0.08)), PreviewAt::Library => app.library.drop_zone.rows.iter().find(|(_, f)| f.is_some()).map(|(r, _)| r.center()), + // A few frames past the playhead on the second row (the first when there is one). + PreviewAt::Timeline => app.drop.timeline.as_ref().and_then(|t| { + let (row, _) = t.rows.get(1).or_else(|| t.rows.first())?; + Some(pos2(t.x0 + (app.s.frame as f32 + 8.5) * t.cell_w, row.center().y)) + }), } } @@ -407,7 +476,7 @@ fn highlight(app: &App, ctx: &egui::Context, files: &[PathBuf], p: Option) 1 => crate::recent::display_name(known[0]), n => trn!("{n} file", "{n} files", n), }; - let fits = |to: DropTarget| known.iter().all(|f| matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary)); + let fits = |to: DropTarget| known.iter().all(|f| fits_one(f, to)); match (spot, p) { (Spot::Stage(..), Some(p)) => { if let Some(g) = app.drop.stage { @@ -418,7 +487,24 @@ fn highlight(app: &App, ctx: &egui::Context, files: &[PathBuf], p: Option) painter.line_segment([p - vec2(0.0, r), p + vec2(0.0, r)], Stroke::new(1.5, T.accent)); let ok = fits(DropTarget::Stage); let layer = app.s.active_layer().map(|l| l.name.clone()).unwrap_or_default(); - let text = if ok { tr!("Place {what} on {layer} at frame {frame}", what = what, layer = layer, frame = app.s.frame + 1) } else { refusal(DropKind::Unsupported, DropTarget::Stage, false) }; + let text = if ok { tr!("Place {what} on {layer} at frame {frame}", what = what, layer = layer, frame = app.s.frame + 1) } else { refusal(DropKind::Unsupported, false) }; + label(p + vec2(14.0, 12.0), text, ok); + } + (Spot::Timeline(layer, frame), Some(p)) => { + // The row outlined and the frame's cell filled: where it lands. + if let Some((row, cell)) = app.drop.timeline.as_ref().and_then(|t| Some((t.rows.iter().find(|(_, l)| *l == layer)?.0, t.at(p, app.s.frame)?.2))) { + painter.rect_stroke(row, crate::theme::SQUARE, Stroke::new(1.5, T.accent), StrokeKind::Inside); + painter.rect_filled(cell, crate::theme::SQUARE, T.accent.gamma_multiply(0.45)); + painter.rect_stroke(cell, crate::theme::SQUARE, stroke, StrokeKind::Inside); + } + let name = app.s.timeline().layer(layer).map(|l| l.name.clone()).unwrap_or_default(); + let sounds_only = !known.is_empty() && known.iter().all(|f| kind_of(f) == DropKind::Sound); + let (ok, text) = match layer_refusal(app, layer) { + Some(why) => (false, why), + None if !fits(DropTarget::Timeline) => (false, refusal(DropKind::Unsupported, false)), + None if sounds_only => (true, tr!("Put {what} on {layer}'s keyframe at frame {frame}", what = what, layer = name, frame = frame + 1)), + None => (true, tr!("Place {what} on {layer} at frame {frame}", what = what, layer = name, frame = frame + 1)), + }; label(p + vec2(14.0, 12.0), text, ok); } (Spot::Library(folder), Some(p)) => { @@ -438,8 +524,8 @@ fn highlight(app: &App, ctx: &egui::Context, files: &[PathBuf], p: Option) (true, Some(f)) => tr!("Add {what} to “{folder}”", what = what, folder = f.name), (true, None) => tr!("Add {what} to the Library", what = what), (false, _) => match known.iter().find(|f| !fits_one(f, DropTarget::Library)) { - Some(f) => refusal(kind_of(f), DropTarget::Library, false), - None => refusal(DropKind::Unsupported, DropTarget::Library, false), + Some(f) => refusal(kind_of(f), false), + None => refusal(DropKind::Unsupported, false), }, }; label(p + vec2(14.0, 12.0), text, ok); @@ -447,17 +533,17 @@ fn highlight(app: &App, ctx: &egui::Context, files: &[PathBuf], p: Option) (Spot::Unknown, _) => { // The desktop doesn't say where the pointer is during a drag: say what each place does. painter.rect_stroke(screen, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); - label(screen.center_top() + vec2(-180.0, 12.0), tr!("Drop {what} on the stage to place it, or on the Library to add it", what = what), true); + label(screen.center_top() + vec2(-180.0, 12.0), tr!("Drop {what} on the stage or a layer's frame to place it, or on the Library to add it", what = what), true); } (spot, p) => { let at = p.unwrap_or(screen.center_top()) + vec2(14.0, 12.0); - label(at, refusal(known.first().map_or(DropKind::Image, |f| kind_of(f)), DropTarget::Window, spot == Spot::Start), false); + label(at, refusal(known.first().map_or(DropKind::Image, |f| kind_of(f)), spot == Spot::Start), false); } } } fn fits_one(f: &Path, to: DropTarget) -> bool { - matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary) + matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary | DropAction::ImportToTimeline) } #[cfg(test)] @@ -471,7 +557,7 @@ mod tests { #[test] fn drops_are_routed_by_type_and_target() { // A document opens wherever it lands, and only one at a time. - for spot in [Spot::Stage(1.0, 2.0), Spot::Library(None), Spot::Window, Spot::Start, Spot::Unknown] { + for spot in [Spot::Stage(1.0, 2.0), Spot::Library(None), Spot::Timeline(LayerId(1), 0), Spot::Window, Spot::Start, Spot::Unknown] { let plan = plan(&[p("walk.anicraft"), p("photo.png"), p("old.fla")], spot); assert_eq!(plan.open, Some(p("walk.anicraft")), "{spot:?}"); assert!(plan.import.is_empty()); @@ -482,10 +568,12 @@ mod tests { let on_stage = plan_at(Spot::Stage(10.0, 20.0)); assert_eq!((on_stage.to, on_stage.import.len(), on_stage.left_out.len()), (Some(DropTarget::Stage), 3, 1)); assert!(on_stage.left_out[0].1.contains("SVG"), "says what AniCraft reads"); - // On the Library: images and sounds; a drawing is pointed to the stage. + // On the Library: drawings (as graphic symbols), images and sounds. let in_library = plan_at(Spot::Library(Some(FolderId(7)))); - assert_eq!((in_library.to, in_library.import.len(), in_library.left_out.len()), (Some(DropTarget::Library), 2, 2)); - assert!(in_library.left_out.iter().any(|(f, why)| f == &p("a.svg") && why.contains("stage"))); + assert_eq!((in_library.to, in_library.import.len(), in_library.left_out.len()), (Some(DropTarget::Library), 3, 1)); + // On a layer's frame: the same three. + let on_frame = plan_at(Spot::Timeline(LayerId(3), 9)); + assert_eq!((on_frame.to, on_frame.import.len(), on_frame.left_out.len()), (Some(DropTarget::Timeline), 3, 1)); // Elsewhere on the window, or over the start screen: nothing imports. for spot in [Spot::Window, Spot::Start] { let plan = plan_at(spot); @@ -517,6 +605,13 @@ mod tests { let (row, folder) = *app.library.drop_zone.rows.iter().find(|(_, f)| f.is_some()).expect("the folder row drew"); assert_eq!(spot_at(&app, Some(row.center())), Spot::Library(folder)); assert_eq!(spot_at(&app, Some(egui::pos2(1.0, 1.0))), Spot::Window, "the menu bar takes nothing"); + // A timeline row: its layer, and the frame under the pointer (the playhead's over the + // layer column). + let tl = app.drop.timeline.clone().expect("the timeline drew"); + let (row, layer) = tl.rows[1]; + let x = tl.x0 + 6.5 * tl.cell_w; + assert_eq!(spot_at(&app, Some(egui::pos2(x, row.center().y))), Spot::Timeline(layer, 6)); + assert_eq!(spot_at(&app, Some(egui::pos2(row.left() + 30.0, row.center().y))), Spot::Timeline(layer, app.s.frame)); assert_eq!(spot_at(&app, None), Spot::Unknown); crate::start::open(&mut app); assert_eq!(spot_at(&app, Some(geo.canvas.center())), Spot::Start); @@ -539,6 +634,19 @@ mod tests { run(&mut app, std::slice::from_ref(&png), Spot::Library(Some(folder))); assert_eq!(app.s.doc.folder_contents(folder).len(), 1); assert!(app.library.expanded.contains(&folder), "the folder opens to show it"); + // On a layer's frame: onto that layer, in a keyframe made there, one undo step. + let star = app.s.timeline().layers[1].id; + let undo = app.s.history_len(); + run(&mut app, std::slice::from_ref(&png), Spot::Timeline(star, 9)); + assert_eq!(app.s.history_len(), undo + 1); + assert!(app.s.timeline().layer(star).and_then(|l| l.keyframe_at(9)).is_some_and(|k| k.start == 9 && k.elements.iter().any(|e| app.s.selection.contains(star, e.id)))); + assert!(app.status.as_ref().is_some_and(|s| !s.error && s.text.contains("new keyframe")), "{:?}", app.status.as_ref().map(|s| &s.text)); + // A locked layer says why, and nothing changes. + app.s.layer = star; + app.run("layer.toggle_lock", json!({})); + let before = app.s.doc.clone(); + run(&mut app, std::slice::from_ref(&png), Spot::Timeline(star, 12)); + assert!(app.s.doc == before && app.status.as_ref().is_some_and(|s| s.error && s.text.contains("locked"))); // An unsupported file: one clear message, nothing changes. let before = app.s.doc.clone(); run(&mut app, &[dir.join("notes.txt")], Spot::Stage(0.0, 0.0)); diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 46e51a72..4c78fba1 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -587,7 +587,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("element.set_color_effect", serde_json::json!({"style": style})); })); } - for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "publishanim", "start", "testmovie", "testmovieinside"] { + for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "publishanim", "start", "testmovie", "testmovieinside", "templates", "savetemplate"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062; egui stands in for the window system here). @@ -782,7 +782,7 @@ fn screen_reader_names_are_translated_too() { found.extend(untranslated_names("library item", |a, _| { a.library_sel = a.s.doc.library.first().map(|s| crate::app::LibraryItem::Symbol(s.id)); })); - for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testmovieinside", "testscript", "exporthtml", "envelope"] { + for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testmovieinside", "testscript", "exporthtml", "envelope", "templates", "savetemplate", "droptimeline"] { found.extend(untranslated_names(panel, |a, _| a.open_panel(Some(panel)))); } assert!(found.is_empty(), "{} screen-reader names not translated in the pseudo-locale:\n{}", found.len(), found.join("\n")); diff --git a/src/main.rs b/src/main.rs index 7ffdd8c2..b92b225a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -59,6 +59,7 @@ mod sound; mod shape_hints; mod stage; mod start; +mod templates; mod test_movie; mod theme; mod timeline; diff --git a/src/platform.rs b/src/platform.rs index 4ea33149..eeeb5de0 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -199,10 +199,24 @@ pub fn unavailable(cmd: &str) -> Option<&'static str> { match cmd { "file.export_video" => Some(tr_noop!("Video export runs ffmpeg, which a web browser can't start: use the desktop app, or export an animated GIF or a PNG sequence")), "plugin.install" | "plugin.remove" | "plugin.reload" => Some(tr_noop!("Plug-ins are installed into a folder on your computer: use the desktop app")), + "file.save_as_template" => Some(tr_noop!("Your templates are kept in a folder on your computer: use the desktop app (the built-in templates work here)")), _ => None, } } +/// Where the user's templates live (ADR 0065): `Templates` in the settings folder, one folder +/// per category. `ANICRAFT_TEMPLATES_DIR` points it elsewhere (tests, screenshots, portable +/// installs). None in a browser, which has no folders to keep them in. +pub fn templates_dir() -> Option { + if WEB { + return None; + } + match std::env::var_os("ANICRAFT_TEMPLATES_DIR").filter(|v| !v.is_empty()) { + Some(d) => Some(PathBuf::from(d)), + None => config_dir().map(|d| d.join("Templates")), // i18n-exempt: a folder name + } +} + /// Where installed plug-ins live: a `plugins` folder in the settings folder (ADR 0017). pub fn plugins_dir() -> Option { config_dir().map(|d| d.join("plugins")) @@ -451,7 +465,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { "file.export_lottie" => (tr_noop!("Lottie animation"), &["json"]), "file.export_html" => (tr_noop!("Web page"), &["html", "htm"]), "file.import" => (tr_noop!("Drawing, image or sound"), &["svg", "png", "jpg", "jpeg", "wav", "ogg", "mp3"]), - "file.import_to_library" => (tr_noop!("Sound or image"), &["wav", "ogg", "mp3", "png", "jpg", "jpeg"]), + "file.import_to_library" => (tr_noop!("Sound, image or drawing"), &["wav", "ogg", "mp3", "png", "jpg", "jpeg", "svg"]), "file.export_audio" => (tr_noop!("WAV sound"), &["wav"]), "file.export_sprite_sheet" => (tr_noop!("PNG sprite sheet"), &["png"]), "file.export_video" => (tr_noop!("Video (WebM or MP4)"), &["webm", "mp4"]), diff --git a/src/start.rs b/src/start.rs index c5cee4af..264192de 100644 --- a/src/start.rs +++ b/src/start.rs @@ -1,6 +1,7 @@ //! The start screen (ADR 0059): what AniCraft shows when it starts without a document to open, //! as Animate's Home screen does. New with stage-size presets (and a custom size), Open, the -//! recent files with their pictures, and the sample animation. It takes the place of the +//! recent files with their pictures, the sample animation, and the templates (ADR 0065: built-in +//! and the user's own; File › New from Template opens the screen on them). It takes the place of the //! workspace, never sits over it as a dialog: the menus keep working, Esc goes back to the //! document, and New, Open or a recent file dismisses it once the document is there. @@ -34,12 +35,14 @@ pub struct StartScreen { pub width: u32, pub height: u32, pub fps: f32, + /// Opened from File › New from Template: scroll to the templates once. + pub show_templates: bool, } impl Default for StartScreen { fn default() -> Self { let d = anicraft_engine::doc::Stage::default(); - StartScreen { width: d.width, height: d.height, fps: d.fps } + StartScreen { width: d.width, height: d.height, fps: d.fps, show_templates: false } } } @@ -52,6 +55,7 @@ pub fn new_params(width: u32, height: u32, fps: f32) -> serde_json::Value { pub fn open(app: &mut App) { app.playing = false; app.start = Some(StartScreen { fps: app.s.doc.stage.fps, ..StartScreen::default() }); + crate::templates::rescan(app); app.status_ok(tr!("Pick a size to start a new animation, or open one you made. Esc goes back to the document.")); } @@ -78,6 +82,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { open_column(app, right, &ctx); } }); + ui.add_space(20.0); + let head = crate::templates::section(app, ui, &ctx); + if let Some(st) = app.start.as_mut().filter(|s| s.show_templates) { + st.show_templates = false; + ui.scroll_to_rect(head, Some(egui::Align::TOP)); + } ui.add_space(16.0); footer(app, ui); }); diff --git a/src/templates.rs b/src/templates.rs new file mode 100644 index 00000000..9f499d67 --- /dev/null +++ b/src/templates.rs @@ -0,0 +1,367 @@ +//! Templates in the window (ADR 0065): the Templates row of the start screen (the built-in +//! templates and the user's own, each with its picture), which File › New from Template opens +//! on, and the File › Save as Template dialog. The commands do the work +//! (`file.new_from_template`, `file.save_as_template`, `file.delete_template`); the user's +//! templates live in the settings folder (`platform::templates_dir`). + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::icons::{self, Icon}; +use crate::theme::{FORM_LABEL_DOCK, T, Type, form_row, text}; +use anicraft_engine::cmds_template::{self, UserTemplate}; +use anicraft_engine::doc::templates::{TEMPLATES, Template}; +use egui::{Align2, Rect, Sense, Stroke, StrokeKind, Vec2, WidgetType, pos2, vec2}; +use serde_json::json; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// The built-in templates' names, categories and descriptions, for the catalogs: the engine's +/// English is the key, translated where it is drawn. +pub const TEXTS: [&str; 17] = [ + tr_noop!("Leaderboard banner"), + tr_noop!("Rectangle banner"), + tr_noop!("Social square"), + tr_noop!("Storyboard 16:9"), + tr_noop!("Character turnaround"), + tr_noop!("Lip-sync mouth chart"), + tr_noop!("Advertising"), + tr_noop!("Social"), + tr_noop!("Storyboard"), + tr_noop!("Character"), + tr_noop!("A 728 × 90 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer"), + tr_noop!("A 300 × 250 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer"), + tr_noop!("A 1080 × 1080 post at 30 fps, 15 seconds long, with a safe margin and thirds on a guide layer"), + tr_noop!("Six 2-second panels at 1920 × 1080, labelled Panel 1 to 6, with action- and title-safe areas"), + tr_noop!("Front, three-quarter, side and back views side by side, on head-height guides eight heads tall"), + tr_noop!("A Mouth graphic symbol with ten labelled mouth shapes to redraw, placed on a face guide"), + tr_noop!("My Templates"), +]; + +/// The folder the user's templates are in. Screenshot and test runs never touch the real one: +/// they use a temporary folder (unless `ANICRAFT_TEMPLATES_DIR` names one). +pub fn folder(app: &App) -> Option { + if app.shot.is_some() && std::env::var_os("ANICRAFT_TEMPLATES_DIR").is_none() && !crate::platform::WEB { + return Some(std::env::temp_dir().join(format!("anicraft-templates-shot-{}", std::process::id()))); + } + crate::platform::templates_dir() +} + +/// A built-in template's text in the interface language. +fn t(s: &'static str) -> &'static str { + if TEXTS.contains(&s) { crate::i18n::t(s) } else { s } +} + +/// A tile's picture size. +const THUMB: Vec2 = Vec2::new(168.0, 95.0); + +/// What the window keeps for templates between frames. +#[derive(Default)] +pub struct Templates { + /// Pictures, by built-in id or user template path (`None`: couldn't be made). + thumbs: HashMap>, + /// The user's templates, as last read from the folder. + pub user: Vec, + /// The Save as Template dialog, while it is open. + pub save: Option, + /// Pictures made in memory (screenshot runs show sample user templates without a folder). + pub(crate) seeded: HashMap>, +} + +/// The Save as Template dialog. +pub struct SaveDialog { + pub name: String, + pub category: String, + focus: bool, + /// The document's picture, made on the dialog's first frame (`None` inside: none to show). + picture: Option>, +} + +fn texture(ctx: &egui::Context, key: &str, png: &[u8]) -> Option { + let px = anicraft_engine::doc::decode_png(png)?; + let (w, h) = (usize::try_from(px.width).ok()?, usize::try_from(px.height).ok()?); + (w > 0 && h > 0 && px.rgba.len() == w * h * 4).then(|| ctx.load_texture(format!("template-{key}"), egui::ColorImage::from_rgba_unmultiplied([w, h], &px.rgba), egui::TextureOptions::LINEAR)) +} + +/// A document's picture as a template shows it: its first frame, guides drawn. +fn picture_png(doc: &anicraft_engine::doc::Document) -> Option> { + cmds_template::picture_png(doc).ok() +} + +impl Templates { + /// A built-in template's picture, rendered by the CPU oracle once. + fn builtin(&mut self, ctx: &egui::Context, t: &Template) -> Option { + self.thumbs.entry(t.id.to_string()).or_insert_with(|| picture_png(&(t.build)()).and_then(|png| texture(ctx, t.id, &png))).clone() + } + + /// A user template's picture, read from beside it once. + fn user_picture(&mut self, ctx: &egui::Context, t: &UserTemplate) -> Option { + let key = t.path.display().to_string(); + if let Some(tex) = self.thumbs.get(&key) { + return tex.clone(); + } + let png = self.seeded.get(&key).cloned().or_else(|| t.thumbnail.as_deref().and_then(|p| std::fs::read(p).ok())); + let tex = png.and_then(|png| texture(ctx, &key, &png)); + self.thumbs.insert(key, tex.clone()); + tex + } + + /// Reads the user's templates again (when the start screen opens, after a save or delete). + pub fn rescan(&mut self, folder: Option<&Path>) { + if !self.seeded.is_empty() { + return; // sample entries (screenshots) + } + self.user = folder.map(cmds_template::user_templates).unwrap_or_default(); + // Pictures may have changed under the same names. + self.thumbs.retain(|k, _| TEMPLATES.iter().any(|t| t.id == k)); + } +} + +/// A template's tile: its picture, name, and category with size. `None` size: unknown. +fn tile(ui: &mut egui::Ui, tex: Option, name: &str, note: &str, size: Option, tip: &str) -> egui::Response { + ui.vertical(|ui| { + ui.set_width(THUMB.x); + ui.spacing_mut().item_spacing.y = 2.0; + let (r, resp) = ui.allocate_exact_size(THUMB, Sense::click()); + a11y::control(ui, &resp, WidgetType::Button, &tr!("New from template {name}", name = name), None); + let hot = resp.hovered() || resp.has_focus(); + let p = ui.painter(); + p.rect_filled(r, T.rc(), T.panel_alt); + match tex { + Some(tex) => { + let s = tex.size_vec2(); + let fit = ((r.width() - 8.0) / s.x.max(1.0)).min((r.height() - 8.0) / s.y.max(1.0)); + p.image(tex.id(), Rect::from_center_size(r.center(), s * fit), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => icons::paint(p, Rect::from_center_size(r.center(), vec2(28.0, 28.0)), Icon::Image, T.text_faint), + } + p.rect_stroke(r, T.rc(), Stroke::new(if hot { 1.5 } else { 1.0 }, if hot { T.accent } else { T.border }), StrokeKind::Inside); + a11y::focus_ring(ui, &resp); + ui.add(egui::Label::new(text(Type::Body, name)).truncate()); + ui.horizontal(|ui| { + ui.add(egui::Label::new(text(Type::Caption, note).color(T.text_dim)).truncate()); + if let Some(size) = size { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(text(Type::DataSmall, size).color(T.text_dim))); + } + }); + resp.on_hover_text(tip) + }) + .inner +} + +/// The Templates row of the start screen. Returns the heading's rect (File › New from Template +/// scrolls to it). +pub fn section(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context) -> Rect { + let head = ui.label(text(Type::Heading, tr!("Templates"))).rect; + ui.add_space(6.0); + let mut act: Option<(&'static str, serde_json::Value)> = None; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(10.0, 10.0); + for t in &TEMPLATES { + let d = (t.build)(); + let size = format!("{} × {}", d.stage.width, d.stage.height); + let tex = app.templates.builtin(ctx, t); + let tip = tr!("{description} · {fps} fps", description = self::t(t.description), fps = d.stage.fps); + if tile(ui, tex, self::t(t.name), self::t(t.category), Some(size), &tip).clicked() { + act = Some(("file.new_from_template", json!({"template": t.id}))); + } + } + }); + ui.add_space(12.0); + ui.label(text(Type::Label, tr!("My templates"))); + ui.add_space(4.0); + let user = app.templates.user.clone(); + if user.is_empty() { + let hint = if folder(app).is_some() { tr!("File › Save as Template keeps the open document here, with a picture, to start from again.") } else { tr!("Your own templates are kept in a folder on your computer: save them in the desktop app.") }; + ui.label(text(Type::Caption, hint)); + } else { + let folder = folder(app); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(10.0, 10.0); + for t in &user { + ui.vertical(|ui| { + let tex = app.templates.user_picture(ctx, t); + if tile(ui, tex, &t.name, &t.category, None, &t.path.display().to_string()).clicked() { + act = Some(("file.new_from_template", json!({"path": t.path.display().to_string()}))); + } + if let Some(f) = &folder + && ui.small_button(tr!("Delete")).named(&tr!("Delete template {name}", name = t.name)).on_hover_text(tr!("Delete this template and its picture (asks first)")).clicked() + { + act = Some(("file.delete_template", json!({"folder": f.display().to_string(), "category": t.category, "name": t.name}))); + } + }); + } + }); + } + if let Some((id, params)) = act { + app.request(id, params); + } + head +} + +/// File › Save as Template: the dialog, with the open document's picture, a name and a +/// category. +pub fn open_save(app: &mut App) { + if folder(app).is_none() { + app.status_err(crate::i18n::t(crate::platform::unavailable("file.save_as_template").unwrap_or(tr_noop!("There is no settings folder to keep templates in on this system")))); + return; + } + app.playing = false; + rescan(app); + let name = app.s.path.as_deref().and_then(Path::file_stem).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned()); + app.templates.save = Some(SaveDialog { name, category: self::t(cmds_template::DEFAULT_CATEGORY).to_string(), focus: true, picture: None }); +} + +/// Reads the user's templates again. +pub fn rescan(app: &mut App) { + let f = folder(app); + app.templates.rescan(f.as_deref()); +} + +/// The categories the user has saved templates in, and the default, each once. +fn categories(user: &[UserTemplate]) -> Vec { + let mut out = vec![self::t(cmds_template::DEFAULT_CATEGORY).to_string()]; + for t in user { + if !out.iter().any(|c| c.eq_ignore_ascii_case(&t.category)) { + out.push(t.category.clone()); + } + } + out +} + +pub fn save_window(app: &mut App, ctx: &egui::Context) { + let Some(folder) = folder(app) else { + app.templates.save = None; + return; + }; + let cats = categories(&app.templates.user); + let doc = &app.s.doc; + let Some(d) = &mut app.templates.save else { return }; + if d.picture.is_none() { + d.picture = Some(picture_png(doc).and_then(|png| texture(ctx, "save-preview", &png))); + } + let (mut submit, mut cancel) = (false, false); + egui::Window::new(tr!("Save as Template")).id(egui::Id::new("save_template")).collapsible(false).resizable(false).anchor(Align2::CENTER_CENTER, [0.0, -60.0]).show(ctx, |ui| { + ui.set_min_width(420.0); + if let Some(Some(tex)) = &d.picture { + let s = tex.size_vec2(); + let fit = (240.0 / s.x.max(1.0)).min(135.0 / s.y.max(1.0)); + ui.vertical_centered(|ui| { + let r = ui.add(egui::Image::new((tex.id(), s * fit))).rect; + ui.painter().rect_stroke(r, crate::theme::SQUARE, Stroke::new(1.0, T.border), StrokeKind::Outside); + }); + ui.add_space(6.0); + } + form_row(ui, FORM_LABEL_DOCK, tr!("Name"), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Template name")); + if d.focus { + r.request_focus(); + d.focus = false; + } + if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + submit = true; + } + }); + form_row(ui, FORM_LABEL_DOCK, tr!("Category"), |ui| { + ui.add(egui::TextEdit::singleline(&mut d.category).desired_width(f32::INFINITY)).named(tr!("Template category")); + }); + ui.horizontal_wrapped(|ui| { + ui.add_space(FORM_LABEL_DOCK); + for c in &cats { + if ui.selectable_label(d.category.trim().eq_ignore_ascii_case(c), c.as_str()).on_hover_text(tr!("Save it in this category")).clicked() { + d.category = c.clone(); + } + } + }); + // Where it goes, and what it replaces. + let target = cmds_template::template_path(&folder, d.category.trim(), d.name.trim()); + match &target { + Ok(p) if p.is_file() => ui.label(text(Type::Caption, tr!("A template called “{name}” is in this category already: saving asks to replace it.", name = d.name.trim())).color(T.accent_text)), + Ok(p) => ui.label(text(Type::Path, p.display().to_string()).color(T.text_dim)), + Err(e) => ui.label(text(Type::Caption, crate::i18n::t_dyn(&e.to_string()).into_owned()).color(T.error)), + }; + ui.label(text(Type::Caption, tr!("The template keeps the document as it is now. The open document doesn't change."))); + ui.add_space(4.0); + ui.horizontal(|ui| { + if ui.add_enabled(target.is_ok(), egui::Button::new(tr!("Save Template"))).clicked() { + submit = true; + } + if ui.button(tr!("Cancel")).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + cancel = true; + } + }); + }); + if submit { + if let Some(d) = app.templates.save.take() { + app.request("file.save_as_template", json!({"folder": folder.display().to_string(), "name": d.name.trim(), "category": d.category.trim()})); + } + } else if cancel { + app.templates.save = None; + } +} + +/// After a template command: the status line and the list (called from `App::announce`). +pub fn announce(app: &mut App, id: &str, v: &serde_json::Value) { + match id { + "file.save_as_template" => { + rescan(app); + let name = v["path"].as_str().map(PathBuf::from).and_then(|p| p.file_stem().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default(); + app.status_ok(tr!("Saved the template “{name}”. File › New from Template starts a document from it.", name = name)); + } + "file.delete_template" => { + rescan(app); + app.status_ok(tr!("Template deleted")); + } + _ => {} + } +} + +/// Sample user templates for screenshots (pictures made in memory, no folder touched). +pub fn sample_user(app: &mut App) { + let samples = [(tr_noop!("Walk cycle"), tr_noop!("Characters"), anicraft_engine::doc::sample::demo()), (tr_noop!("Title card"), cmds_template::DEFAULT_CATEGORY, anicraft_engine::doc::templates::find("social-square").map_or_else(Default::default, |t| (t.build)()))]; + app.templates.user.clear(); + for (name, category, doc) in samples { + let path = PathBuf::from(format!("{category}/{name}.anicraft")); + if let Some(png) = picture_png(&doc) { + app.templates.seeded.insert(path.display().to_string(), png); + } + app.templates.user.push(UserTemplate { name: crate::i18n::t(name).to_string(), category: crate::i18n::t(category).to_string(), path, thumbnail: None }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_built_in_templates_text_is_in_the_catalog_list() { + for t in &TEMPLATES { + for s in [t.name, t.category, t.description] { + assert!(TEXTS.contains(&s), "{s:?} is listed for translation"); + } + } + assert!(TEXTS.contains(&cmds_template::DEFAULT_CATEGORY)); + } + + #[test] + fn a_template_tile_opens_a_new_document_from_it() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(PathBuf::from("unused.png"))); + crate::start::open(&mut app); + app.request("file.new_from_template", json!({"template": "banner-300x250"})); + assert!(app.start.is_none(), "the start screen goes once the document is there"); + assert_eq!((app.s.doc.stage.width, app.s.doc.stage.height), (300, 250)); + assert!(app.status.as_ref().is_some_and(|s| !s.error && s.text.contains("Rectangle banner")), "{:?}", app.status.as_ref().map(|s| &s.text)); + // Over unsaved work it asks first. + app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + app.request("file.new_from_template", json!({"template": "storyboard"})); + assert!(app.confirm.is_some()); + // The section draws every built-in template with its picture. + app.confirm = None; + crate::start::open(&mut app); + sample_user(&mut app); + let screen = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() }; + let mut out = ctx.run_ui(screen, |ui| app.frame(ui)); + out.textures_delta.clear(); + assert_eq!(TEMPLATES.iter().filter(|t| app.templates.thumbs.get(t.id).is_some_and(Option::is_some)).count(), TEMPLATES.len()); + } +} diff --git a/src/timeline.rs b/src/timeline.rs index 9a871832..512a46b4 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -429,6 +429,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let rows_bottom = body.bottom() - FOOTER_H; let tl_now = app.s.timeline().clone(); let mut next_y = rows_top; + // Where each row is, for files dropped on a layer's frame (ADR 0065). + let mut drop_rows = Vec::new(); for (r, &i) in rows.iter().enumerate().skip(first_row) { let Some(layer) = layers.get(i) else { continue }; let y = next_y; @@ -440,6 +442,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } next_y += rh; let row = Rect::from_min_size(pos2(body.left(), y), vec2(body.width(), rh)); + drop_rows.push((row, layer.id)); let left = Rect::from_min_max(row.left_top(), pos2(grid.left(), row.bottom())); let is_active = layer.id == active; painter.rect_filled(left, 0.0, if is_active { T.accent_dim } else if r % 2 == 0 { T.panel } else { T.panel_alt }); @@ -1064,6 +1067,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.with_clip_rect(grid).text(head.center(), Align2::CENTER_CENTER, label, font(role), T.ink); } + app.drop.timeline = Some(crate::drop::TimelineGeo { rows: drop_rows, cells_left: grid.left(), x0: grid.left() + pad - scroll * cell_w, cell_w }); + // footer buttons for layers let footer = Rect::from_min_max(pos2(body.left(), body.bottom() - FOOTER_H), pos2(grid.left(), body.bottom())); if n_layers > rows_visible { @@ -1074,18 +1079,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { { painter.rect_filled(footer, 0.0, T.panel_alt); painter.line_segment([footer.left_top(), footer.right_top()], Stroke::new(1.0, T.border)); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(footer.shrink2(vec2(8.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); - if child.button(tr!("+ Layer")).on_hover_text(tr!("New layer")).clicked() { - app.run("layer.new", json!({})); - } - if child.add_enabled(layers.len() > 1, egui::Button::new(tr!("Delete"))).named(tr!("Delete layer")).on_hover_text(tr!("Delete the active layer")).clicked() { - app.request("layer.delete", json!({})); - } - // New folder, Up and Down as icon buttons, so the row fits the layer column. + // New folder, Up and Down as icon buttons, laid out first from the right edge so they + // always show; the text buttons share what is left, shortened if a language makes them + // long (pseudo-locale screenshots lost the Down chevron off the column's edge). + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(footer.shrink2(vec2(8.0, 4.0))).layout(egui::Layout::right_to_left(egui::Align::Center))); for (icon, id, tip) in [ - (Icon::FolderPlus, "layer.new_folder", tr!("New folder above the active layer (move layers in under it with Up and Down)")), - (Icon::ChevronUp, "layer.move_up", tr!("Move layer up")), (Icon::ChevronDown, "layer.move_down", tr!("Move layer down")), + (Icon::ChevronUp, "layer.move_up", tr!("Move layer up")), + (Icon::FolderPlus, "layer.new_folder", tr!("New folder above the active layer (move layers in under it with Up and Down)")), ] { let (r, resp) = child.allocate_exact_size(vec2(TARGET, TARGET), Sense::click()); if resp.hovered() { @@ -1097,6 +1098,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.run(id, json!({})); } } + child.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if ui.add(egui::Button::new(tr!("+ Layer")).truncate()).named(tr!("New layer")).on_hover_text(tr!("New layer")).clicked() { + app.run("layer.new", json!({})); + } + if ui.add_enabled(layers.len() > 1, egui::Button::new(tr!("Delete")).truncate()).named(tr!("Delete layer")).on_hover_text(tr!("Delete the active layer")).clicked() { + app.request("layer.delete", json!({})); + } + }); } // Horizontal scrollbar under the frames: the thumb is the visible part of the timeline. From 48501f227c279977721edeb39e920b7e575f2c57 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:11:14 -0700 Subject: [PATCH 077/192] fix(doc): template outlines take one rectangle (clippy) (M8) --- crates/doc/src/templates.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/templates.rs b/crates/doc/src/templates.rs index 1e2a6bf8..d809c45c 100644 --- a/crates/doc/src/templates.rs +++ b/crates/doc/src/templates.rs @@ -54,8 +54,8 @@ fn line(d: &mut Document, name: &str, a: (f32, f32), b: (f32, f32), color: u32, element(d, name, Affine::IDENTITY, Shape { path: Arc::new(p), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false }) } -/// A stroked rectangle outline. -fn outline(d: &mut Document, name: &str, x: f32, y: f32, w: f32, h: f32, color: u32, width: f32) -> Arc { +/// A stroked rectangle outline, `(x, y, w, h)`. +fn outline(d: &mut Document, name: &str, (x, y, w, h): (f32, f32, f32, f32), color: u32, width: f32) -> Arc { element(d, name, Affine::IDENTITY, Shape { path: Arc::new(Path::rect(x, y, w, h)), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false }) } @@ -85,7 +85,7 @@ fn banner(width: u32, height: u32) -> Document { let mut d = blank(width, height, 24.0); let (w, h) = (width as f32, height as f32); let m = (w.min(h) * 0.1).round(); - let guides = vec![outline(&mut d, "Safe area", m, m, w - 2.0 * m, h - 2.0 * m, GUIDE, 1.0), outline(&mut d, "Edge", 0.5, 0.5, w - 1.0, h - 1.0, GUIDE_SOFT, 1.0)]; + let guides = vec![outline(&mut d, "Safe area", (m, m, w - 2.0 * m, h - 2.0 * m), GUIDE, 1.0), outline(&mut d, "Edge", (0.5, 0.5, w - 1.0, h - 1.0), GUIDE_SOFT, 1.0)]; let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)]; layers.extend(drawing_layers(&mut d, &["Call to action", "Text", "Artwork"], FRAMES)); let bg = element(&mut d, "background", Affine::IDENTITY, Shape::filled(Path::rect(0.0, 0.0, w, h), Paint::Solid(Rgba::hex(0xeef2f7)))); @@ -110,7 +110,7 @@ fn social_square() -> Document { let mut d = blank(1080, 1080, 30.0); let s = 1080.0; let m = 60.0; - let mut guides = vec![outline(&mut d, "Safe margin", m, m, s - 2.0 * m, s - 2.0 * m, GUIDE, 2.0)]; + let mut guides = vec![outline(&mut d, "Safe margin", (m, m, s - 2.0 * m, s - 2.0 * m), GUIDE, 2.0)]; for (i, t) in [s / 3.0, s * 2.0 / 3.0].into_iter().enumerate() { guides.push(line(&mut d, &format!("Third {}", i + 1), (t, 0.0), (t, s), GUIDE_SOFT, 1.0)); guides.push(line(&mut d, &format!("Third {}", i + 3), (0.0, t), (s, t), GUIDE_SOFT, 1.0)); @@ -132,7 +132,7 @@ fn storyboard() -> Document { let (w, h) = (1920.0, 1080.0); let safe = |d: &mut Document, name: &str, keep: f32, color: u32| { let (mx, my) = (w * (1.0 - keep) / 2.0, h * (1.0 - keep) / 2.0); - outline(d, name, mx, my, w - 2.0 * mx, h - 2.0 * my, color, 2.0) + outline(d, name, (mx, my, w - 2.0 * mx, h - 2.0 * my), color, 2.0) }; let guides = vec![ safe(&mut d, "Action safe", 0.93, GUIDE), From 35dbe30f60d49829e2ce426d3c0b9230cc55bcf9 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:12:11 -0700 Subject: [PATCH 078/192] docs: ADR 0065 templates, SVG into the Library and drops on the timeline; roadmap, changelog, attribution (M8) --- ATTRIBUTION.md | 1 + CHANGELOG.md | 19 ++++ ...e-desktop-recent-files-and-start-screen.md | 8 +- ...o-the-library-and-drops-on-the-timeline.md | 100 ++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 6 +- 6 files changed, 128 insertions(+), 7 deletions(-) create mode 100644 docs/adr/0065-templates-svg-into-the-library-and-drops-on-the-timeline.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index aab3a22c..0b52071b 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -28,6 +28,7 @@ shaders or SDK code). | Library symbol-kind marks, selection handles, timeline marks | UI | AniCraft contributors | Original work, drawn in code (`src/panels.rs`, `src/timeline.rs`, `src/stage.rs`) | MIT OR Apache-2.0 | | Sample animation (ball, star, sun, hills, sky) | First launch, tests, CLI `--sample` | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`) | MIT OR Apache-2.0 | | Interactive sample (menu, Play button, spinner) | File › New from Sample (`which: interactive`), Test Movie tests and screenshots | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`, `interactive`) | MIT OR Apache-2.0 | +| Built-in templates (Leaderboard and Rectangle banners, Social square, Storyboard 16:9, Character turnaround, Lip-sync mouth chart: guides, layers, labels and placeholder mouth shapes) | File › New from Template and the start screen (ADR 0065) | AniCraft contributors | Original work, generated in code (`crates/doc/src/templates.rs`); sizes and safe areas follow public conventions (the IAB's 728 × 90 and 300 × 250 ad units, EBU R 95's 93 % action-safe and 90 % title-safe areas), the mouth set the common phoneme groups animators use | MIT OR Apache-2.0 | | Colour theme | UI | AniCraft contributors | Original work (`src/theme.rs`) | MIT OR Apache-2.0 | | `docs/brand/artcraft-logo-white.png` | ArtCraft brand mark (wordmark, light ink for dark backgrounds) | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`), not open source | | `docs/brand/artcraft-logo-white.svg` | ArtCraft brand mark (wordmark, light ink for dark backgrounds) | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`), not open source | diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e517961..724ca7d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ ## Unreleased +* **Templates, SVG into the Library, and drops on the timeline** (ADR 0065, M8). + * **File › New from Template** and the start screen's new **Templates** row: Leaderboard banner + 728 × 90, Rectangle banner 300 × 250, Social square 1080 × 1080 at 30 fps, Storyboard 16:9 (six + labelled panels), Character turnaround and a Lip-sync mouth chart. Each has named layers and + guides on a locked guide layer (they show while drawing and never export). They open as new, + untitled documents with a drawing layer active. + * **File › Save as Template** keeps the open document, with a picture, under a name and a + category in your settings folder. It shows under "My templates" on the start screen, with + Delete. Replacing or deleting a template asks first. + * **SVG into the Library**: dropping an SVG on the Library, or File › Import › Import to Library, + makes one graphic symbol named after the file, in the folder under the pointer. + * **Drops on the timeline**: a sound dropped on a layer's frame goes onto that keyframe. An image + or SVG goes onto that layer at that frame, in a new keyframe if needed. Either way it is one undo + step, and a highlight shows the cell. Locked layers, folders and the camera say why they won't + take it. + * The timeline's layer footer keeps its Move Down button in every language. + * Headless: `file.new_from_template`, `file.templates`, `file.save_as_template`, + `file.delete_template`, and `file.drop` with `to: "timeline"`. + * Exact drop positions from the desktop still wait for winit 0.31 (eframe 0.37 is still on 0.30). * **Test Movie in its own window, and opening documents on macOS** (ADR 0062, M8). * **Control › Test Movie** (Ctrl+Enter) now opens in a **window of its own** on the desktop, as in Animate. It is sized to the stage at 100 % (smaller if that wouldn't fit the diff --git a/docs/adr/0059-files-from-the-desktop-recent-files-and-start-screen.md b/docs/adr/0059-files-from-the-desktop-recent-files-and-start-screen.md index 34f10284..9fd20619 100644 --- a/docs/adr/0059-files-from-the-desktop-recent-files-and-start-screen.md +++ b/docs/adr/0059-files-from-the-desktop-recent-files-and-start-screen.md @@ -79,7 +79,9 @@ engine, and two of them keep state (the recent list, its pictures) between sessi ## Not yet -* Exact desktop drop positions (winit 0.31), and dropping folders of images as a sequence. -* SVG into the Library (as a graphic symbol), and dropping onto the timeline (a layer and frame). +* Exact desktop drop positions (winit 0.31; eframe 0.36 and 0.37 are on winit 0.30, ADR 0065), and + dropping folders of images as a sequence. +* ~~SVG into the Library, dropping onto the timeline, templates on the start screen~~: done in + ADR 0065. * Opening several dropped documents (needs document tabs), and reopening the last document at start. -* Templates on the start screen, and thumbnails that follow the poster frame. +* Thumbnails that follow the poster frame. diff --git a/docs/adr/0065-templates-svg-into-the-library-and-drops-on-the-timeline.md b/docs/adr/0065-templates-svg-into-the-library-and-drops-on-the-timeline.md new file mode 100644 index 00000000..0ced0f20 --- /dev/null +++ b/docs/adr/0065-templates-svg-into-the-library-and-drops-on-the-timeline.md @@ -0,0 +1,100 @@ +# ADR 0065: Templates, SVG into the Library, and drops on the timeline + +* Status: accepted (2026-11-11) +* Relates to: ADR 0004 (destructive actions), ADR 0021 (SVG clips and masks), ADR 0040 + (interface languages), ADR 0050 and 0053 (Library folders, Place on Stage), ADR 0059 (files + from the desktop, recent files, start screen), roadmap M8 + +## Context + +ADR 0059 left four things next: templates on the start screen, SVG into the Library, drops on the +timeline, and exact desktop drop positions. Artists coming from Animate start banners, social posts +and storyboards from templates, keep their own studio setups as templates, drag an SVG into the +Library to get a symbol, and drag a sound onto a frame of the timeline. + +## Decision + +1. **Built-in templates are code, not files** (`anicraft_doc::templates`, beside the sample + documents). Six, all original: Leaderboard banner 728 × 90 and Rectangle banner 300 × 250 (24 fps, + 15 s, the safe area a tenth of the short edge in), Social square 1080 × 1080 at 30 fps (safe + margin, thirds), Storyboard 16:9 (six labelled 2-second panels on a Panels layer, action-safe + 93 % and title-safe 90 %), Character turnaround (five views on lines a head apart, eight heads + tall), and Lip-sync mouth chart (a Mouth graphic symbol with ten labelled keyframes holding + placeholder shapes, placed at Single Frame on a face guide). Guides sit on a locked guide layer, + so they show while drawing and never export. Nothing binary is committed, every template is + tested to build, open, draw on, save and reopen, and they cost under 0.1 ms to build. When a + template opens, the first unlocked drawing layer is active, so drawing works at once. +2. **User templates are plain `.anicraft` files with a picture**: + `//.anicraft` and `.png` in the settings folder (or + `ANICRAFT_TEMPLATES_DIR`). We chose folders over a manifest because they need no new format, + survive a copy to another computer, and can be tidied in a file browser. Category and name must + be valid file names everywhere: at most 64 characters, none of `/ \ : * ? " < > |`, no control + characters, no leading or trailing dot, no Windows device names. They are refused with a reason, + never silently changed. As with recent files, the engine never looks for the folder: the shell + passes it to `file.save_as_template`, `file.templates` and `file.delete_template`. + `file.new_from_template` takes a built-in `template` id or any `.anicraft` `path`, and opens it + untitled (Save asks for a name and never writes over the template). It isn't a recent file, and + it asks first over unsaved work, like New. Replacing a template and deleting one are irreversible + and always confirm (ADR 0004). The document itself doesn't change when it is saved as a template. +3. **A template's picture shows its guides.** `cmds_template::picture_png` renders the first frame + with the CPU oracle at the recent files' 240 × 135, with guide layers drawn as artwork and their + lines widened by 1.5 ÷ scale, so a 2-pixel guide on a 1920-wide stage still reads. That takes + 0.4 to 1.1 ms per template. Built-in pictures are rendered once per run; user pictures are + written on save. +4. **File menu and start screen.** New from Template sits under New from Sample and Save as Template + under Save As, in registry order, as in Animate. New from Template opens the start screen + scrolled to its Templates row: the built-in tiles, then "My templates" with Delete. One screen + picks everything, and Esc goes back. Save as Template is a small dialog with the picture, the + name, the category (the categories used before offered as chips), where it will be saved, and a + note when it will replace one. The built-in names and descriptions are English in the engine, + listed with `tr_noop!` in `src/templates.rs` for the catalogs, and translated where drawn. The + default category is offered in the interface language because it becomes a folder name. On the + web there is no folder: the built-in templates work, and Save as Template says why it isn't + there. +5. **SVG into the Library is one graphic symbol.** `file.import_to_library` and drops on the Library + take `.svg`. The result is a graphic symbol named after the file (a free name, numbered), + holding the drawing's shapes with the registration point at its centre (as Convert to Symbol + puts it), and its clip and mask layers inside it (ADR 0021). A drop puts it into the folder under + the pointer. +6. **Drops on the timeline** (`file.drop` with `to: "timeline"`, `layer`, `frame`; one undo step) + move the playhead and the active layer to the drop. A **sound** goes onto the keyframe the frame + is in, as Animate puts it, and a keyframe is made only past the layer's end. One sound per drop, + since a keyframe holds one. **Images and SVGs** go into a keyframe **starting** at that frame, + made there when the frame is inside another keyframe's span. It is made as Insert Keyframe makes + it, keeping what the frame showed, so the art before and after stays. The new artwork is centred + in the view. A drawing that needs several layers or masks can't sit on one layer, so it goes in + as a graphic symbol instance (and into the Library). We don't add layers the user didn't drop + on. Folders, the camera, armature layers and locked layers refuse, saying why, and nothing + changes. The shell records each timeline row and the frame mapping as it draws + (`drop::TimelineGeo`). The highlight outlines the row and fills the frame's cell, with "Place … on + Star at frame 9" or "Put whoosh.wav on Star's keyframe at frame 9", or the refusal in red. Over + the layer column a drop means that layer at the playhead. +7. **Exact desktop drop positions stay out.** winit 0.30.13 is the version eframe 0.36 uses, and + eframe 0.37 too. It reports `HoveredFile`/`DroppedFile` with a path and no position, and Windows + and macOS send no pointer moves while dragging. ADR 0059's wait for the first pointer move after + the drop stays. When eframe moves to winit 0.31 (which carries drag positions), `drop::frame` + can read them, and the timeline highlight will follow the pointer on the desktop as it already + does in the browser. +8. **The layer footer fits every language.** Its icon buttons (New folder, Up, Down) are laid out + first from the right edge of the layer column, and "+ Layer" and Delete share the rest, + shortening with an ellipsis if they have to. Before, in the pseudo-locale the longer text pushed + the Down chevron off the column. Each keeps its full accessible name and tooltip. + +## Consequences + +* Templates, SVG symbols and timeline drops work headless (CLI, MCP) like every command. The new + commands are in the `file` namespace, which plug-ins may not call. +* `file.*` commands are left out of `panic_hunt_every_command` because they touch the disk. The + template and timeline-drop commands have their own hostile-params test, writing only to a + temporary folder. Screenshot and test runs never touch the real templates folder. +* A template is only as portable as the files it refers to. Bitmaps and sounds are inside the + `.anicraft`, so it carries everything. + +## Not yet + +* Template descriptions for user templates, renaming or moving a template between categories, and + a "Show in folder" button. +* Exact desktop drop positions (winit 0.31), dropping folders of images as a sequence, and a sound + dropped across several layers. +* Previews that play a template's animation, and more built-in templates (presentation, mobile + banners, HTML5 canvas ads with click tags). diff --git a/docs/adr/README.md b/docs/adr/README.md index 20f3fcf8..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0065 | (M8 templates and drops) | Templates, SVG into the Library, drops on the timeline | diff --git a/docs/roadmap.md b/docs/roadmap.md index c3221216..1da2cb22 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,7 +16,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. Not yet: exact drop positions on the desktop (winit 0.30 gives none during a drag; a drop waits for the first pointer move, else lands mid-view), SVG into the Library, drops on the timeline, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. **Templates, SVG into the Library and drops on the timeline** (ADR 0065): six built-in templates made in code (banners 728 × 90 and 300 × 250, social square 1080 × 1080 at 30 fps, storyboard 16:9 panels, character turnaround, lip-sync mouth chart) with guides on a locked guide layer, on the start screen and File › New from Template; File › Save as Template keeps the document with a picture in the settings folder by category (replacing and deleting confirm); an SVG dropped on or imported to the Library becomes one graphic symbol named after the file, in the folder under the pointer; a sound dropped on a layer's frame goes onto that keyframe, an image or SVG onto that layer in a keyframe made there if needed, one undo step, with a highlight on the cell. Not yet: exact drop positions on the desktop (eframe 0.36 and 0.37 are on winit 0.30, which gives none during a drag; a drop waits for the first pointer move, else lands mid-view), user template descriptions and renaming, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | @@ -40,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | -| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. | +| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. | ## Releases @@ -61,7 +61,7 @@ titled with its milestone. | M5 | Audio layers: import, waveform, playback sync | timeline, layers | | M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | -| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); next: the accessibility follow-ups | `.anicraft` format, session, AccessKit in eframe | +| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); next: the accessibility follow-ups | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and ActionScript (on M6's plug-in host). From 109fed163778ffbd216a2fc7be300debac4d835f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:06:03 -0700 Subject: [PATCH 079/192] docs(adr): reserve ADR 0066 for dynamic and input text fields (M5) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..e86f0376 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0066 | M5 text fields (in progress) | Dynamic and input text fields | From 538142057dc5b6786542563746a69d756162c66c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:25:33 -0700 Subject: [PATCH 080/192] feat(text): dynamic and input text fields in the model, player, scripts and XFL import (M5) --- crates/actions/src/as3/ir.rs | 17 + crates/actions/src/as3/lower.rs | 31 +- crates/actions/src/as3/run.rs | 10 + crates/actions/src/as3/tests.rs | 51 +++ crates/doc/src/eval.rs | 110 ++++- crates/doc/src/field.rs | 390 ++++++++++++++++++ crates/doc/src/field_tests.rs | 182 ++++++++ crates/doc/src/lib.rs | 144 +++++++ crates/doc/src/player.rs | 259 +++++++++++- crates/doc/src/player_tests.rs | 106 +++++ crates/engine/src/cmds_actions.rs | 11 +- crates/engine/src/cmds_text.rs | 198 ++++++++- crates/engine/src/find_tests.rs | 2 +- crates/engine/src/player.rs | 61 ++- crates/engine/src/tests.rs | 4 +- crates/engine/tests/xfl_corpus.rs | 7 +- crates/render/src/html_tests.rs | 2 + crates/svg/src/text.rs | 1 + crates/text/src/lib.rs | 143 ++++++- crates/xfl/src/import.rs | 3 +- crates/xfl/src/text.rs | 127 +++++- crates/xfl/src/text_tests.rs | 31 +- crates/xfl/tests/corpus.rs | 24 +- .../tests/corpus/text/golden/frame-000.png | Bin 1730 -> 2128 bytes .../tests/corpus/textfields/DOMDocument.xml | 76 ++++ .../corpus/textfields/golden/frame-000.png | Bin 0 -> 2741 bytes .../tests/corpus/textfields/textfields.xfl | 1 + 27 files changed, 1911 insertions(+), 80 deletions(-) create mode 100644 crates/doc/src/field.rs create mode 100644 crates/doc/src/field_tests.rs create mode 100644 crates/xfl/tests/corpus/textfields/DOMDocument.xml create mode 100644 crates/xfl/tests/corpus/textfields/golden/frame-000.png create mode 100644 crates/xfl/tests/corpus/textfields/textfields.xfl diff --git a/crates/actions/src/as3/ir.rs b/crates/actions/src/as3/ir.rs index 327e4aa3..ec3f1978 100644 --- a/crates/actions/src/as3/ir.rs +++ b/crates/actions/src/as3/ir.rs @@ -371,6 +371,10 @@ pub enum Prop { MouseY, /// The instance name. Name, + /// A text field's text, and its length in UTF-16 units (ADR 0066). Only as `field.text` and + /// `field.length`: a bare `text` is a variable. + Text, + Length, } impl Prop { @@ -392,6 +396,15 @@ impl Prop { _ => return None, }) } + /// A property read or set as `instance.m`: those [`Prop::from_name`] knows, and a text + /// field's `text` and `length`. + pub fn from_member(s: &str) -> Option { + match s { + "text" => Some(Prop::Text), + "length" => Some(Prop::Length), + _ => Prop::from_name(s), + } + } pub fn name(self) -> &'static str { match self { Prop::X => "x", @@ -407,6 +420,8 @@ impl Prop { Prop::MouseX => "mouseX", Prop::MouseY => "mouseY", Prop::Name => "name", + Prop::Text => "text", + Prop::Length => "length", } } /// The instance property a script may also set. @@ -518,6 +533,8 @@ pub enum LValue { Var { n: String }, /// An instance property. Prop { at: Place, p: Property }, + /// A text field's text (`field.text = …`, `field.appendText(…)` as `+=`). + Text { at: Place }, } /// An expression. diff --git a/crates/actions/src/as3/lower.rs b/crates/actions/src/as3/lower.rs index a8519622..385b682c 100644 --- a/crates/actions/src/as3/lower.rs +++ b/crates/actions/src/as3/lower.rs @@ -244,6 +244,15 @@ impl<'a> Lower<'a> { if matches!(&obj.kind, E::Name(o) if o == "Math") { return self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }); } + // `field.appendText(v)` is `field.text += v` (ADR 0066). + if m == "appendText" { + let [arg] = args else { + self.problem(pos, "`appendText` takes one argument, the text to add"); + return None; + }; + let (at, v) = (self.field_place(obj, u), self.expr(arg, u)); + return Some(IS::Do { x: X::Set { to: LValue::Text { at: at? }, op: Some(BinOp::Add), v: Box::new(v?) } }); + } if Method::from_name(m).is_none() && m != "addEventListener" && m != "removeEventListener" { self.problem(pos, format!("calling `{m}` isn't supported (timeline methods such as `play()` and `gotoAndStop()`, `addEventListener` and `removeEventListener` are)")); return None; @@ -590,6 +599,17 @@ impl<'a> Lower<'a> { Some(at) } + /// The text field a script names (`score_txt`, `panel.name_txt`): an instance, not the + /// stage or a timeline (`this` is one only if it is a field, which a frame script's isn't). + fn field_place(&mut self, e: &Expr, u: &Unit) -> O { + let at = self.place(e, u)?; + if at.base == Base::Stage || (at.base == Base::This && at.path.is_this()) { + self.problem(e.pos, "this isn't a text field; name the field by its instance name, as in `score_txt.text`"); + return None; + } + Some(at) + } + /// Whether an expression names an instance rather than a value (for `==` between instances). fn is_instance(&self, e: &Expr, u: &Unit) -> bool { match &e.kind { @@ -628,9 +648,10 @@ impl<'a> Lower<'a> { self.free(n, e.pos, false); Some(LValue::Var { n: n.clone() }) } + E::Member(o, m) if m == "text" => Some(LValue::Text { at: self.field_place(o, u)? }), E::Member(o, m) => { - let Some(p) = Prop::from_name(m) else { - self.problem(e.pos, format!("setting `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX and scaleY are)")); + let Some(p) = Prop::from_member(m) else { + self.problem(e.pos, format!("setting `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY and a text field's text are)")); return None; }; let Some(p) = p.settable() else { @@ -841,11 +862,11 @@ impl<'a> Lower<'a> { self.problem(e.pos, format!("reading `{m}` of a value isn't supported yet")); return None; } - let Some(p) = Prop::from_name(m) else { - self.problem(e.pos, format!("reading `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY, currentFrame, totalFrames, currentLabel, mouseX, mouseY and name are)")); + let Some(p) = Prop::from_member(m) else { + self.problem(e.pos, format!("reading `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY, currentFrame, totalFrames, currentLabel, mouseX, mouseY, name, and a text field's text and length are)")); return None; }; - let at = self.place(o, u)?; + let at = if matches!(p, Prop::Text | Prop::Length) { self.field_place(o, u)? } else { self.place(o, u)? }; if at.base == Base::Stage && !matches!(p, Prop::MouseX | Prop::MouseY) { self.problem(e.pos, format!("`stage.{m}` isn't supported yet")); return None; diff --git a/crates/actions/src/as3/run.rs b/crates/actions/src/as3/run.rs index 29900460..262237fe 100644 --- a/crates/actions/src/as3/run.rs +++ b/crates/actions/src/as3/run.rs @@ -49,6 +49,8 @@ pub trait World { fn get(&mut self, at: &Place, p: Prop) -> Result; /// Sets an instance property. fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option>; + /// Sets a text field's text (ADR 0066). + fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option>; fn trace(&mut self, line: String); /// A timeline variable's value, and writing one (the world knows its type). fn read(&mut self, name: &str) -> Result; @@ -347,6 +349,7 @@ impl Vm<'_> { }; self.w.get(at, prop).map_err(|message| Stop::Error { line: self.line, message }) } + LValue::Text { at } => self.w.get(at, Prop::Text).map_err(|message| Stop::Error { line: self.line, message }), } } @@ -373,6 +376,13 @@ impl Vm<'_> { self.w.set(at, *p, n).map_err(|e| lift(self.line, e))?; Ok(v) } + LValue::Text { at } => { + if matches!(v, Value::Null | Value::Undefined) { + return self.err(format!("`text` is set to text, not {}", v.text())); + } + self.w.set_text(at, v.text()).map_err(|e| lift(self.line, e))?; + Ok(v) + } } } diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs index 08accc66..2cc2e506 100644 --- a/crates/actions/src/as3/tests.rs +++ b/crates/actions/src/as3/tests.rs @@ -30,6 +30,8 @@ struct Mock { rng: u32, key: Option, frame: u32, + /// Text fields' text, by name. + texts: BTreeMap, } impl World for Mock { @@ -48,6 +50,10 @@ impl World for Mock { Prop::CurrentFrame => Value::Num(f64::from(self.frame + 1)), Prop::Name => Value::str(&at.to_string()), Prop::Visible => Value::Bool(true), + Prop::Text | Prop::Length => { + let t = self.texts.get(&at.path.0).ok_or_else(|| format!("“{at}” isn't a text field"))?; + if p == Prop::Text { Value::str(t) } else { Value::Num(text_len(t) as f64) } + } p => Value::Num(self.props.get(&(at.path.0.clone(), p.name())).copied().unwrap_or(0.0)), }) } @@ -65,6 +71,14 @@ impl World for Mock { self.props.insert((at.path.0.clone(), name), v); Ok(()) } + fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option> { + if !self.texts.contains_key(&at.path.0) { + return Err(Some(format!("“{at}” isn't a text field"))); + } + self.log.push(format!("text {at} = {text}")); + self.texts.insert(at.path.0.clone(), text); + Ok(()) + } fn trace(&mut self, line: String) { self.log.push(line); } @@ -500,3 +514,40 @@ fn a_full_budget_runs_quickly() { assert_eq!(r, Err(Stop::Fuel)); assert!(ms < 500.0, "{ms} ms"); } + +#[test] +fn scripts_set_append_and_read_text_fields() { + let src = r#" + var n:int = 3; + score_txt.text = "Score: " + n; + score_txt.appendText("!"); + score_txt.text += "?"; + trace(score_txt.text, score_txt.length); + panel.name_txt.text = String(score_txt.length * 2); + var text:String = "a variable named text"; + trace(text); + "#; + let c = ok(src); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + m.texts.insert("score_txt".into(), String::new()); + m.texts.insert("panel.name_txt".into(), "x".into()); + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + assert_eq!(r, Ok(())); + assert_eq!(m.texts["score_txt"], "Score: 3!?"); + assert_eq!(m.texts["panel.name_txt"], "20"); + assert!(m.log.contains(&"Score: 3!? 10".to_string()), "{:?}", m.log); + assert!(m.log.contains(&"a variable named text".to_string()), "a bare `text` stays a variable"); + // Setting null stops the script with a message; `this.text` and the stage aren't fields. + let (_, r, _) = { + let c = ok("score_txt.text = null;"); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + m.texts.insert("score_txt".into(), String::new()); + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + ((), r, ()) + }; + assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("not null")), "{r:?}"); + assert!(err("this.text = 'x';").2.contains("isn't a text field")); + assert!(err("stage.text = 'x';").2.contains("text field") || err("stage.text = 'x';").2.contains("stage")); + assert!(err("a_txt.appendText();").2.contains("one argument")); + assert!(err("a_txt.length = 3;").2.contains("can only be read")); +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index c1b35195..a17dcd6f 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -430,6 +430,8 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut // In the player, a symbol instance has its own path, and maybe properties a script set. let child = match (&el.kind, play) { (ElementKind::Symbol { .. }, Some(p)) => Some(p.child(el.id)), + // So is a dynamic or input text field (ADR 0066). + (ElementKind::Text(t), Some(p)) if t.field.is_some() => Some(p.child(el.id)), _ => None, }; let set; @@ -478,23 +480,36 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut }, }); } - ElementKind::Text(t) => out.items.push(DisplayItem { - path: t.outline.clone(), - transform: xf, - fill: Some(Paint::Solid(t.color)), - stroke: None, - fill_rule: FillRule::NonZero, - color, - layer: root_layer, - element: root_el, - outline: layer_outline, - clip, - masks, - guide, - group: cx.group, - image: None, - smooth: true, - }), + ElementKind::Text(t) => { + let item = |path: Arc, transform: Affine, fill: Option, stroke: Option, clip: Option, masks: Option| DisplayItem { + path, + transform, + fill, + stroke, + fill_rule: FillRule::NonZero, + color, + layer: root_layer, + element: root_el, + outline: layer_outline, + clip, + masks, + guide, + group: cx.group, + image: None, + smooth: true, + }; + match &t.field { + // Mask artwork: a field's text masks; its box and border don't. + Some(f) if masks.is_none() => { + let live = child.as_ref().map(|c| (c.state.fields.get(&c.path), c.state.focus.as_deref() == Some(c.path.as_slice()))); + field_items(t, f, live, xf, clip, out, item); + } + _ => { + let path = child.as_ref().and_then(|c| c.state.fields.get(&c.path)).and_then(|s| s.look.as_ref()).map_or_else(|| t.outline.clone(), |l| l.outline.clone()); + out.items.push(item(path, xf, Some(Paint::Solid(t.color)), None, clip, masks)); + } + } + } ElementKind::Camera => {} ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => { let Some(sym) = doc.symbol(*symbol) else { continue }; @@ -536,6 +551,67 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut } } +/// The highlight behind selected text in a focused field. +pub const SELECTION: Rgba = Rgba::new(0.62, 0.78, 1.0, 1.0); + +/// A dynamic or input field's items (ADR 0066): its background, its text cut to its box, the +/// selection and caret when it has the keyboard, and its border. `live` is its state in the +/// player (and whether it is focused); without one, it shows its authored outline. +fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option<&crate::field::FieldState>, bool)>, xf: Affine, clip: Option, out: &mut DisplayList, item: impl Fn(Arc, Affine, Option, Option, Option, Option) -> DisplayItem) { + let (w, h) = (t.box_width.max(0.0), t.box_height.max(0.0)); + let rect = Arc::new(Path::rect(0.0, 0.0, w, h)); + if f.background { + out.items.push(item(rect.clone(), xf, Some(Paint::Solid(f.background_color)), None, clip, None)); + } + // The box clips what is inside it. + let inner = out.clip_parents.len() as u32; + out.clip_parents.push(clip); + out.items.push(item(rect.clone(), xf, Some(Paint::Solid(Rgba::BLACK)), None, clip, Some(inner))); + let (state, focused) = live.unwrap_or((None, false)); + let scroll = state.map_or(anicraft_geom::Vec2::ZERO, |s| s.scroll); + let text_xf = xf.mul(&Affine::translate(-scroll.x, -scroll.y)); + let look = state.and_then(|s| s.look.as_deref()); + // The selection, under the text. + if let (true, Some(st), Some(look)) = (focused, state, look) { + let (a, b) = st.selection(); + if a != b { + for (row, l) in look.lines.iter().enumerate() { + let (from, to) = (a.max(l.start), b.min(l.end)); + if from > to || (from == to && !(a <= l.end && b > l.end)) { + continue; + } + let (x0, x1) = (l.x_at(from), if b > l.end { l.x_at(l.end) + t.size * 0.25 } else { l.x_at(to) }); + let y = row as f32 * look.line_height; + let r = Path::rect(crate::FIELD_GUTTER + x0, crate::FIELD_GUTTER + y, (x1 - x0).max(0.0), look.line_height); + out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(SELECTION)), None, Some(inner), None)); + } + } + } + // The text: laid out by the player when it changed, else the authored outline (a field whose + // text changed but couldn't be laid out shows none). + let outline = match (state.and_then(|s| s.text.as_ref()), look) { + (_, Some(l)) => Some(l.outline.clone()), + (None, None) => Some(t.outline.clone()), + (Some(_), None) => None, + }; + if let Some(path) = outline { + out.items.push(item(path, text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)); + } + // The caret, in an input field with the keyboard and nothing selected. + if let (true, Some(st), crate::TextKind::Input) = (focused, state, f.kind) + && st.caret == st.anchor + { + let (at, lh) = look.map_or((anicraft_geom::Vec2::ZERO, t.size * 1.2), |l| (l.caret_at(st.caret), l.line_height)); + let r = Path::rect(crate::FIELD_GUTTER + at.x - 0.5, crate::FIELD_GUTTER + at.y, 1.0, lh); + out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)); + } + if f.border { + let mut s = Stroke::new(f.border_color, 1.0); + s.style.join = crate::Join::Miter; + out.items.push(item(rect, xf, None, Some(s), clip, None)); + } +} + /// A shape inside a 9-slice instance (ADR 0055): its outline placed by its own transform, then /// cut at the guides and mapped piecewise; drawn by the instance's transform without its scale. /// The stroke keeps its width (times the shape's own scale inside the symbol); gradients follow diff --git a/crates/doc/src/field.rs b/crates/doc/src/field.rs new file mode 100644 index 00000000..b3eb7685 --- /dev/null +++ b/crates/doc/src/field.rs @@ -0,0 +1,390 @@ +//! Text fields while a movie plays (ADR 0066): what a dynamic or input field holds, where its +//! caret and selection are, and the editing that keys and the pointer do to it. +//! +//! Everything here is pure data and pure functions, like the rest of the player: the same field, +//! look and keys always give the same text, caret and selection. Laying text out needs the +//! fonts, which live a layer above (`anicraft-text`), so the player asks its host for a +//! [`FieldLook`] whenever a field's text changes and keeps it in the state; drawing a state then +//! needs nothing else. + +use crate::{FIELD_GUTTER, LineType, MAX_FIELD_CHARS, TextBlock, TextField, TextKind}; +use anicraft_geom::{Path, Vec2}; +use std::sync::Arc; + +/// One laid-out line's characters and caret places (indices count `char`s of the shown text). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CaretLine { + /// The first character on the line and the boundary after its last. + pub start: u32, + pub end: u32, + /// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending; `x` from + /// the text's left edge (the box's, less the gutter). + pub stops: Vec<(u32, f32)>, +} + +impl CaretLine { + /// The caret's x at boundary `i`. + pub fn x_at(&self, i: u32) -> f32 { + let mut x = self.stops.first().map_or(0.0, |s| s.1); + for &(c, sx) in &self.stops { + if c > i { + break; + } + x = sx; + } + x + } + + /// The boundary nearest `x`. + pub fn index_at(&self, x: f32) -> u32 { + let mut best = (self.start, f32::INFINITY); + for &(c, sx) in &self.stops { + let d = (sx - x).abs(); + if d < best.1 { + best = (c, d); + } + } + best.0.clamp(self.start, self.end) + } +} + +/// A field's text laid out: its outline (in the box's space, the gutter applied, as a text +/// block's outline is) and where the caret can stand. +#[derive(Clone, Debug, PartialEq)] +pub struct FieldLook { + pub outline: Arc, + /// Top line first; never empty. + pub lines: Arc<[CaretLine]>, + /// From one line's top to the next's. + pub line_height: f32, + /// The laid-out text's size (it may be bigger than the box, which clips it). + pub width: f32, + pub height: f32, +} + +impl FieldLook { + /// The line holding boundary `i`: the last that starts at or before it. + pub fn line_of(&self, i: u32) -> usize { + let mut at = 0; + for (n, l) in self.lines.iter().enumerate() { + if l.start <= i { + at = n; + } else { + break; + } + } + at + } + + /// The caret's place at boundary `i`: x from the text's left, and the line's top. + pub fn caret_at(&self, i: u32) -> Vec2 { + let n = self.line_of(i); + let x = self.lines.get(n).map_or(0.0, |l| l.x_at(i)); + Vec2::new(x, n as f32 * self.line_height) + } + + /// The boundary nearest a point in the text's space. + pub fn index_at(&self, p: Vec2) -> u32 { + let h = self.line_height.max(1e-3); + let row = if p.y.is_finite() { (p.y / h).floor().max(0.0) as usize } else { 0 }; + let row = row.min(self.lines.len().saturating_sub(1)); + self.lines.get(row).map_or(0, |l| l.index_at(p.x)) + } +} + +/// What a field holds while the movie plays. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FieldState { + /// Its text once a script or the viewer changed it; `None`: the timeline's own (so a + /// keyframe with other words still shows them). + pub text: Option, + /// The text laid out (the host's work); `None` while it shows the authored outline. + pub look: Option>, + /// The caret and the other end of the selection (character boundaries; equal: nothing + /// selected). + pub caret: u32, + pub anchor: u32, + /// How far the text has scrolled to keep the caret in view (pixels, never negative). + pub scroll: Vec2, +} + +impl FieldState { + /// The field's text: what was set, or the block's own. + pub fn value<'a>(&'a self, block: &'a TextBlock) -> &'a str { + self.text.as_deref().unwrap_or(&block.text) + } + + /// The selected range, low end first. + pub fn selection(&self) -> (u32, u32) { + (self.caret.min(self.anchor), self.caret.max(self.anchor)) + } + + /// The selected text. + pub fn selected(&self, block: &TextBlock) -> String { + let (a, b) = self.selection(); + slice(self.value(block), a, b).to_string() + } +} + +/// The byte offset of character boundary `i` in `s` (its end when past it). +pub fn byte_at(s: &str, i: u32) -> usize { + s.char_indices().nth(i as usize).map_or(s.len(), |(b, _)| b) +} + +/// The characters of `s` from boundary `a` to `b`. +pub fn slice(s: &str, a: u32, b: u32) -> &str { + let (x, y) = (byte_at(s, a.min(b)), byte_at(s, a.max(b))); + s.get(x..y).unwrap_or("") +} + +/// Characters in `s`, as boundaries count them. +pub fn chars(s: &str) -> u32 { + s.chars().count().min(u32::MAX as usize) as u32 +} + +/// Text a script sets, as a field keeps it: at most [`MAX_FIELD_CHARS`] characters, with `\r` +/// and `\r\n` (ActionScript's line ends) as line breaks. +pub fn fit(field: &TextField, text: &str) -> String { + let _ = field; + text.replace("\r\n", "\n").replace('\r', "\n").chars().take(MAX_FIELD_CHARS).collect() +} + +/// What an editing key does (the ActionScript key codes the player receives). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Edit { + Left, + Right, + Up, + Down, + Home, + End, + Backspace, + Delete, + Enter, + SelectAll, +} + +impl Edit { + /// The edit a key code makes, if any. + pub fn from_key(code: u32) -> Option { + Some(match code { + 37 => Edit::Left, + 39 => Edit::Right, + 38 => Edit::Up, + 40 => Edit::Down, + 36 => Edit::Home, + 35 => Edit::End, + 8 => Edit::Backspace, + 46 => Edit::Delete, + 13 => Edit::Enter, + _ => return None, + }) + } +} + +/// What an edit changed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Changed { + pub text: bool, + pub caret: bool, +} + +/// A focused field being edited: its block (style and authored text), its state, and whether +/// the viewer may change the text (input fields) or only select it. +pub struct Editor<'a> { + pub block: &'a TextBlock, + pub field: &'a TextField, + pub st: &'a mut FieldState, +} + +impl Editor<'_> { + fn len(&self) -> u32 { + chars(self.st.value(self.block)) + } + + fn editable(&self) -> bool { + self.field.kind == TextKind::Input + } + + /// Replaces the selection with `s` (typed characters, a paste or a line break). + pub fn insert(&mut self, s: &str) -> Changed { + if !self.editable() { + return Changed::default(); + } + let one = !self.field.lines.multiline(); + let mut add: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !one)).collect(); + let (a, b) = self.st.selection(); + let value = self.st.value(self.block).to_string(); + let kept = chars(&value) - (b - a); + let room = if self.field.max_chars > 0 { self.field.max_chars.saturating_sub(kept) } else { u32::MAX }; + let room = room.min((MAX_FIELD_CHARS as u32).saturating_sub(kept)); + if chars(&add) > room { + add = add.chars().take(room as usize).collect(); + } + if add.is_empty() && a == b { + return Changed::default(); + } + let mut next = String::with_capacity(value.len() + add.len()); + next.push_str(slice(&value, 0, a)); + next.push_str(&add); + next.push_str(slice(&value, b, u32::MAX)); + let caret = a + chars(&add); + self.st.text = Some(next); + self.st.caret = caret; + self.st.anchor = caret; + Changed { text: true, caret: true } + } + + /// One editing key; `shift` extends the selection with caret moves. + pub fn key(&mut self, e: Edit, shift: bool, look: Option<&FieldLook>) -> Changed { + let len = self.len(); + let (a, b) = self.st.selection(); + let moved = |st: &mut FieldState, to: u32, shift: bool| { + st.caret = to.min(len); + if !shift { + st.anchor = st.caret; + } + Changed { text: false, caret: true } + }; + match e { + Edit::SelectAll => { + self.st.anchor = 0; + self.st.caret = len; + Changed { text: false, caret: true } + } + Edit::Left if !shift && a != b => moved(self.st, a, false), + Edit::Right if !shift && a != b => moved(self.st, b, false), + Edit::Left => { + let to = self.st.caret.saturating_sub(1); + moved(self.st, to, shift) + } + Edit::Right => { + let to = self.st.caret.saturating_add(1); + moved(self.st, to, shift) + } + Edit::Home | Edit::End | Edit::Up | Edit::Down => { + let Some(look) = look else { + let to = if matches!(e, Edit::Home | Edit::Up) { 0 } else { len }; + return moved(self.st, to, shift); + }; + let n = look.line_of(self.st.caret); + let line = look.lines.get(n); + let to = match e { + Edit::Home => line.map_or(0, |l| l.start), + Edit::End => line.map_or(len, |l| l.end), + _ => { + let x = line.map_or(0.0, |l| l.x_at(self.st.caret)); + let target = if e == Edit::Up { n.checked_sub(1) } else { Some(n + 1).filter(|m| *m < look.lines.len()) }; + match target.and_then(|m| look.lines.get(m)) { + Some(l) => l.index_at(x), + None if e == Edit::Up => 0, + None => len, + } + } + }; + moved(self.st, to, shift) + } + Edit::Backspace | Edit::Delete if !self.editable() => Changed::default(), + Edit::Backspace | Edit::Delete if a != b => self.insert(""), + Edit::Backspace => { + if a == 0 { + return Changed::default(); + } + self.st.anchor = a - 1; + self.insert("") + } + Edit::Delete => { + if b >= len { + return Changed::default(); + } + self.st.anchor = a; + self.st.caret = b + 1; + self.insert("") + } + Edit::Enter if self.field.lines.multiline() => self.insert("\n"), + Edit::Enter => Changed::default(), + } + } + + /// The pointer at `p` (the text's space): pressed (`extend`: dragging from an earlier press). + pub fn point(&mut self, p: Vec2, extend: bool, look: Option<&FieldLook>) -> Changed { + let i = look.map_or(self.len(), |l| l.index_at(p + self.st.scroll)).min(self.len()); + self.st.caret = i; + if !extend { + self.st.anchor = i; + } + Changed { text: false, caret: true } + } +} + +/// Keeps the caret in view: scrolls the text so the caret's line fits in the box's height and +/// (when lines don't wrap) the caret in its width. +pub fn scroll_to_caret(block: &TextBlock, field: &TextField, st: &mut FieldState) { + let Some(look) = st.look.clone() else { + st.scroll = Vec2::ZERO; + return; + }; + let view = Vec2::new((block.box_width - 2.0 * FIELD_GUTTER).max(1.0), (block.box_height - 2.0 * FIELD_GUTTER).max(1.0)); + let c = look.caret_at(st.caret); + let mut s = st.scroll; + if field.lines != LineType::Multiline { + if c.x - s.x > view.x { + s.x = c.x - view.x; + } + if c.x < s.x { + s.x = c.x; + } + } else { + s.x = 0.0; + } + if c.y + look.line_height - s.y > view.y { + s.y = c.y + look.line_height - view.y; + } + if c.y < s.y { + s.y = c.y; + } + // Never past the text's end. + s.x = s.x.min((look.width - view.x).max(0.0)).max(0.0); + s.y = s.y.min((look.height - view.y).max(0.0)).max(0.0); + st.scroll = if s.x.is_finite() && s.y.is_finite() { s } else { Vec2::ZERO }; +} + +/// A look for tests: every character `cw` wide and `lh` tall (a square per visible one), lines +/// broken at `\n` and, with `wrap`, after as many characters as fit. +#[cfg(test)] +pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option) -> FieldLook { + let per = wrap.map(|w| ((w / cw).floor() as u32).max(1)); + let mut lines = Vec::new(); + let mut outline = Path::new(); + let (mut start, mut col, mut stops, mut width) = (0u32, 0u32, vec![(0u32, 0.0f32)], 0.0f32); + let mut i = 0u32; + for c in text.chars() { + if c == '\n' { + lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) }); + i += 1; + (start, col) = (i, 0); + stops.push((i, 0.0)); + continue; + } + if per.is_some_and(|p| col == p) { + lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) }); + (start, col) = (i, 0); + stops.push((i, 0.0)); + } + if !c.is_whitespace() { + let r = Path::rect(FIELD_GUTTER + col as f32 * cw + 1.0, FIELD_GUTTER + lines.len() as f32 * lh + 1.0, cw - 2.0, lh - 2.0); + outline.cmds.extend(r.cmds); + } + col += 1; + i += 1; + stops.push((i, col as f32 * cw)); + width = width.max(col as f32 * cw); + } + lines.push(CaretLine { start, end: i, stops }); + let n = lines.len(); + FieldLook { outline: Arc::new(outline), lines: lines.into(), line_height: lh, width, height: n as f32 * lh } +} + +#[cfg(test)] +#[path = "field_tests.rs"] +mod tests; diff --git a/crates/doc/src/field_tests.rs b/crates/doc/src/field_tests.rs new file mode 100644 index 00000000..1120264a --- /dev/null +++ b/crates/doc/src/field_tests.rs @@ -0,0 +1,182 @@ +use super::*; +use crate::{Rgba, TextAlign}; + +fn block(text: &str, f: TextField) -> TextBlock { + TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f) } +} + +/// Runs edits on a field as the player does: each change of text lays it out again (10 px per +/// character, 10 px lines) and keeps the caret in view. +struct Rig { + block: TextBlock, + field: TextField, + st: FieldState, +} + +impl Rig { + fn new(text: &str, kind: TextKind, lines: LineType) -> Rig { + let field = TextField { lines, ..TextField::new(kind) }; + let mut r = Rig { block: block(text, field.clone()), field, st: FieldState::default() }; + r.relayout(); + r + } + fn relayout(&mut self) { + let shown = self.field.shown(self.st.value(&self.block)); + self.st.look = Some(Arc::new(mono_look(&shown, 10.0, 10.0, self.field.wrap_width(self.block.box_width)))); + scroll_to_caret(&self.block, &self.field, &mut self.st); + } + fn apply(&mut self, ch: Changed) { + if ch.text { + self.relayout(); + } else { + scroll_to_caret(&self.block, &self.field, &mut self.st); + } + } + fn ed(&mut self) -> (Editor<'_>, Option>) { + let look = self.st.look.clone(); + (Editor { block: &self.block, field: &self.field, st: &mut self.st }, look) + } + fn key(&mut self, e: Edit, shift: bool) -> &mut Self { + let (mut ed, look) = self.ed(); + let ch = ed.key(e, shift, look.as_deref()); + self.apply(ch); + self + } + fn typed(&mut self, s: &str) -> &mut Self { + for c in s.chars() { + let (mut ed, _) = self.ed(); + let ch = ed.insert(&c.to_string()); + self.apply(ch); + } + self + } + fn click(&mut self, x: f32, y: f32, extend: bool) -> &mut Self { + let (mut ed, look) = self.ed(); + let ch = ed.point(Vec2::new(x, y), extend, look.as_deref()); + self.apply(ch); + self + } + fn text(&self) -> &str { + self.st.value(&self.block) + } +} + +#[test] +fn typing_moves_the_caret_and_keys_edit_around_it() { + let mut r = Rig::new("", TextKind::Input, LineType::Single); + r.typed("hello"); + assert_eq!((r.text(), r.st.caret, r.st.anchor), ("hello", 5, 5)); + r.key(Edit::Left, false).key(Edit::Left, false).typed("X"); + assert_eq!((r.text(), r.st.caret), ("helXlo", 4)); + r.key(Edit::Backspace, false); + assert_eq!((r.text(), r.st.caret), ("hello", 3)); + r.key(Edit::Delete, false); + assert_eq!((r.text(), r.st.caret), ("helo", 3)); + r.key(Edit::Home, false); + assert_eq!(r.st.caret, 0); + r.key(Edit::Backspace, false); + assert_eq!(r.text(), "helo", "nothing before the caret"); + r.key(Edit::End, false).key(Edit::Delete, false); + assert_eq!((r.text(), r.st.caret), ("helo", 4), "nothing after it"); + // Enter types nothing in a one-line field; control characters never go in. + r.key(Edit::Enter, false).typed("\u{7}\t"); + assert_eq!(r.text(), "helo"); +} + +#[test] +fn shift_selects_and_typing_replaces_the_selection() { + let mut r = Rig::new("abcdef", TextKind::Input, LineType::Single); + r.click(20.0, 5.0, false); + assert_eq!(r.st.caret, 2, "a click puts the caret at the nearest boundary"); + r.key(Edit::Right, true).key(Edit::Right, true); + assert_eq!(r.st.selection(), (2, 4)); + assert_eq!(r.st.selected(&r.block), "cd"); + // An arrow without Shift collapses the selection to its side. + r.key(Edit::Left, false); + assert_eq!((r.st.caret, r.st.anchor), (2, 2)); + r.key(Edit::End, true); + assert_eq!(r.st.selection(), (2, 6)); + r.typed("Z"); + assert_eq!((r.text(), r.st.caret), ("abZ", 3)); + // Dragging extends from where the press was; Backspace deletes the selection. + r.click(0.0, 5.0, false).click(19.0, 5.0, true); + assert_eq!(r.st.selection(), (0, 2)); + r.key(Edit::Backspace, false); + assert_eq!((r.text(), r.st.caret), ("Z", 0)); + r.key(Edit::SelectAll, false); + assert_eq!(r.st.selection(), (0, 1)); +} + +#[test] +fn multiline_fields_take_enter_and_move_between_lines() { + let mut r = Rig::new("", TextKind::Input, LineType::MultilineNoWrap); + r.typed("abc").key(Edit::Enter, false).typed("de"); + assert_eq!(r.text(), "abc\nde"); + assert_eq!(r.st.caret, 6); + r.key(Edit::Up, false); + assert_eq!(r.st.caret, 2, "up keeps the column"); + r.key(Edit::End, false); + assert_eq!(r.st.caret, 3); + r.key(Edit::Down, false); + assert_eq!(r.st.caret, 6, "down to the shorter line's end"); + r.key(Edit::Down, false); + assert_eq!(r.st.caret, 6, "down from the last line goes to the end"); + r.key(Edit::Up, false).key(Edit::Up, false); + assert_eq!(r.st.caret, 0, "up from the first line goes to the start"); + // Clicking on the second line. + r.click(17.0, 14.0, false); + assert_eq!(r.st.caret, 6, "x 17 on line 2 is nearest the boundary after d"); +} + +#[test] +fn max_chars_and_passwords() { + let mut r = Rig::new("", TextKind::Input, LineType::Password); + r.field.max_chars = 4; + r.typed("secret"); + assert_eq!(r.text(), "secr", "at most max_chars"); + let shown = r.field.shown(r.text()); + assert_eq!(shown, "****"); + // A paste is cut to the room left, and single-line fields drop its line breaks. + let mut r = Rig::new("ab", TextKind::Input, LineType::Single); + r.field.max_chars = 6; + r.key(Edit::End, false); + let (mut ed, _) = r.ed(); + let ch = ed.insert("c\nd\nefgh"); + r.apply(ch); + assert_eq!(r.text(), "abcdef"); +} + +#[test] +fn dynamic_fields_select_but_never_change() { + let mut r = Rig::new("read only", TextKind::Dynamic, LineType::Single); + r.typed("x").key(Edit::Backspace, false).key(Edit::Delete, false); + assert_eq!(r.text(), "read only"); + assert!(r.st.text.is_none(), "untouched"); + r.key(Edit::SelectAll, false); + assert_eq!(r.st.selected(&r.block), "read only"); +} + +#[test] +fn one_line_fields_scroll_to_keep_the_caret_in_view() { + // The box shows 50 px of text (54 less the gutters): five characters. + let mut r = Rig::new("", TextKind::Input, LineType::Single); + r.typed("abcdefgh"); + assert_eq!(r.st.scroll.x, 30.0, "the caret at 80 px shows at the right edge"); + r.key(Edit::Home, false); + assert_eq!(r.st.scroll.x, 0.0); + // Multiline: lines wrap and it scrolls down instead (the box shows two 10 px lines). + let mut r = Rig::new("", TextKind::Input, LineType::Multiline); + r.typed("aaaaabbbbbccccc"); + assert_eq!(r.st.look.as_ref().map(|l| l.lines.len()), Some(3)); + assert_eq!((r.st.scroll.x, r.st.scroll.y), (0.0, 10.0)); +} + +#[test] +fn script_text_is_capped_and_takes_actionscript_line_ends() { + let f = TextField::new(TextKind::Dynamic); + assert_eq!(fit(&f, "a\rb\r\nc"), "a\nb\nc"); + assert_eq!(chars(&fit(&f, &"x".repeat(MAX_FIELD_CHARS + 10))), MAX_FIELD_CHARS as u32); + assert_eq!(slice("héllo", 1, 3), "él"); + assert_eq!(slice("héllo", 4, 99), "o"); + assert_eq!(byte_at("héllo", 2), 3); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d0a08c6c..da0877bc 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -14,6 +14,7 @@ pub mod camera; mod filter; mod easing; mod eval; +pub mod field; mod hints; pub mod nine_slice; pub mod library; @@ -466,6 +467,149 @@ pub struct TextBlock { /// The layout box. pub box_width: f32, pub box_height: f32, + /// A dynamic or input text field (ADR 0066); `None`: static text. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub field: Option, +} + +impl TextBlock { + /// What kind of text it is: static, dynamic or input. + pub fn kind(&self) -> TextKind { + self.field.as_ref().map_or(TextKind::Static, |f| f.kind) + } +} + +/// Animate's three text types (ADR 0066). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TextKind { + /// Drawn as laid out; scripts can't reach it. + #[default] + Static, + /// Scripts set and read its text (`field.text`) while the movie plays. + Dynamic, + /// The viewer types into it while the movie plays; scripts read what was typed. + Input, +} + +impl TextKind { + pub const ALL: [TextKind; 3] = [TextKind::Static, TextKind::Dynamic, TextKind::Input]; + pub fn key(self) -> &'static str { + match self { + TextKind::Static => "static", + TextKind::Dynamic => "dynamic", + TextKind::Input => "input", + } + } + pub fn from_key(s: &str) -> Option { + TextKind::ALL.into_iter().find(|k| k.key() == s.trim().to_ascii_lowercase()) + } +} + +/// A field's line type, as Animate's Properties name them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LineType { + /// One line: Enter types nothing, the text scrolls sideways to keep the caret in view. + #[default] + Single, + /// Lines wrap at the field's width. + Multiline, + /// Lines break only where the text does. + MultilineNoWrap, + /// One line, drawn as `*` (input fields). + Password, +} + +impl LineType { + pub const ALL: [LineType; 4] = [LineType::Single, LineType::Multiline, LineType::MultilineNoWrap, LineType::Password]; + pub fn key(self) -> &'static str { + match self { + LineType::Single => "single", + LineType::Multiline => "multiline", + LineType::MultilineNoWrap => "multiline_no_wrap", + LineType::Password => "password", + } + } + pub fn from_key(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_"); + LineType::ALL.into_iter().find(|k| k.key() == s) + } + /// More than one line (Enter starts a new one). + pub fn multiline(self) -> bool { + matches!(self, LineType::Multiline | LineType::MultilineNoWrap) + } +} + +/// The inset of text in a field's box, on every side, in pixels (as Animate's fields have). +pub const FIELD_GUTTER: f32 = 2.0; +/// Longest text a field holds (characters). +pub const MAX_FIELD_CHARS: usize = 16_384; +/// Longest instance or variable name (characters). +pub const MAX_FIELD_NAME: usize = 256; + +/// A dynamic or input text field (ADR 0066): how it is drawn and how the viewer may use it. The +/// element's name is its instance name; the block's text is what it shows before a script or the +/// viewer changes it. Its box is the block's `box_width` × `box_height` (fixed, not the text's +/// size), and its outline is the shown text laid out [`FIELD_GUTTER`] inside the box, so +/// everything that draws or measures text works on fields unchanged. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextField { + pub kind: TextKind, + #[serde(default)] + pub lines: LineType, + /// The viewer can select its text (dynamic fields; input fields always can). + #[serde(default = "yes")] + pub selectable: bool, + /// A line around the box, and a fill behind the text. + #[serde(default)] + pub border: bool, + #[serde(default = "black")] + pub border_color: Rgba, + #[serde(default)] + pub background: bool, + #[serde(default = "white")] + pub background_color: Rgba, + /// Most characters the viewer may type (0: no limit). + #[serde(default)] + pub max_chars: u32, + /// The ActionScript 1/2 variable the field shows (kept from Animate documents, not run). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub variable: String, +} + +fn black() -> Rgba { + Rgba::BLACK +} +fn white() -> Rgba { + Rgba::WHITE +} + +impl TextField { + /// A single-line field of `kind`. + pub fn new(kind: TextKind) -> TextField { + TextField { kind, lines: LineType::Single, selectable: true, border: false, border_color: Rgba::BLACK, background: false, background_color: Rgba::WHITE, max_chars: 0, variable: String::new() } + } + + /// The width text wraps at in a box `box_width` wide, if its lines wrap. + pub fn wrap_width(&self, box_width: f32) -> Option { + (self.lines == LineType::Multiline).then(|| (box_width - 2.0 * FIELD_GUTTER).max(1.0)) + } + + /// What a field shows for `text`: `*` for each character of a password. + pub fn shown(&self, text: &str) -> String { + if self.lines == LineType::Password && self.kind == TextKind::Input { text.chars().map(|_| '*').collect() } else { text.to_string() } + } + + /// The viewer can focus it: an input field, or a selectable dynamic one. + pub fn focusable(&self) -> bool { + self.kind == TextKind::Input || (self.kind == TextKind::Dynamic && self.selectable) + } + + /// Values in range: names cut to length, at most [`MAX_FIELD_CHARS`] typed. + pub fn sanitized(&self) -> TextField { + TextField { max_chars: self.max_chars.min(MAX_FIELD_CHARS as u32), variable: self.variable.chars().take(MAX_FIELD_NAME).collect(), ..self.clone() } + } } /// An instance on a keyframe. diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index 9a1dacdd..5d9b9983 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -19,8 +19,9 @@ use crate::actions::as3::run::{self, Stop, World}; use crate::actions::as3::{Compiled, Decls, Problem}; use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target}; use crate::eval::{Play, evaluate_guided, evaluate_symbol, guide_walk}; +use crate::field::{Changed, Edit, Editor, FieldLook, FieldState, chars, fit, scroll_to_caret}; use crate::sound::Started; -use crate::{BlendMode, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, Group, LayerKind, MAX_SYMBOL_DEPTH, Rgba, SoundSync, SymbolId, SymbolKind, Timeline}; +use crate::{BlendMode, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, FIELD_GUTTER, Group, LayerKind, MAX_SYMBOL_DEPTH, Rgba, SoundSync, SymbolId, SymbolKind, TextBlock, TextField, TextKind, Timeline}; use anicraft_geom::{Affine, Vec2}; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; @@ -198,6 +199,14 @@ pub struct PlayerState { pub pressed: Option, /// Steps taken since the start. pub tick: u64, + /// Each text field a script or the viewer has touched (ADR 0066), by instance path. + pub fields: BTreeMap, + /// The field that has the keyboard (an input field, or a selectable dynamic one). + pub focus: Option, + /// Shift is held (key code 16 down): caret moves extend the selection. + pub shift: bool, + /// The pointer went down in the focused field and is selecting as it drags. + pub selecting: bool, } impl PlayerState { @@ -282,6 +291,10 @@ pub enum Event { /// A key went down (or repeats) and came up, by its ActionScript key code. KeyDown(u32), KeyUp(u32), + /// A character typed (or pasted) into the focused input field (ADR 0066). + Char(char), + /// Select All in the focused field. + SelectAll, } /// The state after a step, what the movie wrote to the Output panel (traces, and why an @@ -303,6 +316,8 @@ pub enum NodeKind { Graphic, MovieClip, Button, + /// A dynamic or input text field (ADR 0066). + Text, } /// One symbol instance on the stage (or the main timeline), as the player sees it at a state. @@ -331,6 +346,16 @@ pub struct Node { pub events: Vec, /// The volume its sounds get: the layers holding it, from the main timeline down. pub gain: f32, + /// A text field's block (its style, box and authored text). + pub text: Option>, +} + +impl Node { + /// A text field's block and field settings. + pub fn field(&self) -> Option<(&TextBlock, &TextField)> { + let t = self.text.as_deref()?; + Some((t, t.field.as_ref()?)) + } } /// Runs plug-in frame scripts for the player (the engine implements it over the plug-in host). @@ -339,6 +364,13 @@ pub trait ScriptHost { fn begin_step(&mut self) {} /// Runs `script` for the timeline described by `cx`; returns the actions it emitted. fn run(&mut self, script: &PluginScript, cx: &ScriptContext<'_>) -> ScriptRun; + /// Lays out `shown` (a field's text as it is drawn) in `block`'s style and box (ADR 0066): + /// the fonts live above this crate. `None`: it can't, and the field keeps its authored + /// outline until its text changes (then it draws only its box). + fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { + let _ = (block, shown); + None + } } /// What a frame script sees. @@ -422,7 +454,7 @@ pub fn input(doc: &Document, state: &PlayerState, events: &[Event], host: &mut d /// drawing order (parents before their contents). pub fn tree(doc: &Document, st: &PlayerState) -> Vec { let tl = doc.timeline(st.scene); - let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, local: Affine::IDENTITY, alpha: 1.0, hittable: true, events: Vec::new(), gain: 1.0 }]; + let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, local: Affine::IDENTITY, alpha: 1.0, hittable: true, events: Vec::new(), gain: 1.0, text: None }]; // The main timeline is seen through its camera (ADR 0027): instances are where the pointer // sees them. let camera = tl.camera_at(st.root.frame, &doc.stage); @@ -517,6 +549,19 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi if out.len() >= MAX_NODES { return; } + // Dynamic and input text fields are instances scripts can name (static text isn't). + if let ElementKind::Text(t) = &el.kind + && t.field.is_some() + { + let mut path = base.clone(); + path.push(el.id); + let ov = st.props.get(&path); + let shown = ov.is_none_or(Overrides::shown); + let set = ov.map(|o| o.apply(el)); + let e: &Element = set.as_ref().unwrap_or(el); + out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: None, kind: NodeKind::Text, frame: 0, frames: 0, xf: layer_xf.mul(&e.transform), local: el.transform, alpha: el.color.alpha(), hittable: hit && shown, events: Vec::new(), gain, text: Some(t.clone()) }); + continue; + } let ElementKind::Symbol { symbol, loop_mode, first_frame, events, .. } = &el.kind else { continue }; let Some(sym) = doc.symbol(*symbol) else { continue }; let mut path = base.clone(); @@ -533,7 +578,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi }; let idx = out.len(); let node_xf = layer_xf.mul(&e.transform); - out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, local: el.transform, alpha: el.color.alpha(), hittable: hit && shown, events: events.clone(), gain }); + out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, local: el.transform, alpha: el.color.alpha(), hittable: hit && shown, events: events.clone(), gain, text: None }); // Names inside a movie clip (or a button's states) are its own; a graphic's // contents belong to the timeline the graphic is on. let inner_owner = if kind == NodeKind::Graphic { owner } else { idx }; @@ -714,8 +759,13 @@ impl<'a, 'h> Run<'a, 'h> { all.contains(p) && !list.is_empty() }); self.st.stage.retain(|l| all.contains(&l.owner)); - // A timeline's variables go with its instance. + // A timeline's variables go with its instance, and a field's text with the field. self.st.vars.retain(|p, _| all.contains(p)); + self.st.fields.retain(|p, _| all.contains(p)); + if self.st.focus.as_ref().is_some_and(|p| !all.contains(p)) { + self.st.focus = None; + self.st.selecting = false; + } for slot in [&mut self.st.hover, &mut self.st.pressed] { if slot.as_ref().is_some_and(|p| !all.contains(p)) { *slot = None; @@ -792,7 +842,7 @@ impl<'a, 'h> Run<'a, 'h> { match n.kind { NodeKind::Root => Some(self.doc.timeline(self.st.scene)), NodeKind::MovieClip => n.symbol.and_then(|s| self.doc.symbol(s)).map(|s| &s.timeline), - NodeKind::Graphic | NodeKind::Button => None, + NodeKind::Graphic | NodeKind::Button | NodeKind::Text => None, } } @@ -1007,8 +1057,14 @@ impl<'a, 'h> Run<'a, 'h> { Prop::MouseX => num(short(self.st.mouse.x)), Prop::MouseY => num(short(self.st.mouse.y)), Prop::Name => Ok(Value::str("root1")), + Prop::Text | Prop::Length => Err("the main timeline isn't a text field".into()), }; } + if matches!(p, Prop::Text | Prop::Length) { + let Some((t, _)) = n.field() else { return Err(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind))) }; + let v = self.st.fields.get(&n.path).map_or(t.text.as_str(), |f| f.value(t)); + return Ok(if p == Prop::Text { Value::str(v) } else { Value::Num(crate::actions::as3::ir::text_len(v) as f64) }); + } let ov = self.st.props.get(&n.path).copied().unwrap_or_default(); let d = decompose64(&n.local); let deg = 180.0 / std::f64::consts::PI; @@ -1032,10 +1088,10 @@ impl<'a, 'h> Run<'a, 'h> { let v = if p == Prop::MouseX { (m[3] * x - m[2] * y) / det } else { (m[0] * y - m[1] * x) / det }; num(fround_short(v)) } + Prop::Text | Prop::Length => Err("not a text field".into()), Prop::CurrentFrame | Prop::TotalFrames | Prop::CurrentLabel => { if n.kind != NodeKind::MovieClip { - let what = if n.kind == NodeKind::Button { "a button" } else { "a graphic" }; - return Err(format!("“{}” is {what}; only movie clips and the main timeline have frames", n.name)); + return Err(format!("“{}” is {}; only movie clips and the main timeline have frames", n.name, kind_name(n.kind))); } match p { Prop::CurrentFrame => num(f64::from(n.frame) + 1.0), @@ -1080,7 +1136,7 @@ impl<'a, 'h> Run<'a, 'h> { _ => matches!(node.kind, NodeKind::Button | NodeKind::MovieClip), }; if !ok { - 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) }; + let why = if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is {}; only buttons and movie clips get pointer events", node.name, kind_name(node.kind)) }; return self.out(format!("{what}: {why}")); } let (path, name) = (node.path.clone(), node.name.clone()); @@ -1154,8 +1210,7 @@ impl<'a, 'h> Run<'a, 'h> { }; let Some(node) = self.nodes.get(i) else { return }; if !matches!(node.kind, NodeKind::Root | NodeKind::MovieClip) { - let what = if node.kind == NodeKind::Button { "a button" } else { "a graphic" }; - return self.out(format!("{}: “{}” is {what}; only movie clips and the main timeline have a playhead", a.describe(), node.name)); + return self.out(format!("{}: “{}” is {}; only movie clips and the main timeline have a playhead", a.describe(), node.name, kind_name(node.kind))); } let (path, frame, frames) = (node.path.clone(), node.frame, node.frames.max(1)); match a { @@ -1248,9 +1303,32 @@ impl<'a, 'h> Run<'a, 'h> { fn event(&mut self, e: Event) { self.refresh(); match e { - Event::Move(p) => self.pointer(Some(p)), + Event::Move(p) => { + self.pointer(Some(p)); + // Dragging in the focused field selects. + if self.st.selecting && self.st.down { + self.point_field(p, true); + } + } Event::Down(p) => { self.pointer(Some(p)); + // A field the viewer can use takes the press (unless a button is above it): it + // gets the keyboard and the caret goes where it was clicked. Anywhere else the + // focused field loses the keyboard. + let hover_at = self.st.hover.as_ref().and_then(|h| self.index_of(h)); + match self.field_at(p).filter(|(i, _)| hover_at.is_none_or(|h| *i > h)) { + Some((_, path)) => { + self.st.focus = Some(path); + self.st.down = true; + self.st.selecting = true; + self.point_field(p, false); + return; + } + None => { + self.st.focus = None; + self.st.selecting = false; + } + } let before = self.pointer_now(); self.st.down = true; self.st.pressed = self.st.hover.clone(); @@ -1261,6 +1339,12 @@ impl<'a, 'h> Run<'a, 'h> { } } Event::Up(p) => { + if self.st.selecting { + self.st.selecting = false; + self.st.down = false; + self.pointer(Some(p)); + return; + } self.pointer(Some(p)); let before = self.pointer_now(); self.st.down = false; @@ -1275,11 +1359,130 @@ impl<'a, 'h> Run<'a, 'h> { } } Event::Leave => self.pointer(None), - Event::KeyDown(k) => self.key(ListenEvent::KeyDown, k), - Event::KeyUp(k) => self.key(ListenEvent::KeyUp, k), + // Keys edit the focused field, then go to the stage's listeners as well (as they + // reach the stage from a focused field in ActionScript). + Event::KeyDown(k) => { + if k == SHIFT { + self.st.shift = true; + } + self.field_key(k); + self.key(ListenEvent::KeyDown, k); + } + Event::KeyUp(k) => { + if k == SHIFT { + self.st.shift = false; + } + self.key(ListenEvent::KeyUp, k); + } + Event::Char(c) => { + let mut b = [0u8; 4]; + let s: &str = c.encode_utf8(&mut b); + self.edit_field(|ed, _| ed.insert(s)); + } + Event::SelectAll => self.edit_field(|ed, look| ed.key(Edit::SelectAll, false, look)), } } + /// The topmost field at stage point `p` the viewer can use, with its node's index. + fn field_at(&self, p: Vec2) -> Option<(usize, InstancePath)> { + for (i, n) in self.nodes.iter().enumerate().rev() { + if n.kind != NodeKind::Text || !n.hittable { + continue; + } + let Some((t, f)) = n.field() else { continue }; + if !f.focusable() { + continue; + } + let Some(q) = n.xf.inverse().map(|m| m.apply(p)) else { continue }; + if q.x >= 0.0 && q.y >= 0.0 && q.x <= t.box_width && q.y <= t.box_height { + return Some((i, n.path.clone())); + } + } + None + } + + /// Field `path`'s block and its place on the stage. + fn field_node(&self, path: &[ElementId]) -> Option<(Arc, Affine)> { + let n = self.index_of(path).and_then(|i| self.nodes.get(i))?; + let t = n.text.clone().filter(|t| t.field.is_some())?; + Some((t, n.xf)) + } + + /// Lays field `path`'s text out as it is now (with the host's fonts) and keeps the caret + /// in the text and in view. + fn relayout(&mut self, path: &[ElementId]) { + let Some((t, _)) = self.field_node(path) else { return }; + let Some(f) = t.field.as_ref() else { return }; + let st = self.st.fields.entry(path.to_vec()).or_default(); + let shown = f.shown(st.value(&t)); + st.look = self.host.lay_out_field(&t, &shown).map(Arc::new); + let len = chars(st.value(&t)); + st.caret = st.caret.min(len); + st.anchor = st.anchor.min(len); + scroll_to_caret(&t, f, st); + } + + /// A script sets field `path`'s text. + fn set_field_text(&mut self, path: &[ElementId], text: &str) { + let Some((t, _)) = self.field_node(path) else { return }; + let Some(f) = t.field.as_ref() else { return }; + self.st.fields.entry(path.to_vec()).or_default().text = Some(fit(f, text)); + self.relayout(path); + } + + /// Runs an edit on the focused field (laying it out first if it never was). + fn edit_field(&mut self, go: impl FnOnce(&mut Editor<'_>, Option<&FieldLook>) -> Changed) { + let Some(path) = self.st.focus.clone() else { return }; + let Some((t, _)) = self.field_node(&path) else { return }; + let Some(f) = t.field.clone() else { return }; + if self.st.fields.get(&path).is_none_or(|s| s.look.is_none()) { + self.relayout(&path); + } + let st = self.st.fields.entry(path.clone()).or_default(); + let look = st.look.clone(); + let changed = go(&mut Editor { block: &t, field: &f, st }, look.as_deref()); + if changed.text { + self.relayout(&path); + } else if changed.caret { + scroll_to_caret(&t, &f, self.st.fields.entry(path).or_default()); + } + } + + /// The pointer at stage point `p` in the focused field: places the caret (`extend`: moves + /// it, keeping the selection's other end). + fn point_field(&mut self, p: Vec2, extend: bool) { + let Some(path) = self.st.focus.clone() else { return }; + let Some((_, xf)) = self.field_node(&path) else { return }; + let Some(q) = xf.inverse().map(|m| m.apply(p)) else { return }; + let q = Vec2::new(q.x - FIELD_GUTTER, q.y - FIELD_GUTTER); + self.edit_field(|ed, look| ed.point(q, extend, look)); + } + + /// A key down for the focused field: an edit, or Tab to the next input field. + fn field_key(&mut self, code: u32) { + if self.st.focus.is_none() { + return; + } + if code == TAB { + let inputs: Vec = self.nodes.iter().filter(|n| n.hittable && n.field().is_some_and(|(_, f)| f.kind == TextKind::Input)).map(|n| n.path.clone()).collect(); + let at = inputs.iter().position(|p| Some(p) == self.st.focus.as_ref()); + let n = inputs.len(); + if n > 0 { + let next = match at { + Some(i) if self.st.shift => (i + n - 1) % n, + Some(i) => (i + 1) % n, + None => 0, + }; + self.st.focus = inputs.get(next).cloned(); + self.edit_field(|ed, look| ed.key(Edit::SelectAll, false, look)); + } + return; + } + let Some(e) = Edit::from_key(code) else { return }; + let shift = self.st.shift; + self.edit_field(|ed, look| ed.key(e, shift, look)); + } + /// Moves the pointer: what it leaves gets Out, what it reaches gets Over. fn pointer(&mut self, p: Option) { self.refresh(); @@ -1346,6 +1549,21 @@ impl<'a, 'h> Run<'a, 'h> { } } +/// The key codes of Shift and Tab. +const SHIFT: u32 = 16; +const TAB: u32 = 9; + +/// How messages name a kind of instance. +fn kind_name(k: NodeKind) -> &'static str { + match k { + NodeKind::Root => "the main timeline", + NodeKind::Graphic => "a graphic", + NodeKind::MovieClip => "a movie clip", + NodeKind::Button => "a button", + NodeKind::Text => "a text field", + } +} + /// The event a listener is handling: the key code of a keyboard event, and its target and /// current target (`None`: the stage). #[derive(Clone, Debug, PartialEq)] @@ -1485,6 +1703,21 @@ impl World for Script<'_, '_, '_> { self.act(at.base, &Action::SetProperty { target: at.path.clone(), property: p, value: v }) } + fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let from = self.from().map_err(Some)?; + let i = self.r.place(from, self.ev.as_ref(), at).map_err(Some)?; + let Some(n) = i.and_then(|i| self.r.nodes.get(i)) else { return Err(Some("the stage isn't a text field".into())) }; + if n.field().is_none() { + return Err(Some(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind)))); + } + let path = n.path.clone(); + self.r.set_field_text(&path, &text); + Ok(()) + } + fn trace(&mut self, line: String) { if self.r.budget() { self.r.out(line); diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 836079e9..b4048fa0 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -705,3 +705,109 @@ fn scripted_play_is_deterministic() { assert!(!a.1.is_empty()); assert_eq!(a, b); } + +// ----- text fields (ADR 0066) --------------------------------------------------------------- + +/// A host that lays fields out in a 10 px monospace (the fonts live above this crate). +struct Mono; + +impl ScriptHost for Mono { + fn run(&mut self, _: &PluginScript, _: &ScriptContext<'_>) -> ScriptRun { + ScriptRun::default() + } + fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { + let f = block.field.as_ref()?; + Some(crate::field::mono_look(shown, 10.0, 10.0, f.wrap_width(block.box_width))) + } +} + +fn field(id: u64, name: &str, text: &str, kind: TextKind, x: f32, y: f32) -> Arc { + let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }) }; + Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }) +} + +fn field_doc(script: &str) -> Document { + let fields = vec![field(5, "score_txt", "0", TextKind::Dynamic, 10.0, 10.0), field(6, "name_txt", "", TextKind::Input, 10.0, 50.0), field(7, "", "", TextKind::Input, 10.0, 90.0)]; + doc(vec![layer(1, vec![as3(kf(0, 1, fields, vec![], ""), script)])], vec![]) +} + +fn text_of(st: &PlayerState, id: u64) -> Option { + st.fields.get(&vec![ElementId(id)]).and_then(|f| f.text.clone()) +} + +#[test] +fn scripts_set_and_read_dynamic_text() { + let d = field_doc("stop();\nvar n:int = 0;\nscore_txt.text = \"Score: \" + n;\nscore_txt.appendText(\"!\");\ntrace(score_txt.text, score_txt.length, name_txt.text == \"\");\nscore_txt.x = 20;\nghost_txt.text = \"x\";"); + let s = start(&d, &mut Mono); + assert_eq!(text_of(&s.state, 5).as_deref(), Some("Score: 0!")); + assert!(s.output.contains(&"Score: 0! 9 true".to_string()), "{:?}", s.output); + assert!(s.output.iter().any(|l| l.contains("no instance named “ghost_txt”")), "{:?}", s.output); + // Laid out by the host, drawn in place of the authored outline, where the script moved it. + let look = s.state.fields.get(&vec![ElementId(5)]).and_then(|f| f.look.clone()).expect("laid out"); + assert_eq!(look.lines[0].end, 9); + let dl = evaluate_player(&d, &s.state); + assert!(dl.items.iter().any(|i| Arc::ptr_eq(&i.path, &look.outline) && i.transform.m[4] == 20.0)); + // Without a host that can lay out, the text is still set and read; it draws only its box. + let s2 = start(&d, &mut NoScripts); + assert_eq!(text_of(&s2.state, 5).as_deref(), Some("Score: 0!")); + // Static text and other instances aren't fields. + let d = field_doc("hero.text = \"x\";"); + assert!(start(&d, &mut Mono).output.iter().any(|l| l.contains("no instance named “hero”"))); +} + +#[test] +fn the_viewer_types_into_input_fields_and_scripts_read_it() { + let d = field_doc("stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\nfunction onKey(e:KeyboardEvent):void {\n if (e.keyCode == Keyboard.ENTER) { score_txt.text = \"Hello, \" + name_txt.text; }\n}"); + let mut h = Mono; + let s = start(&d, &mut h); + // A click in the input field gives it the keyboard; typing goes in, editing keys edit. + let mut ev = vec![Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0))]; + ev.extend("Adx".chars().map(Event::Char)); + ev.extend([Event::KeyDown(8), Event::KeyDown(37), Event::Char('a'), Event::KeyDown(35), Event::Char('!')]); + let s = input(&d, &s.state, &ev, &mut h); + assert_eq!(s.state.focus, Some(vec![ElementId(6)])); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("Aad!")); + // Shift+Home selects; typing replaces it; Enter reaches the stage's key listener too. + let s = input(&d, &s.state, &[Event::KeyDown(16), Event::KeyDown(36), Event::KeyUp(16), Event::Char('B'), Event::Char('o'), Event::KeyDown(13)], &mut h); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("Bo")); + assert_eq!(text_of(&s.state, 5).as_deref(), Some("Hello, Bo")); + // The focused field draws its caret; a click elsewhere takes the keyboard away. + let caret = |st: &PlayerState| evaluate_player(&d, st).items.iter().filter(|i| i.fill.is_some() && i.masks.is_none() && i.path.bounds().width() <= 1.01 && i.path.bounds().height() > 5.0).count(); + assert_eq!(caret(&s.state), 1); + let s = input(&d, &s.state, &[Event::Down(Vec2::new(300.0, 300.0)), Event::Up(Vec2::new(300.0, 300.0)), Event::Char('z')], &mut h); + assert_eq!(s.state.focus, None); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("Bo"), "no field, no typing"); + assert_eq!(caret(&s.state), 0); + // A dynamic field takes no typing; Tab goes from input field to input field. + let s = input(&d, &s.state, &[Event::Down(Vec2::new(20.0, 15.0)), Event::Up(Vec2::new(20.0, 15.0)), Event::Char('q')], &mut h); + assert_eq!(s.state.focus, Some(vec![ElementId(5)]), "a selectable dynamic field can be focused"); + assert_eq!(text_of(&s.state, 5).as_deref(), Some("Hello, Bo")); + let s = input(&d, &s.state, &[Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0)), Event::KeyDown(9)], &mut h); + assert_eq!(s.state.focus, Some(vec![ElementId(7)])); + let s = input(&d, &s.state, &[Event::KeyDown(9)], &mut h); + assert_eq!(s.state.focus, Some(vec![ElementId(6)]), "Tab wraps round"); + assert_eq!(s.state.fields.get(&vec![ElementId(6)]).map(|f| f.selection()), Some((0, 2)), "and selects the field's text"); +} + +#[test] +fn fields_draw_their_box_and_the_authored_text_everywhere() { + let d = field_doc(""); + // The authoring frame and the player draw the authored outline, a border, inside a clip. + for dl in [evaluate(&d, 0), evaluate_player(&d, &start(&d, &mut NoScripts).state)] { + let texts = dl.items.iter().filter(|i| i.path.bounds() == Path::rect(2.0, 2.0, 8.0, 8.0).bounds() && i.masks.is_none()).count(); + assert_eq!(texts, 3); + assert_eq!(dl.items.iter().filter(|i| i.stroke.is_some()).count(), 3, "three borders"); + assert_eq!(dl.items.iter().filter(|i| i.masks.is_some()).count(), 3, "each box clips its text"); + assert_eq!(dl.clip_parents.len(), 3); + } +} + +#[test] +fn typing_is_deterministic() { + let d = field_doc("stop();"); + let ev: Vec = [Event::Down(Vec2::new(30.0, 55.0)), Event::Up(Vec2::new(30.0, 55.0))].into_iter().chain("deterministic".chars().map(Event::Char)).chain([Event::KeyDown(16), Event::KeyDown(37), Event::KeyDown(37), Event::Char('X')]).collect(); + let a = step(&d, &start(&d, &mut Mono).state, &ev, &mut Mono); + let b = step(&d, &start(&d, &mut Mono).state, &ev, &mut Mono); + assert_eq!(a, b); + assert_eq!(text_of(&a.state, 6).as_deref(), Some("deterministX")); +} diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index 229167a8..60c2e87c 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { c("actions.set", "Set Actions", "", None, "{actions: [{op: stop|play|goto_and_play|goto_and_stop|next_frame|prev_frame|next_scene|prev_scene|trace|set_property, target?, frame?, scene?, message?, property?, value?}] | plugin: id, entry?, symbol?: id (a movie clip's timeline), layer?, frame?} sets what the keyframe at the frame runs; or {element, event: click|press|release|over|out, actions} sets an instance's event handler. An empty list clears it", true, set), c("actions.clear", "Clear Actions", "", None, "{symbol?, layer?, frame?} clears the keyframe's actions; {element, event?} clears an instance's handlers (one event, or all)", true, clear), c("actions.list", "List Actions", "", None, "{} every keyframe with actions or a frame script and every instance with event handlers, in every scene and symbol", false, list), - c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance for actions", true, set_name), + c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance, or a dynamic or input text field, for actions and scripts", true, set_name), ] } @@ -232,7 +232,14 @@ fn set_name(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param(format!("“{name}” can't be an instance name: use letters, digits, _ or $ (no spaces), not starting with a digit, at most {} characters", actions::MAX_NAME_CHARS))); } let e = instance_mut(s, p)?.clone(); - interactive_kind(s, &e)?; + // Dynamic and input text fields take names too (ADR 0066); static text has none. + match &e.kind { + ElementKind::Text(t) if t.field.is_some() => {} + ElementKind::Text(_) => return Err(EngineError::State("static text has no instance name: make it dynamic or input text first (Properties › Text type)".into())), + _ => { + interactive_kind(s, &e)?; + } + } let el = instance_mut(s, p)?; el.name = name.clone(); Ok(json!({"element": el.id.0, "name": name})) diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 33c3a3f7..b1cb65c5 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -1,9 +1,13 @@ //! Text commands (ADR 0012): create and edit text blocks, list fonts. Laying text out happens //! here, when it changes; the document keeps the outlines, so rendering never needs fonts. +//! +//! Dynamic and input text fields (ADR 0066): `text.field` sets a block's Text type and field +//! options. A field's box is fixed and its text is laid out inside the gutter, aligned in the box; +//! [`field_layout`] does that for the commands and for the player while a movie plays. use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Rgba, TextAlign, TextBlock}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, Rgba, TextAlign, TextBlock, TextField, TextKind}; use anicraft_geom::{Affine, Path}; use anicraft_text::{Align, Fonts}; use serde_json::{Value, json}; @@ -32,9 +36,10 @@ impl Default for TextStyle { pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("text.create", "New Text", "", None, "{text, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn), + c("text.create", "New Text", "", None, "{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn), c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, |s, p| s.each_layer(false, |s| edit(s, p))), c("text.fonts", "Fonts", "", None, "{}", false, fonts), + c("text.field", "Text Type", "", None, "{type?: static|dynamic|input, lines?: single|multiline|multiline_no_wrap|password (input only), width?, height? (the field's box, px), selectable?, border?, background?, border_color?, background_color?, max_chars? (input; 0: no limit), variable? (kept, not run)} on the selected text; dynamic and input fields are named with instance.set_name and scripted in Test Movie and the HTML export (ADR 0066)", true, |s, p| s.each_layer(false, |s| set_field(s, p))), ] } @@ -120,22 +125,196 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu outline: Arc::new(layout.outline), box_width: layout.width, box_height: layout.height, + field: None, }; Ok((block, note)) } +/// A field's text laid out (ADR 0066): `shown` in the block's style, wrapped at the box less its +/// gutters when it is multiline, aligned in the box, with the outline moved into the gutter. +/// The carets are from the text's left edge (the alignment applied, not the gutter). +pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_width: f32, shown: &str) -> std::result::Result { + let wrap = field.wrap_width(box_width); + let mut l = fonts.layout( + shown, + &anicraft_text::Style { + family: style.font.clone(), + size: style.size, + bold: style.bold, + italic: style.italic, + align: match style.align { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: wrap, + }, + )?; + // Lines that don't wrap align against the widest; the widest aligns in the box. + let inner = (box_width - 2.0 * FIELD_GUTTER).max(0.0); + let shift = match (wrap, style.align) { + (Some(_), _) | (None, TextAlign::Left) => 0.0, + (None, TextAlign::Center) => ((inner - l.width) * 0.5).max(0.0), + (None, TextAlign::Right) => (inner - l.width).max(0.0), + }; + l.outline = l.outline.transformed(&Affine::translate(FIELD_GUTTER + shift, FIELD_GUTTER)); + if shift != 0.0 { + for line in &mut l.carets { + for s in &mut line.stops { + s.1 += shift; + } + } + l.width += shift; + } + Ok(l) +} + +/// A field block for `text`: laid out in its box (`box_width` × `box_height`). +pub(crate) fn lay_out_field(text: &str, style: &TextStyle, field: &TextField, box_width: f32, box_height: f32) -> Result<(TextBlock, Option)> { + let fonts = Fonts::get(); + let text: String = text.chars().take(MAX_FIELD_CHARS).collect(); + let l = field_layout(fonts, style, field, box_width, &field.shown(&text)).map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; + let note = (!style.font.trim().is_empty() && !l.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), l.family)); + let block = TextBlock { + text, + font: l.family, + size: style.size, + bold: style.bold, + italic: style.italic, + color: style.color, + align: style.align, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: field.wrap_width(box_width), + outline: Arc::new(l.outline), + box_width, + box_height, + field: Some(field.clone()), + }; + Ok((block, note)) +} + +/// The block `t` with new text or style: a field keeps its box (or takes `width` as its new +/// width); static text wraps at `width`. +fn relay(t: &TextBlock, text: &str, style: &TextStyle, width: Option) -> Result<(TextBlock, Option)> { + match &t.field { + Some(f) => lay_out_field(text, style, f, width.unwrap_or(t.box_width), t.box_height), + None => lay_out(text, style, width), + } +} + +/// The box a block becomes a field in: the text's own size and the gutters (at least 20 px wide). +fn field_box(t: &TextBlock) -> (f32, f32) { + ((t.width.unwrap_or(t.box_width) + 2.0 * FIELD_GUTTER).max(20.0), t.box_height + 2.0 * FIELD_GUTTER) +} + +fn kind_param(p: &Value) -> Result> { + opt_str(p, "type")?.map(|k| TextKind::from_key(k).ok_or_else(|| EngineError::Param(format!("'type' is static, dynamic or input, not '{k}'")))).transpose() +} + +fn set_field(s: &mut Session, p: &Value) -> Result { + let kind = kind_param(p)?; + let lines = opt_str(p, "lines")?.map(|k| LineType::from_key(k).ok_or_else(|| EngineError::Param(format!("'lines' is single, multiline, multiline_no_wrap or password, not '{k}'")))).transpose()?; + let size = |key: &str| -> Result> { + match opt_f32(p, key)? { + Some(v) if (1.0..=100_000.0).contains(&v) => Ok(Some(v)), + Some(_) => Err(EngineError::Param(format!("'{key}' must be between 1 and 100000 px"))), + None => Ok(None), + } + }; + let (width, height) = (size("width")?, size("height")?); + let max_chars = opt_u32(p, "max_chars")?; + if max_chars.is_some_and(|n| n as usize > MAX_FIELD_CHARS) { + return Err(EngineError::Param(format!("'max_chars' is at most {MAX_FIELD_CHARS}"))); + } + let variable = opt_str(p, "variable")?.map(|v| v.trim().chars().take(MAX_FIELD_NAME).collect::()); + let (selectable, border, background) = (opt_bool(p, "selectable")?, opt_bool(p, "border")?, opt_bool(p, "background")?); + let (border_color, background_color) = (opt_color(p, "border_color")?, opt_color(p, "background_color")?); + let mut changed = 0; + let mut notes = Vec::new(); + for e in s.selected_elements_mut()? { + let ElementKind::Text(t) = &e.kind else { continue }; + let to = kind.unwrap_or(t.kind()); + let style = style_of(t); + let (block, note) = if to == TextKind::Static { + if t.field.is_none() { + continue; + } + // Back to static text: laid out as before fields, the words where they were. + e.transform = e.transform.mul(&Affine::translate(FIELD_GUTTER, FIELD_GUTTER)); + e.name.clear(); + lay_out(&t.text, &style, t.field.as_ref().and_then(|f| f.wrap_width(t.box_width)))? + } else { + let (bw, bh) = if t.field.is_some() { (t.box_width, t.box_height) } else { field_box(t) }; + // Wrapped text becomes a multiline field, text with line breaks a multiline one + // that doesn't wrap, the rest a single line. + let lines_of = if t.width.is_some() { + LineType::Multiline + } else if t.text.contains('\n') { + LineType::MultilineNoWrap + } else { + LineType::Single + }; + let mut f = t.field.clone().unwrap_or_else(|| TextField { lines: lines_of, ..TextField::new(to) }); + if t.field.is_none() { + // The text stays where it was; the box grows round it. + e.transform = e.transform.mul(&Affine::translate(-FIELD_GUTTER, -FIELD_GUTTER)); + } + f.kind = to; + if let Some(l) = lines { + if l == LineType::Password && to != TextKind::Input { + return Err(EngineError::Param("only input text can be a password field".into())); + } + f.lines = l; + } + if f.lines == LineType::Password && to != TextKind::Input { + f.lines = LineType::Single; + } + f.selectable = selectable.unwrap_or(f.selectable); + f.border = border.unwrap_or(f.border); + f.background = background.unwrap_or(f.background); + f.border_color = border_color.unwrap_or(f.border_color); + f.background_color = background_color.unwrap_or(f.background_color); + f.max_chars = max_chars.unwrap_or(f.max_chars); + if let Some(v) = &variable { + f.variable.clone_from(v); + } + lay_out_field(&t.text, &style, &f.sanitized(), width.unwrap_or(bw), height.unwrap_or(bh))? + }; + notes.extend(note); + e.kind = ElementKind::Text(Arc::new(block)); + changed += 1; + } + if changed == 0 { + return Err(EngineError::State("the selection has no text to change".into())); + } + notes.dedup(); + Ok(json!({"changed": changed, "note": notes.first()})) +} + pub(crate) fn style_of(t: &TextBlock) -> TextStyle { TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing } } fn create(s: &mut Session, p: &Value) -> Result { let text: String = str_req(p, "text")?.to_string(); - if text.trim().is_empty() { + let kind = kind_param(p)?.unwrap_or_default(); + // An input field may start empty (the viewer fills it in); static text may not. + if text.trim().is_empty() && kind == TextKind::Static { return Err(EngineError::Param("'text' is empty".into())); } let style = style_param(p, &s.text_style)?; let width = width_param(p, None)?; let (block, note) = lay_out(&text, &style, width)?; + let (block, note) = if kind == TextKind::Static { + (block, note) + } else { + let (bw, bh) = field_box(&block); + let f = TextField { lines: if width.is_some() { LineType::Multiline } else if text.contains('\n') { LineType::MultilineNoWrap } else { LineType::Single }, ..TextField::new(kind) }; + lay_out_field(&text, &style, &f, bw, bh)? + }; let x = opt_f32(p, "x")?.unwrap_or((s.doc.stage.width as f32 - block.box_width) * 0.5); let y = opt_f32(p, "y")?.unwrap_or((s.doc.stage.height as f32 - block.box_height) * 0.5); let id = ElementId(s.doc.alloc_id()); @@ -148,19 +327,20 @@ fn create(s: &mut Session, p: &Value) -> Result { } fn edit(s: &mut Session, p: &Value) -> Result { - let new_text = match opt_str(p, "text")? { - Some(t) if t.trim().is_empty() => return Err(EngineError::Param("'text' is empty (delete the text instead)".into())), - t => t.map(str::to_string), - }; + let new_text = opt_str(p, "text")?.map(str::to_string); let mut notes = Vec::new(); let mut edited = 0; let mut last_style = None; for e in s.selected_elements_mut()? { let ElementKind::Text(t) = &e.kind else { continue }; let style = style_param(p, &style_of(t))?; - let width = width_param(p, t.width)?; let text = new_text.clone().unwrap_or_else(|| t.text.clone()); - let (block, note) = lay_out(&text, &style, width)?; + // Fields may be empty (a script or the viewer fills them); static text may not. + if text.trim().is_empty() && t.field.is_none() { + return Err(EngineError::Param("'text' is empty (delete the text instead)".into())); + } + let width = if t.field.is_some() { width_param(p, Some(t.box_width))?.or(Some(t.box_width)).map(|w| w.max(1.0)) } else { width_param(p, t.width)? }; + let (block, note) = relay(t, &text, &style, width)?; notes.extend(note); last_style = Some(TextStyle { font: block.font.clone(), ..style }); e.kind = ElementKind::Text(Arc::new(block)); diff --git a/crates/engine/src/find_tests.rs b/crates/engine/src/find_tests.rs index efa675f3..764ee72b 100644 --- a/crates/engine/src/find_tests.rs +++ b/crates/engine/src/find_tests.rs @@ -38,7 +38,7 @@ impl Build { self.doc.alloc_id() } pub fn text(&mut self, t: &str, color: Rgba) -> Element { - let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0 }; + let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None }; Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) } } pub fn rect(&mut self, fill: Paint, stroke: Option) -> Element { diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index e57000ed..9306aaea 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -12,7 +12,8 @@ use anicraft_doc::actions::as3::Problem; use anicraft_doc::actions::{Action, CompileResult, FrameScript, MAX_ACTIONS, PluginScript, check_actions}; use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step, TimelineRef}; -use anicraft_doc::{Document, LayerKind, SymbolKind, Timeline, player}; +use anicraft_doc::field::{CaretLine, FieldLook}; +use anicraft_doc::{Document, LayerKind, SymbolKind, TextBlock, Timeline, player}; use anicraft_geom::Vec2; use anicraft_plugins::{Host, Kind, Limits, Registry}; use serde_json::{Map, Value, json}; @@ -92,6 +93,22 @@ impl ScriptHost for ScriptRunner<'_> { } } } + + fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { + field_look(block, shown) + } +} + +/// A field's text laid out with this computer's fonts, as the player draws and edits it +/// (ADR 0066). +pub fn field_look(block: &TextBlock, shown: &str) -> Option { + let f = block.field.as_ref()?; + let l = crate::cmds_text::field_layout(anicraft_text::Fonts::get(), &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?; + let mut lines: Vec = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, stops: c.stops }).collect(); + if lines.is_empty() { + lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }); + } + Some(FieldLook { outline: std::sync::Arc::new(l.outline), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height }) } /// What a running frame script talks to. @@ -165,6 +182,26 @@ pub fn state_view(doc: &Document, st: &PlayerState, nodes: &[Node], here: Option "hover": path_of(&st.hover), "tick": st.tick, }); + // Text fields (ADR 0066): their text as it is now, and which has the keyboard. + let fields: Vec = nodes + .iter() + .enumerate() + .filter_map(|(i, n)| n.field().map(|(t, f)| (i, n, t, f))) + .take(MAX_VIEW_CLIPS) + .map(|(i, n, t, f)| { + let fs = st.fields.get(&n.path); + let text = fs.map_or(t.text.as_str(), |x| x.value(t)); + let mut o = json!({"path": path_name(nodes, i), "name": n.name, "type": f.kind.key(), "text": text}); + if st.focus.as_ref() == Some(&n.path) { + let (a, b) = fs.map_or((0, 0), |x| x.selection()); + o["focus"] = json!({"caret": fs.map_or(0, |x| x.caret), "selection": [a, b]}); + } + o + }) + .collect(); + if !fields.is_empty() { + v["fields"] = Value::Array(fields); + } if let Some((i, frame, label)) = here { let n = nodes.get(i); v["timeline"] = json!({"path": path_name(nodes, i), "frame": frame, "frames": n.map_or(1, |n| n.frames), "label": label, "playing": n.and_then(|n| st.playhead(&n.path)).is_some_and(|c| c.playing)}); @@ -257,11 +294,25 @@ pub fn parse_key(v: &Value) -> Result { } } +/// Most characters one `text` event types. +pub const MAX_TYPED: usize = 10_000; + /// Parses an event: a pointer event `{type: move|down|up|click|leave, x, y}` (a click is a -/// press and a release at one point) or a key event `{type: key_down|key_up|key, key}` (`key` -/// is a press and a release). +/// press and a release at one point), a key event `{type: key_down|key_up|key, key}` (`key` +/// is a press and a release), or typing into the focused text field (ADR 0066): +/// `{type: text, text}` (each character typed in turn) and `{type: select_all}`. pub fn parse_events(v: &Value) -> Result, String> { - let kind = v.get("type").and_then(Value::as_str).ok_or("an event needs a \"type\": move, down, up, click, leave, key_down, key_up or key")?; + let kind = v.get("type").and_then(Value::as_str).ok_or("an event needs a \"type\": move, down, up, click, leave, key_down, key_up, key, text or select_all")?; + if kind == "text" { + let t = v.get("text").and_then(Value::as_str).ok_or("a text event needs a \"text\" to type")?; + if t.chars().count() > MAX_TYPED { + return Err(format!("a text event types at most {MAX_TYPED} characters")); + } + return Ok(t.chars().map(Event::Char).collect()); + } + if kind == "select_all" { + return Ok(vec![Event::SelectAll]); + } if matches!(kind, "key_down" | "key_up" | "key") { let k = parse_key(v.get("key").unwrap_or(&Value::Null))?; return Ok(match kind { @@ -280,7 +331,7 @@ pub fn parse_events(v: &Value) -> Result, String> { let p = Vec2::new(num("x")?, num("y")?); vec![Event::Move(p), Event::Down(p), Event::Up(p)] } - other => return Err(format!("unknown event type '{other}' (move, down, up, click, leave, key_down, key_up or key)")), + other => return Err(format!("unknown event type '{other}' (move, down, up, click, leave, key_down, key_up, key, text or select_all)")), }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 06519499..2c4a9108 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1340,7 +1340,7 @@ fn opening_an_xfl_folder_imports_it_untitled() { assert_eq!((s.doc.stage.width, s.doc.stage.fps), (320, 12.0)); assert_eq!(s.doc.timeline(s.scene).layers[0].name, "Art"); assert_eq!(s.doc.frame_count(), 6); - assert!(v["report"].as_str().unwrap().contains("1 dynamic and input text fields (imported as static text)"), "{v}"); + assert!(v["report"].as_str().unwrap().contains("Runs in Test Movie: 1 dynamic text fields"), "{v}"); assert!(s.path.is_none(), "imported documents are untitled: Save never writes over the original"); assert!(s.execute("file.save", &json!({})).is_err()); // It renders. @@ -1363,6 +1363,8 @@ fn opening_an_xfl_folder_imports_it_untitled() { run(&mut back, "file.open", json!({"path": file.display().to_string()})); let ElementKind::Text(t) = &back.doc.timeline(0).layers[0].keyframes[0].elements.iter().find(|e| e.id == text.id).unwrap().kind else { panic!("text") }; assert_eq!((t.text.as_str(), t.size, t.bold), ("Hello again", 20.0, true)); + assert_eq!(t.kind(), anicraft_doc::TextKind::Dynamic, "a dynamic field stays one (ADR 0066)"); + assert_eq!((t.box_width, t.field.as_ref().map(|f| f.lines)), (200.0, Some(anicraft_doc::LineType::Single))); } std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index 1ef47a46..1ee72873 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -42,6 +42,7 @@ const FRAMES: &[(&str, &[u32])] = &[ ("shapes", &[0]), ("symbols", &[0, 5]), ("text", &[0]), + ("textfields", &[0]), ("tweens", &[0, 6, 12]), ]; @@ -126,6 +127,10 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("scripts", 4, 160.0, 90.0, 0xE76F51), ("scripts", 4, 240.0, 90.0, 0xF4F1EA), ("text", 0, 300.0, 80.0, 0xE9EDC9), + // Fields draw their box (white behind a border) with no fonts at all (ADR 0066). + ("text", 0, 290.0, 134.0, 0xFFFFFF), + ("textfields", 0, 100.0, 30.0, 0xFFFFFF), + ("textfields", 0, 300.0, 170.0, 0xF4F1EA), ]; fn import(case: &str) -> Document { @@ -218,7 +223,7 @@ fn every_package_opens_with_file_open_and_round_trips_through_the_file_format() fn raw_shapes_open_raw_merged_and_unchanged_to_the_eye() { let mut failures = Vec::new(); let (mut raw_total, mut merged_total) = (0, 0); - for (case, frames) in FRAMES.iter().filter(|(c, _)| !matches!(*c, "text")) { + for (case, frames) in FRAMES.iter().filter(|(c, _)| !matches!(*c, "text" | "textfields")) { let mut s = Session::default(); let info = s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}")); let raw = s.doc.scenes.iter().flat_map(|sc| sc.timeline.layers.iter()).chain(s.doc.library.iter().flat_map(|sym| sym.timeline.layers.iter())).flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()).filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).count(); diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 9eb6eead..2f5b7cc0 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -189,6 +189,8 @@ fn js_events(events: &[Event]) -> String { Event::Leave => json!({"type": "leave"}), Event::KeyDown(k) => json!({"type": "keydown", "code": k}), Event::KeyUp(k) => json!({"type": "keyup", "code": k}), + Event::Char(c) => json!({"type": "char", "text": c.to_string()}), + Event::SelectAll => json!({"type": "selectall"}), }) .collect(); Value::Array(list).to_string() diff --git a/crates/svg/src/text.rs b/crates/svg/src/text.rs index c3534cff..f7d23103 100644 --- a/crates/svg/src/text.rs +++ b/crates/svg/src/text.rs @@ -291,6 +291,7 @@ impl<'a> Builder<'a> { outline: Arc::new(layout.outline), box_width: layout.width, box_height: layout.height, + field: None, }; Ok(Some((block, ascent))) } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 9690d6f9..2599a6f0 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -73,6 +73,48 @@ pub struct Layout { /// From the top of the box to the first line's baseline (pixels), for placing text by its /// baseline, as SVG does. pub ascent: f32, + /// Where a caret can stand, one entry per laid-out line, top first (ADR 0066: text fields + /// that viewers type into). + pub carets: Vec, +} + +/// One laid-out line's characters and caret positions. Indices count `char`s of the whole text +/// (line breaks included); `x` is from the box's left edge, alignment applied. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CaretLine { + /// The first character on the line and the boundary after its last (a wrapped line's + /// trailing spaces belong to it; a line break belongs to neither line). + pub start: u32, + pub end: u32, + /// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending. + pub stops: Vec<(u32, f32)>, +} + +impl CaretLine { + /// The caret's x at character boundary `i` on this line: at the glyph starting there, or + /// after the line's last glyph, or (inside a ligature) at the glyph it is part of. + pub fn x_at(&self, i: u32) -> f32 { + let mut x = self.stops.first().map_or(0.0, |s| s.1); + for &(c, sx) in &self.stops { + if c > i { + break; + } + x = sx; + } + x + } + + /// The boundary nearest to `x` on this line. + pub fn index_at(&self, x: f32) -> u32 { + let mut best = (self.start, f32::INFINITY); + for &(c, sx) in &self.stops { + let d = (sx - x).abs(); + if d < best.1 { + best = (c, d); + } + } + best.0.clamp(self.start, self.end) + } } /// What a font name written by another program means on this computer: a PostScript name @@ -299,8 +341,25 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. let mut lines: Vec<(f32, Vec<(Glyph, f32)>)> = Vec::new(); - for para in text.split('\n') { - let para = para.strip_suffix('\r').unwrap_or(para); + // Per line: the character index its paragraph starts at, the paragraph's length in + // characters, and the byte → character map of the paragraph (shared by its lines). + let mut spans: Vec<(u32, u32, Arc>)> = Vec::new(); + let mut para_start = 0u32; + for raw in text.split('\n') { + let para = raw.strip_suffix('\r').unwrap_or(raw); + let mut to_char = vec![0u32; para.len() + 1]; + let mut n = 0u32; + for (b, _) in para.char_indices() { + if let Some(slot) = to_char.get_mut(b) { + *slot = n; + } + n += 1; + } + if let Some(last) = to_char.last_mut() { + *last = n; + } + let to_char = Arc::new(to_char); + let lines_before = lines.len(); let mut buffer = harfrust::UnicodeBuffer::new(); buffer.push_str(para); buffer.guess_segment_properties(); @@ -355,6 +414,10 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option } let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); lines.push((width, line)); + for _ in lines_before..lines.len() { + spans.push((para_start, n, to_char.clone())); + } + para_start += raw.chars().count() as u32 + 1; } let box_width = style.width.unwrap_or_else(|| lines.iter().map(|(w, _)| *w).fold(0.0, f32::max)); @@ -374,7 +437,56 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option } } let height = (lines.len().max(1) as f32 - 1.0) * line_height + (metrics.ascent - metrics.descent); - Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing, lines: lines.len().max(1), line_height, ascent }) + let carets = caret_lines(&lines, &spans, box_width, style.align); + Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing, lines: lines.len().max(1), line_height, ascent, carets }) +} + +/// The caret positions of laid-out lines (see [`CaretLine`]). +fn caret_lines(lines: &[(f32, Vec<(Glyph, f32)>)], spans: &[(u32, u32, Arc>)], box_width: f32, align: Align) -> Vec { + let mut out: Vec = Vec::with_capacity(lines.len()); + for (row, ((width, line), (pstart, plen, to_char))) in lines.iter().zip(spans).enumerate() { + let shift = match align { + Align::Left => 0.0, + Align::Center => (box_width - width) * 0.5, + Align::Right => box_width - width, + }; + let ch = |cluster: usize| pstart + to_char.get(cluster).copied().unwrap_or(*plen).min(*plen); + // A paragraph's first line starts with it; a wrapped line at its first glyph. + let first_of_para = row == 0 || spans.get(row - 1).is_none_or(|p| p.0 != *pstart); + let start = if first_of_para { *pstart } else { line.first().map_or(*pstart, |(g, _)| ch(g.cluster)) }; + let mut stops: Vec<(u32, f32)> = line.iter().map(|(g, gx)| (ch(g.cluster), shift + gx)).collect(); + stops.sort_by_key(|s| s.0); + stops.dedup_by_key(|s| s.0); + if first_of_para && stops.first().is_none_or(|s| s.0 > start) { + stops.insert(0, (start, shift)); + } + // The boundary after the last glyph (its trailing spaces, if any, follow it). + if let Some(&(c, _)) = stops.last() { + stops.push((c + 1, shift + width)); + } + out.push(CaretLine { start, end: start, stops }); + // The previous line of the same paragraph ends where this one starts. + if !first_of_para && let Some(prev) = out.len().checked_sub(2).and_then(|i| out.get_mut(i)) { + prev.end = start; + } + } + // The last line of each paragraph ends with it. + for (row, (pstart, plen, _)) in spans.iter().enumerate() { + let last_of_para = spans.get(row + 1).is_none_or(|p| p.0 != *pstart); + if last_of_para && let Some(l) = out.get_mut(row) { + l.end = pstart + plen; + } + } + for l in &mut out { + l.end = l.end.max(l.start); + let end = l.end; + l.stops.retain(|s| s.0 <= end); + if l.stops.last().is_none_or(|s| s.0 < end) { + let x = l.stops.last().map_or(0.0, |s| s.1); + l.stops.push((end, x)); + } + } + out } /// Draws glyph outlines (font space, y up) into a path (pixels, y down) at a pen position. @@ -531,4 +643,29 @@ mod tests { let b = one.outline.bounds(); assert!(b.max.y > one.ascent - 1.0 && b.min.y < one.ascent, "glyphs sit on the baseline: {b:?}"); } + + #[test] + fn carets_stand_at_every_boundary_line_by_line() { + let Some(fonts) = fonts() else { return }; + let l = fonts.layout("ab +cd", &style(20.0)).unwrap(); + assert_eq!(l.carets.len(), 2); + let (a, b) = (&l.carets[0], &l.carets[1]); + assert_eq!((a.start, a.end, b.start, b.end), (0, 2, 3, 5), "the line break belongs to neither line"); + assert_eq!(a.x_at(0), 0.0); + assert!(a.x_at(1) > 0.0 && a.x_at(2) > a.x_at(1)); + assert!((a.x_at(2) - fonts.layout("ab", &style(20.0)).unwrap().width).abs() < 0.01, "after the last glyph"); + assert_eq!(a.index_at(-5.0), 0); + assert_eq!(a.index_at(1000.0), 2); + assert_eq!(b.index_at(a.x_at(1)), 4, "the same place on the next line"); + // Wrapped lines: the space stays on the first line, the next word starts the second. + let w = fonts.layout("aaa bbb", &Style { width: Some(fonts.layout("aaa b", &style(20.0)).unwrap().width), ..style(20.0) }).unwrap(); + assert_eq!(w.carets.len(), 2); + assert_eq!((w.carets[0].start, w.carets[0].end, w.carets[1].start, w.carets[1].end), (0, 4, 4, 7)); + // Empty text has one line with one place for the caret; centred text starts mid-box. + let e = fonts.layout("", &style(20.0)).unwrap(); + assert_eq!(e.carets, vec![CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }]); + let c = fonts.layout("", &Style { width: Some(100.0), align: Align::Center, ..style(20.0) }).unwrap(); + assert_eq!(c.carets[0].x_at(0), 50.0); + } } diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 6954a59c..08f0d432 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -404,7 +404,8 @@ impl<'a> Builder<'a> { let name: String = el.attr("name").unwrap_or("").chars().take(256).collect(); for (i, p) in crate::text::field(el, fonts, &mut self.faces, &mut self.report).into_iter().enumerate() { let mut e = Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform: m.mul(&Affine::translate(p.offset.x, p.offset.y)), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(p.block)) }; - // A dynamic or input field's instance name goes on its first block. + // A dynamic or input field's instance name goes on it (its first block for static + // text, which keeps the name for a later conversion). if i == 0 { e.name.clone_from(&name); } diff --git a/crates/xfl/src/text.rs b/crates/xfl/src/text.rs index ea412874..549c5030 100644 --- a/crates/xfl/src/text.rs +++ b/crates/xfl/src/text.rs @@ -7,10 +7,14 @@ //! becomes one block per run of consecutive lines that share a style, stacked as Animate //! stacks them; a line that mixes styles takes the style most of its characters have, and the //! report says so. +//! +//! Dynamic and input fields (ADR 0066) become one field each, whatever their runs: a field is one +//! instance that scripts and the viewer use, so it takes its main style, keeps its instance name, +//! line type, border, selectability and maximum length, and the report counts them as running. use crate::import::{Report, color}; use crate::xml::Element as X; -use anicraft_doc::{Rgba, TextAlign, TextBlock}; +use anicraft_doc::{LineType, Rgba, TextAlign, TextBlock, TextField, TextKind}; use anicraft_geom::Vec2; use anicraft_text::{Align, FaceMatch, Fonts, TextError}; use std::collections::HashMap; @@ -86,6 +90,20 @@ struct Flags { shifted: bool, } +impl Flags { + fn report(&self, report: &mut Report) { + if self.justified { + report.skip("justified text (drawn left-aligned)"); + } + if self.indented { + report.skip("first-line indents"); + } + if self.shifted { + report.skip("superscript and subscript (drawn on the line)"); + } + } +} + /// A line of the field: its pieces, each with the style of the run it came from. type Line = Vec<(String, usize)>; @@ -113,9 +131,6 @@ fn main_style(line: &Line) -> (usize, bool) { /// Lays out one text field. Fonts are looked up once per face name (`faces`); missing ones go /// into the report. pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, report: &mut Report) -> Vec { - if el.name != "DOMStaticText" { - report.skip("dynamic and input text fields (imported as static text)"); - } if el.attr("orientation").is_some_and(|o| o != "horizontal") { report.skip("vertical text (drawn horizontal)"); } @@ -163,6 +178,10 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo if cut { report.skip("text cut to 100,000 characters per field"); } + if el.name != "DOMStaticText" { + flags.report(report); + return text_field(el, fonts, faces, report, &lines, &styles).into_iter().collect(); + } // Trailing empty lines draw nothing. while lines.last().is_some_and(|l| l.iter().all(|(t, _)| t.trim().is_empty())) { lines.pop(); @@ -170,15 +189,7 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo if lines.is_empty() || styles.is_empty() { return Vec::new(); } - if flags.justified { - report.skip("justified text (drawn left-aligned)"); - } - if flags.indented { - report.skip("first-line indents"); - } - if flags.shifted { - report.skip("superscript and subscript (drawn on the line)"); - } + flags.report(report); // Consecutive lines in the same style make one block. let mut blocks: Vec<(usize, String)> = Vec::new(); @@ -252,6 +263,7 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo outline: Arc::new(layout.outline), box_width: layout.width, box_height: layout.height, + field: None, }; out.push(Placed { block, offset: Vec2::new(origin.x + st.left_margin, origin.y + y) }); y += layout.lines as f32 * layout.line_height; @@ -269,3 +281,92 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo } out } + +/// A dynamic or input field (ADR 0066): one block in the field's main style, its box from the +/// field's `width` and `height` (or the text's size, for an auto-size field), its text laid out +/// inside the gutter. Empty fields are kept (an empty input field is the usual kind). +fn text_field(el: &X, fonts: &Fonts, faces: &mut HashMap, report: &mut Report, lines: &[Line], styles: &[RunStyle]) -> Option { + let kind = if el.name == "DOMInputText" { TextKind::Input } else { TextKind::Dynamic }; + report.run(if kind == TextKind::Input { "input text fields" } else { "dynamic text fields" }); + let all: Line = lines.iter().flatten().cloned().collect(); + let (s, mixed) = main_style(&all); + if mixed { + report.skip("text fields with mixed text styles (drawn in their main style)"); + } + let st = styles.get(s).cloned().unwrap_or_else(|| run_style(None, &mut Flags::default())); + let text: String = lines.iter().map(|l| l.iter().map(|(t, _)| t.as_str()).collect::()).collect::>().join("\n"); + let text = text.trim_end_matches('\n').to_string(); + let line_type = match el.attr("lineType") { + Some("multiline") => LineType::Multiline, + Some("multiline no wrap") => LineType::MultilineNoWrap, + Some("password") if kind == TextKind::Input => LineType::Password, + _ => LineType::Single, + }; + let border = el.bool("border").unwrap_or(false); + let variable: String = el.attr("variableName").unwrap_or("").trim().chars().take(anicraft_doc::MAX_FIELD_NAME).collect(); + if !variable.is_empty() { + report.keep("text field variables (ActionScript 1.0 and 2.0)"); + } + if el.bool("renderAsHTML").unwrap_or(false) { + report.skip("text fields rendered as HTML (drawn as plain text)"); + } + let max_chars = el.f32("maxCharacters").filter(|n| n.is_finite() && *n > 0.0).map_or(0, |n| n.min(anicraft_doc::MAX_FIELD_CHARS as f32) as u32); + // Animate's "show border" draws a black line round a white box. + let field = TextField { lines: line_type, selectable: el.bool("isSelectable").unwrap_or(true), border, background: border, max_chars, variable, ..TextField::new(kind) }; + let auto = el.bool("autoExpand").unwrap_or(false); + let width = el.f32("width").filter(|w| w.is_finite() && *w > 0.0).map(|w| w.min(100_000.0)); + let face = faces.entry(st.face.clone()).or_insert_with(|| fonts.find_face(&st.face)).clone(); + let wrap = width.and_then(|w| field.wrap_width(w - st.left_margin - st.right_margin)); + let style = anicraft_text::Style { + family: face.family.clone().unwrap_or_default(), + size: st.size, + bold: st.bold || face.bold, + italic: st.italic || face.italic, + align: match st.align { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }, + letter_spacing: st.letter_spacing, + line_spacing: st.line_spacing, + width: wrap.or(if auto { None } else { width.map(|w| (w - 2.0 * GUTTER - st.left_margin - st.right_margin).max(1.0)).filter(|_| st.align != TextAlign::Left) }), + }; + let shown = field.shown(&text); + let (outline, family, tw, th) = match fonts.layout(&shown, &style) { + Ok(l) => { + if face.family.is_none() && !face.wanted.is_empty() { + report.missing_fonts.insert(face.wanted.clone()); + report.fallback_font.get_or_insert_with(|| l.family.clone()); + } + let moved = l.outline.transformed(&anicraft_geom::Affine::translate(GUTTER + st.left_margin, GUTTER)); + (moved, l.family, l.width, l.height) + } + Err(e) => { + report.skip(if e == TextError::NoFonts { "text fields (no fonts on this computer)" } else { "text cut to 100,000 characters per field" }); + (anicraft_geom::Path::new(), face.wanted.clone(), 0.0, st.size * 1.2) + } + }; + let box_width = match (width, auto) { + (Some(w), false) => w, + (Some(w), true) => w.max(tw + 2.0 * GUTTER), + (None, _) => tw + 2.0 * GUTTER, + }; + let box_height = el.f32("height").filter(|h| h.is_finite() && *h > 0.0).map_or(th + 2.0 * GUTTER, |h| h.min(100_000.0)); + let block = TextBlock { + text, + font: family, + size: style.size, + bold: style.bold, + italic: style.italic, + color: st.color, + align: st.align, + letter_spacing: st.letter_spacing, + line_spacing: st.line_spacing, + width: wrap, + outline: Arc::new(outline), + box_width, + box_height, + field: Some(field), + }; + Some(Placed { block, offset: Vec2::new(el.f32("left").unwrap_or(0.0), el.f32("top").unwrap_or(0.0)) }) +} diff --git a/crates/xfl/src/text_tests.rs b/crates/xfl/src/text_tests.rs index d34272f1..48f107e7 100644 --- a/crates/xfl/src/text_tests.rs +++ b/crates/xfl/src/text_tests.rs @@ -2,7 +2,7 @@ use crate::import::{Report, XflError, import_with, import_with_fonts}; use crate::text::GUTTER; -use anicraft_doc::{Document, Element, ElementKind, Paint, Rgba, TextAlign, TextBlock, evaluate}; +use anicraft_doc::{Document, Element, ElementKind, LineType, Paint, Rgba, TextAlign, TextBlock, TextKind, evaluate}; use anicraft_text::Fonts; use std::sync::Arc; @@ -129,22 +129,41 @@ fn missing_fonts_fall_back_and_are_reported() { } #[test] -fn dynamic_and_input_text_come_across_as_static_text_and_are_reported() { +fn dynamic_and_input_text_become_fields_with_their_names() { let Some((fonts, _)) = fonts() else { return }; let field = format!( - r#"{}{}{}"#, + r#"{}{}{}"#, run("0", r#"size="16""#), run("type here", r#"size="16" alignment="justify""#), run("down", r#"size="16" indent="5" characterPosition="superscript""#) ); let (doc, report) = import_doc(&doc_with(&field), fonts); let t = texts(&doc); - assert_eq!(t.iter().map(|(e, _)| e.name.as_str()).collect::>(), ["score", "answer", ""], "instance names are kept"); - assert_eq!(t[1].1.align, TextAlign::Left); - for (what, n) in [("dynamic and input text fields (imported as static text)", 2), ("justified text (drawn left-aligned)", 1), ("vertical text (drawn horizontal)", 1), ("first-line indents", 1), ("superscript and subscript (drawn on the line)", 1)] { + assert_eq!(t.iter().map(|(e, _)| e.name.as_str()).collect::>(), ["score", "answer", "notes", ""], "instance names are kept"); + let kinds: Vec = t.iter().map(|(_, b)| b.kind()).collect(); + assert_eq!(kinds, [TextKind::Dynamic, TextKind::Input, TextKind::Input, TextKind::Static]); + // The box is the field's; the text sits in the gutter, the element at the field's matrix. + let (score, sb) = &t[0]; + assert_eq!((sb.box_width, sb.box_height), (100.0, 22.0)); + assert_eq!(score.transform.translation(), anicraft_geom::Vec2::new(10.0, 20.0)); + assert!(sb.outline.bounds().min.x >= GUTTER - 0.5, "{:?}", sb.outline.bounds()); + let f = sb.field.as_ref().unwrap(); + assert!(f.border && f.background && !f.selectable); + let f = t[1].1.field.as_ref().unwrap(); + assert_eq!((f.lines, f.max_chars, f.variable.as_str()), (LineType::Password, 8, "_root.pw")); + assert_eq!(t[1].1.text, "type here", "the value is kept; it is drawn as stars"); + let n = &t[2].1; + assert_eq!((n.text.as_str(), n.field.as_ref().map(|f| f.lines), n.box_height), ("", Some(LineType::Multiline), 60.0), "an empty input field is kept"); + assert_eq!(report.runs.get("dynamic text fields"), Some(&1)); + assert_eq!(report.runs.get("input text fields"), Some(&2)); + assert_eq!(report.kept.get("text field variables (ActionScript 1.0 and 2.0)"), Some(&1)); + for (what, n) in [("justified text (drawn left-aligned)", 1), ("vertical text (drawn horizontal)", 1), ("first-line indents", 1), ("superscript and subscript (drawn on the line)", 1)] { assert_eq!(report.skipped.get(what), Some(&n), "{what}: {report:?}"); } assert!(report.missing_fonts.is_empty(), "no face asks for the default family"); + // Every non-interactive render draws the authored text in its box, with its border. + let dl = evaluate(&doc, 0); + assert!(dl.items.iter().any(|i| i.stroke.is_some()), "the border"); } #[test] diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index b0b58bd2..400bb8af 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -79,19 +79,28 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[ "symbols", &[("instances of missing symbols", 1), ("missing library files", 1), ("reverse loop modes (played forward)", 1)], ), - ("text", &[("dynamic and input text fields (imported as static text)", 2), ("text fields (no fonts on this computer)", 4)]), + ("text", &[("text fields (no fonts on this computer)", 4)]), + ("textfields", &[("text fields (no fonts on this computer)", 4)]), ("tweens", &[("motion tweens (kept as keyframes)", 1), ("tween spins (turned the shortest way)", 1)]), ]; /// What each package keeps without running (ADR 0013 tier 1: scripts outside the subset, and /// class names); packages not listed keep nothing. -const KEPT: &[(&str, &[(&str, usize)])] = &[("bitmaps", &[("library folders", 1)]), ("nineslice", &[("library folders", 1)]), ("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)]), ("symbols", &[("library folders", 1)])]; +const KEPT: &[(&str, &[(&str, usize)])] = &[ + ("bitmaps", &[("library folders", 1)]), + ("nineslice", &[("library folders", 1)]), + ("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)]), + ("symbols", &[("library folders", 1)]), + ("textfields", &[("text field variables (ActionScript 1.0 and 2.0)", 1)]), +]; /// The frame scripts each package brings that run (ADR 0013 tier 2: in the subset). const RUNS: &[(&str, &[(&str, usize)])] = &[ ("interactive", &[("frame scripts in ActionScript 3.0", 4)]), ("scenes", &[("frame scripts in ActionScript 3.0", 2)]), ("scripts", &[("frame scripts in ActionScript 3.0", 2)]), + ("text", &[("dynamic text fields", 1), ("input text fields", 1)]), + ("textfields", &[("dynamic text fields", 1), ("frame scripts in ActionScript 3.0", 1), ("input text fields", 3)]), ]; #[test] @@ -331,8 +340,17 @@ fn text_fields_become_blocks_with_this_computers_fonts() { .collect(); let want = [("", "Corpus", 28.0, true), ("", "self-authored, line two", 12.0, false), ("", "A fixed-width field wraps its words onto lines.", 11.0, false), ("score", "Score 0042", 18.0, false), ("answer", "type here", 14.0, false)]; assert_eq!(blocks.iter().map(|(n, t, s, b)| (n.as_str(), t.as_str(), *s, *b)).collect::>(), want); - assert_eq!(report.skipped.get("dynamic and input text fields (imported as static text)"), Some(&2)); + assert_eq!(report.runs.get("dynamic text fields"), Some(&1), "fields run in Test Movie (ADR 0066)"); assert!(!report.skipped.contains_key("text fields (no fonts on this computer)")); + // The text fields package: fields with their boxes, kinds and names, laid out in the box. + let (doc, _) = import_files(&files("textfields"), fonts).unwrap(); + let fields: Vec<(String, anicraft_doc::TextKind, f32, f32)> = doc.timeline(0).layers[1].keyframes[0] + .elements + .iter() + .filter_map(|e| if let ElementKind::Text(t) = &e.kind { Some((e.name.clone(), t.kind(), t.box_width, t.box_height)) } else { None }) + .collect(); + use anicraft_doc::TextKind::{Dynamic, Input}; + assert_eq!(fields, [("score_txt".into(), Dynamic, 200.0, 28.0), ("name_txt".into(), Input, 200.0, 24.0), ("notes_txt".into(), Input, 140.0, 64.0), ("pw_txt".into(), Input, 120.0, 24.0)]); } /// A small deterministic generator (xorshift), so a failing variant can be found again. diff --git a/crates/xfl/tests/corpus/text/golden/frame-000.png b/crates/xfl/tests/corpus/text/golden/frame-000.png index 1252f495b959746a92e0aea775936c17e7ba37b1..109de9e46aa720d6addbc33e660e6b8877ff6a86 100644 GIT binary patch delta 901 zcmX@adqH4=G82dRM%6Z!`d|IU-{*cWydInW^Z%1J>2n2td#`_R(Eom8`@@|Ix1a6& zbM$dt*XnNx&ItRM?L9UsH&qLhr6h12_8G@ zNeeEjJF6Z`oKSAb?)=<6*RuDD{g?l9?)@LW>-IZ76s`Y|WOL!P?YG$y8QXj@W0h}3!WLq)IYmu zBM)>n<2SzdkM9-xKg%fXT)B4Vt5xEmy2fVDj_>&PMft|fJ#FF)lh-iIP2R)I2gTgt a&Gjs1e_0jM9{dPl00K`}KbLh*2~7aln?1b% delta 188 zcmca0aENz;G80?pM%6Z!$t^7Ec(9U?x&I&6W!s*uTK#YF6{E*X<-RVPEYG44_KolT z + + + + + + + + + + + + + + + + + + + + + + + + Score: 0 + + + + + + + + + + + + + + + + + + Notes wrap at the width of the field. + + + + + + + + + secret + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/textfields/golden/frame-000.png b/crates/xfl/tests/corpus/textfields/golden/frame-000.png new file mode 100644 index 0000000000000000000000000000000000000000..d68b277a1e2d10a9f3d4f1f331e00df66f8a7a1e GIT binary patch literal 2741 zcmeAS@N?(olHy`uVBq!ia0vp^3xGI^gAGX9ABzPFaMgIaIEGX(zCFOaKqYe8v5)`D z-}Rn2v%JVVd0p=9ZBUfiGjE#L`gumiO7DJ_ZO^J&)^44B)t`O(JLB-!ulJc{V|Ja7 zDZN_HUsCYWuJ~%`f7=TOm;OEz8vggY10hBGA8fmw_gr%O-E*P;i)~&^o4xbtwAnx7 z`9Nm=;jVlC{r?2}pPTnT+Zy+J>yB6Z@4x?Z?)?X^^&c+nIktMg*8kHBo4vo!tUvhv z?>~8?`xeKt_kYVSzFNQk{=c{P(@IM^uUC8xe_C$|a@c46AA9frcYY>)yyETky4-cY z-haQn|L^TJeR?0I*8f}eN57pI6*?WGi{p_Wr-zF!$*dz2Wtt|E4>G0_T6z{ojA>Q}z}1T(5h3{n@Jj zbwEe$Kl|#1(E5+B)}Q)c^y0y#+Gp_}s`vkIKV#na@fOfsF<w4AN>yJP&^x1m< zVeP$#yg!eooWYXK20Z21u4lhnWW4=Ok#YFn*$WWG(kJ!$Z`b!+%ib#%ZhITG_(D~P zD8DwN{nQu>t@9 literal 0 HcmV?d00001 diff --git a/crates/xfl/tests/corpus/textfields/textfields.xfl b/crates/xfl/tests/corpus/textfields/textfields.xfl new file mode 100644 index 00000000..860a820e --- /dev/null +++ b/crates/xfl/tests/corpus/textfields/textfields.xfl @@ -0,0 +1 @@ +PROXY-CS5 \ No newline at end of file From ee19adfa9685b7f8bce860576ec1a2bb4b072b9b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:31:16 -0700 Subject: [PATCH 081/192] feat(text): Text type in Properties and typing into fields in Test Movie (M5) --- crates/doc/src/player.rs | 39 ++++++---- crates/engine/src/lib.rs | 7 ++ src/a11y.rs | 2 +- src/app.rs | 29 ++++++++ src/main.rs | 2 +- src/panels.rs | 108 +++++++++++++++++++++++++++- src/test_movie.rs | 151 ++++++++++++++++++++++++++++++++++++--- 7 files changed, 311 insertions(+), 27 deletions(-) diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index 5d9b9983..5015fb37 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -467,6 +467,30 @@ pub fn hit(doc: &Document, st: &PlayerState, p: Vec2) -> Option { hit_in(doc, st, &tree(doc, st), p) } +/// The text field at stage point `p` the viewer can click into, topmost first (ADR 0066): what +/// a window shows a text cursor over. +pub fn field_at(doc: &Document, st: &PlayerState, p: Vec2) -> Option { + field_hit(&tree(doc, st), p).map(|(_, path)| path) +} + +/// The topmost focusable field node at `p`, with its index. +fn field_hit(nodes: &[Node], p: Vec2) -> Option<(usize, InstancePath)> { + for (i, n) in nodes.iter().enumerate().rev() { + if n.kind != NodeKind::Text || !n.hittable { + continue; + } + let Some((t, f)) = n.field() else { continue }; + if !f.focusable() { + continue; + } + let Some(q) = n.xf.inverse().map(|m| m.apply(p)) else { continue }; + if q.x >= 0.0 && q.y >= 0.0 && q.x <= t.box_width && q.y <= t.box_height { + return Some((i, n.path.clone())); + } + } + None +} + /// The frame of a button's timeline, `len` frames long, that answers the pointer: the Hit /// frame (the fourth) when it has one, otherwise the Up frame. pub fn hit_frame(len: u32) -> u32 { @@ -1385,20 +1409,7 @@ impl<'a, 'h> Run<'a, 'h> { /// The topmost field at stage point `p` the viewer can use, with its node's index. fn field_at(&self, p: Vec2) -> Option<(usize, InstancePath)> { - for (i, n) in self.nodes.iter().enumerate().rev() { - if n.kind != NodeKind::Text || !n.hittable { - continue; - } - let Some((t, f)) = n.field() else { continue }; - if !f.focusable() { - continue; - } - let Some(q) = n.xf.inverse().map(|m| m.apply(p)) else { continue }; - if q.x >= 0.0 && q.y >= 0.0 && q.x <= t.box_width && q.y <= t.box_height { - return Some((i, n.path.clone())); - } - } - None + field_hit(&self.nodes, p) } /// Field `path`'s block and its place on the stage. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 58142abf..0bbf23bd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -966,6 +966,13 @@ pub fn element_label(doc: &Document, e: &Element) -> String { None => "Graphic: missing".to_string(), }, ElementKind::Camera => "Camera".to_string(), + // An empty field (an input field waiting for the viewer) is named by its type. + ElementKind::Text(t) if t.text.trim().is_empty() => match t.kind() { + anicraft_doc::TextKind::Static => "Static text", + anicraft_doc::TextKind::Dynamic => "Dynamic text", + anicraft_doc::TextKind::Input => "Input text", + } + .to_string(), ElementKind::Text(t) => { let first: String = t.text.lines().next().unwrap_or("").chars().take(24).collect(); format!("Text: {first}{}", if t.text.chars().count() > first.chars().count() { "…" } else { "" }) diff --git a/src/a11y.rs b/src/a11y.rs index a1fdf087..bec87f1a 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -361,7 +361,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "textfields", "testtext"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062): its controls, named in that window. diff --git a/src/app.rs b/src/app.rs index 48b73428..2de9566a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1274,6 +1274,35 @@ impl App { crate::test_movie::demo_pointer(self); } } + Some(which @ ("textfields" | "testtext")) => { + // Dynamic and input text fields (ADR 0066): a score a script sets, a name field + // and a multiline notes field. `textfields` selects the name field for its + // Properties; `testtext` plays it in Test Movie with a name typed and Enter + // pressed, the notes field focused with a word selected. + self.perform("file.new", json!({"width": 640, "height": 400})); + // i18n-exempt: document content + let fields = [("Score: 0", "dynamic", "score_txt", 40.0, 40.0, 30.0, 360.0, 44.0, "single"), ("", "input", "name_txt", 40.0, 130.0, 22.0, 360.0, 34.0, "single"), ("Notes wrap at the width of the field, and viewers can type more.", "input", "notes_txt", 40.0, 200.0, 18.0, 360.0, 110.0, "multiline")]; + for (text, kind, name, x, y, size, w, h, lines) in fields { + self.run("text.create", json!({"text": text, "type": kind, "x": x, "y": y, "size": size, "color": "#264653"})); + self.run("instance.set_name", json!({"name": name})); + self.run("text.field", json!({"width": w, "height": h, "lines": lines, "border": kind == "input", "background": kind == "input", "max_chars": if name == "name_txt" { 24 } else { 0 }})); + } + // i18n-exempt: script source, document content + let code = "stop();\nscore_txt.text = \"Type your name, then press Enter\";\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\n\nfunction onKey(e:KeyboardEvent):void {\n\tif (e.keyCode == Keyboard.ENTER && name_txt.length > 0) {\n\t\tscore_txt.text = \"Hello, \" + name_txt.text + \"!\";\n\t}\n}\n"; + self.run("layer.new", json!({})); + self.run("script.set", json!({"frame": 0, "text": code, "language": "actionscript3"})); + if which == "textfields" { + self.run("layer.select", json!({"index": 1})); + if let Some(id) = self.s.visible_elements().iter().find(|e| e.name == "name_txt").map(|e| e.id.0) { + self.run("element.select", json!({"ids": [id]})); + } + } else { + // Floating inside the editor, so the screenshot shows it (this run only). + self.prefs.test_movie_window = false; + crate::test_movie::open(self); + crate::test_movie::demo_typing(self); + } + } Some("exporthtml") => { // File › Export › Export HTML Canvas… on the interactive sample (the in-app // prompt: screenshots never open native dialogs). diff --git a/src/main.rs b/src/main.rs index 655e7479..899be7df 100644 --- a/src/main.rs +++ b/src/main.rs @@ -214,7 +214,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/panels.rs b/src/panels.rs index 5b096101..6a05d064 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -3,7 +3,7 @@ use crate::app::{App, Tool}; use crate::icons::{self, Icon}; use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, section, text, to_color32, with_type}; -use anicraft_engine::doc::{ColorEffect, ColorStyle, ElementKind, LibraryItem, Paint, Rgba, SymbolKind, evaluate_layer_elements}; +use anicraft_engine::doc::{ColorEffect, ColorStyle, ElementKind, LibraryItem, LineType, Paint, Rgba, SymbolKind, TextKind, evaluate_layer_elements}; use crate::a11y::{self, Named}; use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; use serde_json::{Value, json}; @@ -516,6 +516,7 @@ pub(crate) fn element_title(doc: &anicraft_engine::doc::Document, e: &anicraft_e None => tr!("Graphic: missing").to_string(), }, ElementKind::Camera => tr!("Camera").to_string(), + ElementKind::Text(t) if t.text.trim().is_empty() => text_kind_label(t.kind()).to_string(), ElementKind::Text(t) => { let first: String = t.text.lines().next().unwrap_or("").chars().take(24).collect(); let more = if t.text.chars().count() > first.chars().count() { "…" } else { "" }; @@ -779,9 +780,12 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E } if let ElementKind::Text(t) = &e.kind { ui.add_space(4.0); + text_field_rows(app, ui, e, t); let mut st = anicraft_engine::cmds_text::TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing }; + // A field's lines wrap by its line type, at its box (rows above); static text by width. let mut width = t.width; - if let Some((label, p)) = text_style_rows(app, ui, &mut st, Some(&mut width)) { + let wrap = if t.field.is_some() { None } else { Some(&mut width) }; + if let Some((label, p)) = text_style_rows(app, ui, &mut st, wrap) { live(app, label, "text.edit", p); } row_prose(ui, tr!("Text"), |ui| { @@ -877,6 +881,106 @@ fn bitmap_row(app: &mut App, ui: &mut egui::Ui, current: anicraft_engine::doc::B }); } +/// A text type's name, as the Properties panel shows it. +pub(crate) fn text_kind_label(kind: TextKind) -> &'static str { + match kind { + TextKind::Static => tr!("Static text"), + TextKind::Dynamic => tr!("Dynamic text"), + TextKind::Input => tr!("Input text"), + } +} + +/// A line type's name, as the Properties panel shows it. +pub(crate) fn line_type_label(lines: LineType) -> &'static str { + match lines { + LineType::Single => tr!("Single line"), + LineType::Multiline => tr!("Multiline"), + LineType::MultilineNoWrap => tr!("Multiline no wrap"), + LineType::Password => tr!("Password"), + } +} + +/// Text type (Static, Dynamic, Input) and, for dynamic and input fields, the instance name +/// scripts use, the line type, the box and the options (ADR 0066), where Animate's Properties +/// has them: at the top of a text field's properties. +fn text_field_rows(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Element, t: &anicraft_engine::doc::TextBlock) { + let kind = t.kind(); + row_prose(ui, tr!("Text type"), |ui| { + egui::ComboBox::from_id_salt("prop_text_type").selected_text(text_kind_label(kind)).show_ui(ui, |ui| { + for k in TextKind::ALL { + if ui.selectable_label(k == kind, text_kind_label(k)).clicked() && k != kind { + app.run("text.field", json!({"type": k.key()})); + } + } + }) + .response + .on_hover_text(tr!("Static text is drawn as laid out. Scripts set dynamic text while the movie plays; viewers type into input text.")) + .set_name(tr!("Text type")); + }); + let Some(f) = &t.field else { return }; + let mut name = e.name.clone(); + row_prose(ui, tr!("Instance"), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(150.0).hint_text(tr!("instance name"))).named(tr!("Instance name")); + if r.on_hover_text(tr!("The name scripts use for the field, as in score_txt.text = \"10\" (letters, digits and _)")).changed() { + live(app, tr_noop!("Instance name"), "instance.set_name", json!({"element": e.id.0, "name": name})); + } + }); + row_prose(ui, tr!("Lines"), |ui| { + egui::ComboBox::from_id_salt("prop_text_lines").selected_text(line_type_label(f.lines)).show_ui(ui, |ui| { + for l in LineType::ALL { + // A password hides what is typed, so only input text has one. + if l == LineType::Password && kind != TextKind::Input { + continue; + } + if ui.selectable_label(l == f.lines, line_type_label(l)).clicked() && l != f.lines { + app.run("text.field", json!({"lines": l.key()})); + } + } + }) + .response + .set_name(tr!("Line type")); + }); + let (mut w, mut h) = (t.box_width, t.box_height); + row(ui, tr!("Box"), |ui| { + if ui.add(egui::DragValue::new(&mut w).prefix("W ").suffix(" px").speed(0.5).range(1.0..=100_000.0).max_decimals(1)).named(tr!("Field width")).changed() { + live(app, tr_noop!("Field size"), "text.field", json!({"width": w})); + } + if ui.add(egui::DragValue::new(&mut h).prefix("H ").suffix(" px").speed(0.5).range(1.0..=100_000.0).max_decimals(1)).named(tr!("Field height")).changed() { + live(app, tr_noop!("Field size"), "text.field", json!({"height": h})); + } + }); + ui.horizontal_wrapped(|ui| { + // Animate's "Show border around text": a line round a filled box. + let mut border = f.border; + if crate::theme::checkbox(ui, &mut border, tr!("Show border")).on_hover_text(tr!("Draw a line round the field and fill its box")).changed() { + app.run("text.field", json!({"border": border, "background": border})); + } + if kind == TextKind::Dynamic { + let mut sel = f.selectable; + if crate::theme::checkbox(ui, &mut sel, tr!("Selectable")).on_hover_text(tr!("Viewers can select the text while the movie plays")).changed() { + app.run("text.field", json!({"selectable": sel})); + } + } + }); + if kind == TextKind::Input { + let mut max = f.max_chars; + row(ui, tr!("Max characters"), |ui| { + if ui.add(egui::DragValue::new(&mut max).speed(0.2).range(0..=anicraft_engine::doc::MAX_FIELD_CHARS as u32)).named(tr!("Max characters")).on_hover_text(tr!("Most characters a viewer may type (0: no limit)")).changed() { + live(app, tr_noop!("Max characters"), "text.field", json!({"max_chars": max})); + } + if max == 0 { + ui.label(text(Type::Caption, tr!("no limit")).color(T.text_faint)); + } + }); + } + if !f.variable.is_empty() { + row(ui, tr!("Variable"), |ui| { + ui.label(text(Type::Data, f.variable.as_str())).on_hover_text(tr!("Kept from the Animate document: an ActionScript 1.0 or 2.0 variable, which doesn't run here")); + }); + } + ui.add_space(4.0); +} + /// A movie clip or button instance's name (what actions address it by) and its events, as at /// the top of Animate's Properties. fn instance_rows(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Element, events: &[anicraft_engine::doc::EventHandler]) { diff --git a/src/test_movie.rs b/src/test_movie.rs index fb2f1914..c3911b18 100644 --- a/src/test_movie.rs +++ b/src/test_movie.rs @@ -17,6 +17,12 @@ //! opens and when clicked), keys go to the movie's keyboard listeners as ActionScript key //! codes, Tab and the arrows included; shortcuts with Ctrl (⌘ on macOS) still reach the app, //! and Esc or Ctrl+W (⌘W) closes the window. +//! +//! Its text fields (ADR 0066): a click in an input field (or a selectable dynamic one) gives it +//! the keyboard; typing, pasting and the system's input methods go into it, Ctrl+A (⌘A) selects +//! its text and Ctrl+C (⌘C) copies the selection, while the editing keys also reach the movie's +//! key listeners. Screen readers find each field as a text input (or a label, for dynamic text) +//! with its instance name and text. use crate::app::App; use crate::icons::Icon; @@ -121,6 +127,8 @@ pub struct TestMovie { skipped: usize, /// The movie takes the keyboard the next time it is drawn. focus: bool, + /// Shift was held last frame (the movie hears key code 16 when it changes). + shift: bool, /// Show Hit Areas: every button's hit area drawn over the movie (ADR 0057). pub hit_areas: bool, /// The window of its own's size and place, once worked out (ADR 0062). @@ -172,7 +180,7 @@ pub fn open(app: &mut App) { let old = app.test_movie.as_ref(); let hit_areas = old.is_some_and(|t| t.hit_areas); let (placement, last_pos) = (old.and_then(|t| t.placement), old.and_then(|t| t.last_pos)); - let mut tm = TestMovie { doc, movie, paused: false, acc: 0.0, texture: None, shown: None, pointer: None, down: false, name, ms: 0.0, voices: Vec::new(), audio: false, skipped, focus: true, hit_areas, placement, last_pos }; + let mut tm = TestMovie { doc, movie, paused: false, acc: 0.0, texture: None, shown: None, pointer: None, down: false, name, ms: 0.0, voices: Vec::new(), audio: false, skipped, focus: true, shift: false, hit_areas, placement, last_pos }; // Sound only when there is some, and never in screenshot runs or tests. if sound::has_sounds(&tm.doc) && app.shot.is_none() { tm.resume(&mut app.sound); @@ -413,6 +421,10 @@ fn body(tm: &mut TestMovie, plugins: &anicraft_engine::plugins::Registry, out: & let k = (avail.x / sw.max(1.0)).min(avail.y / sh.max(1.0)).max(0.01); let size = egui::vec2(sw * k, sh * k); let (outer, _) = ui.allocate_exact_size(egui::vec2(avail.x, size.y), egui::Sense::hover()); + let rect = egui::Rect::from_center_size(outer.center(), size); + // The text fields, for screen readers: made before the movie surface so the surface keeps + // the pointer (ADR 0066). + field_nodes(ui, tm, rect, k); let resp = ui.interact(outer, surface_id(), egui::Sense::click_and_drag()); crate::a11y::surface(ui, &resp, tr!("The movie: point, click and type to play it")); if tm.focus || resp.is_pointer_button_down_on() { @@ -423,7 +435,6 @@ fn body(tm: &mut TestMovie, plugins: &anicraft_engine::plugins::Registry, out: & if resp.has_focus() { ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false })); } - let rect = egui::Rect::from_center_size(outer.center(), size); // The pointer, in stage coordinates, to the player. let mut events = Vec::new(); let to_stage = |p: egui::Pos2| Vec2::new((p.x - rect.left()) / k, (p.y - rect.top()) / k); @@ -447,25 +458,63 @@ fn body(tm: &mut TestMovie, plugins: &anicraft_engine::plugins::Registry, out: & tm.pointer = inside.then_some(p); } tm.down = down && (tm.down || inside); - // The keyboard, while the movie has it (Ctrl/⌘ shortcuts stay the app's). + // The keyboard, while the movie has it (Ctrl/⌘ shortcuts stay the app's, except Select All, + // Copy and Paste while a text field has the keyboard). if resp.has_focus() { + let field = tm.movie.state.focus.is_some(); + let shift = ui.input(|i| i.modifiers.shift); + if shift != tm.shift { + tm.shift = shift; + events.push(if shift { Event::KeyDown(16) } else { Event::KeyUp(16) }); + } + if field { + let select_all = ui.input_mut(|i| { + // The app's own Copy and Paste would act on the stage instead. + i.consume_key(egui::Modifiers::COMMAND, egui::Key::C); + i.consume_key(egui::Modifiers::COMMAND, egui::Key::V); + i.consume_key(egui::Modifiers::COMMAND, egui::Key::A) + }); + if select_all { + events.push(Event::SelectAll); + } + } + let mut copy = false; ui.input(|i| { for e in &i.events { - if let egui::Event::Key { key, pressed, modifiers, .. } = e - && !modifiers.command - && *key != egui::Key::Escape - && let Some(code) = key_code(*key) - { - events.push(if *pressed { Event::KeyDown(code) } else { Event::KeyUp(code) }); + match e { + egui::Event::Key { key, pressed, modifiers, .. } if !modifiers.command && *key != egui::Key::Escape => { + if let Some(code) = key_code(*key) { + events.push(if *pressed { Event::KeyDown(code) } else { Event::KeyUp(code) }); + } + } + // Typing, pasting and input methods go into the field with the keyboard. + egui::Event::Text(t) | egui::Event::Paste(t) | egui::Event::Ime(egui::ImeEvent::Commit(t)) => events.extend(t.chars().take(anicraft_engine::player::MAX_TYPED).map(Event::Char)), + egui::Event::Copy => copy = field, + _ => {} } } }); + if copy && let Some(text) = selected_text(tm) { + ctx.copy_text(text); + } } let mut runner = ScriptRunner::new(plugins); tm.movie.input(&tm.doc, &events, &mut runner); tm.feed(out); if inside && tm.movie.state.hover.is_some() { ctx.set_cursor_icon(egui::CursorIcon::PointingHand); + } else if inside && let Some(p) = tm.pointer + && anicraft_engine::doc::player::field_at(&tm.doc, &tm.movie.state, p).is_some() + { + ctx.set_cursor_icon(egui::CursorIcon::Text); + } + // The system's input methods compose where the focused field is. + if resp.has_focus() + && let Some(r) = focused_rect(tm, rect, k) + { + let password = focused_block(tm).and_then(|t| t.field.as_ref().map(|f| f.lines == anicraft_engine::doc::LineType::Password)).unwrap_or(false); + let purpose = if password { egui::IMEPurpose::Password } else { egui::IMEPurpose::Normal }; + ctx.output_mut(|o| o.ime = Some(egui::output::IMEOutput { purpose, rect: r, cursor_rect: egui::Rect::from_min_size(r.left_bottom(), egui::vec2(1.0, 1.0)), should_interrupt_composition: false })); } // ---- time: the document's frame rate, kept by the sound while it plays ---- if !tm.paused { @@ -555,6 +604,90 @@ fn body(tm: &mut TestMovie, plugins: &anicraft_engine::plugins::Registry, out: & restart } +/// `--open testtext` (screenshots): a name typed into the name field and Enter pressed (the +/// script greets it), then the notes field clicked and a word selected with Shift; paused there. +pub fn demo_typing(app: &mut App) { + let plugins = &app.s.plugins; + let Some(tm) = app.test_movie.as_mut() else { return }; + let mut r = ScriptRunner::new(plugins); + let name = Vec2::new(60.0, 147.0); + let mut ev = vec![Event::Move(name), Event::Down(name), Event::Up(name)]; + ev.extend("Ada Lovelace".chars().map(Event::Char)); + ev.extend([Event::KeyDown(13), Event::KeyUp(13)]); + let notes = Vec2::new(380.0, 228.0); + ev.extend([Event::Down(notes), Event::Up(notes), Event::KeyDown(16), Event::KeyDown(37), Event::KeyDown(37), Event::KeyDown(37), Event::KeyDown(37), Event::KeyUp(16)]); + tm.movie.input(&tm.doc, &ev, &mut r); + tm.paused = true; +} + +/// The block of the field that has the keyboard. +fn focused_block(tm: &TestMovie) -> Option> { + let path = tm.movie.state.focus.as_ref()?; + anicraft_engine::doc::player::tree(&tm.doc, &tm.movie.state).into_iter().find(|n| &n.path == path)?.text +} + +/// The focused field's selected text (Copy). +fn selected_text(tm: &TestMovie) -> Option { + let t = focused_block(tm)?; + let path = tm.movie.state.focus.as_ref()?; + // A password's text is never copied. + if t.field.as_ref().is_some_and(|f| f.lines == anicraft_engine::doc::LineType::Password) { + return None; + } + let s = tm.movie.state.fields.get(path).map(|f| f.selected(&t)).unwrap_or_default(); + (!s.is_empty()).then_some(s) +} + +/// A field's box on screen, for the picture at `rect` drawn `k` points per stage pixel. +fn screen_rect(n: &anicraft_engine::doc::player::Node, t: &anicraft_engine::doc::TextBlock, rect: egui::Rect, k: f32) -> egui::Rect { + let b = anicraft_engine::geom::Rect::new(0.0, 0.0, t.box_width, t.box_height).transformed(&n.xf); + egui::Rect::from_min_max(rect.min + egui::vec2(b.min.x, b.min.y) * k, rect.min + egui::vec2(b.max.x, b.max.y) * k) +} + +/// The focused field's box on screen. +fn focused_rect(tm: &TestMovie, rect: egui::Rect, k: f32) -> Option { + let path = tm.movie.state.focus.as_ref()?; + let nodes = anicraft_engine::doc::player::tree(&tm.doc, &tm.movie.state); + let n = nodes.iter().find(|n| &n.path == path)?; + let (t, _) = n.field()?; + Some(screen_rect(n, t, rect, k)) +} + +/// Each text field on the stage as a node screen readers find: an input field as a text input +/// (a password as a password input, a multiline one as a multiline input) and a dynamic field as +/// a label, named by its instance name, with its text as its value (ADR 0066). +fn field_nodes(ui: &mut egui::Ui, tm: &TestMovie, rect: egui::Rect, k: f32) { + use anicraft_engine::doc::{LineType, TextKind}; + use egui::accesskit::Role; + let st = &tm.movie.state; + for n in anicraft_engine::doc::player::tree(&tm.doc, st).iter().filter(|n| n.hittable).take(256) { + let Some((t, f)) = n.field() else { continue }; + let r = screen_rect(n, t, rect, k).intersect(rect); + if !r.is_positive() { + continue; + } + let id = surface_id().with(("field", &n.path)); + ui.interact(r, id, egui::Sense::hover()); + let value = st.fields.get(&n.path).map_or(t.text.as_str(), |x| x.value(t)); + let shown = f.shown(value); + let role = match (f.kind, f.lines) { + (TextKind::Input, LineType::Password) => Role::PasswordInput, + (TextKind::Input, LineType::Multiline | LineType::MultilineNoWrap) => Role::MultilineTextInput, + (TextKind::Input, _) => Role::TextInput, + _ => Role::Label, + }; + let name = if n.name.is_empty() { tr!("Text field").to_string() } else { n.name.clone() }; + ui.ctx().accesskit_node_builder(id, |node| { + node.set_role(role); + node.set_label(name.as_str()); + node.set_value(shown.as_str()); + if st.focus.as_ref() == Some(&n.path) { + node.set_selected(true); + } + }); + } +} + /// `--open testmovie` (screenshots): the sample's Play button clicked, the show played through /// and back on the menu, the pointer resting on the button (its Over state); paused there. pub fn demo_pointer(app: &mut App) { From b4e5a9f7db84c7c4eccf35763018f61ab55a6b0b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:32:58 -0700 Subject: [PATCH 082/192] test(text): text fields through commands, the file, headless Test Movie and screen readers (M5) --- crates/engine/src/tests_script.rs | 46 ++++++++++++++++++++++++++++++- src/a11y.rs | 13 +++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests_script.rs b/crates/engine/src/tests_script.rs index c34ade8f..f6d52817 100644 --- a/crates/engine/src/tests_script.rs +++ b/crates/engine/src/tests_script.rs @@ -3,7 +3,7 @@ use crate::{Session, format}; use anicraft_doc::actions::{FrameScript, Language}; -use anicraft_doc::{LayerKind, SymbolId, SymbolKind, sample}; +use anicraft_doc::{ElementKind, LayerKind, SymbolId, SymbolKind, sample}; use serde_json::{Value, json}; const AS3: &str = "import flash.events.MouseEvent;\r\n\tstop(); // “wait”\n"; @@ -215,3 +215,47 @@ fn scripts_link_through_their_timeline_and_test_movie_plays_keys() { assert!(s.execute("control.test_movie", &json!({"events": [bad]})).is_err()); } } + +/// Dynamic and input text fields (ADR 0066), end to end through commands: Text type, instance +/// names, the file format, and a headless Test Movie that types into a field. +#[test] +fn text_fields_are_made_named_saved_and_typed_into() { + if anicraft_text::Fonts::get().families().is_empty() { + return; // A computer without fonts: the player tests cover fields with a test layout. + } + let mut s = Session::default(); + let ok = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + ok(&mut s, "text.create", json!({"text": "0", "x": 20, "y": 20, "size": 20})); + assert!(s.execute("instance.set_name", &json!({"name": "score_txt"})).unwrap_err().to_string().contains("static text has no instance name")); + assert!(s.execute("text.field", &json!({"type": "dynamic", "lines": "password"})).unwrap_err().to_string().contains("only input text")); + ok(&mut s, "text.field", json!({"type": "dynamic", "width": 200, "border": true})); + ok(&mut s, "instance.set_name", json!({"name": "score_txt"})); + let field = |s: &Session, name: &str| s.doc.timeline(0).layers[0].keyframes[0].elements.iter().find(|e| e.name == name).cloned().unwrap(); + let ElementKind::Text(t) = &field(&s, "score_txt").kind else { panic!("text") }; + assert_eq!((t.kind(), t.box_width), (anicraft_doc::TextKind::Dynamic, 200.0)); + assert!(t.outline.bounds().min.x >= anicraft_doc::FIELD_GUTTER - 0.5, "the text sits inside the gutter"); + // An empty input field, with a script reading it when Enter is pressed. + ok(&mut s, "text.create", json!({"text": "", "type": "input", "x": 20, "y": 80, "size": 20})); + ok(&mut s, "text.field", json!({"width": 200, "height": 30, "max_chars": 5})); + ok(&mut s, "instance.set_name", json!({"name": "name_txt"})); + ok(&mut s, "script.set", json!({"frame": 0, "text": "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, k);\nfunction k(e:KeyboardEvent):void { if (e.keyCode == Keyboard.ENTER) { score_txt.text = \"Hi \" + name_txt.text; trace(name_txt.length); } }"})); + // Saved and opened again, the fields are the same. + let dir = std::env::temp_dir().join(format!("anicraft-fields-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("fields.anicraft"); + ok(&mut s, "file.save", json!({"path": file.display().to_string()})); + let mut back = Session::default(); + ok(&mut back, "file.open", json!({"path": file.display().to_string()})); + assert_eq!(field(&back, "name_txt").kind, field(&s, "name_txt").kind); + std::fs::remove_dir_all(&dir).ok(); + // Headless Test Movie: click the input field, type past its limit, press Enter. + let v = ok(&mut back, "control.test_movie", json!({"frames": 3, "events": [{"tick": 1, "type": "click", "x": 40, "y": 92}, {"tick": 1, "type": "text", "text": "Adalovelace"}, {"tick": 2, "type": "key", "key": "ENTER"}]})); + let fields = v["state"]["fields"].as_array().unwrap(); + let text_of = |n: &str| fields.iter().find(|f| f["name"] == n).map(|f| f["text"].clone()).unwrap(); + assert_eq!(text_of("name_txt"), "Adalo", "at most 5 characters"); + assert_eq!(text_of("score_txt"), "Hi Adalo"); + assert!(v["output"].as_array().unwrap().iter().any(|l| l["line"] == "5"), "{}", v["output"]); + assert!(back.execute("control.test_movie", &json!({"events": [{"type": "text"}]})).is_err()); + // Plug-ins may set text types (document content, like the rest of text.*). + assert!(crate::cmds_plugin::plugin_may_call("text.field").is_ok()); +} diff --git a/src/a11y.rs b/src/a11y.rs index bec87f1a..58ea72a5 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -354,6 +354,19 @@ mod tests { audit(&t).into_iter().map(|m| format!("[{name}] {m}")).collect() } + /// Test Movie exposes its text fields (ADR 0066): input fields as text inputs named by their + /// instance names, with what was typed as their value; dynamic text as a label. + #[test] + fn test_movie_text_fields_are_text_inputs() { + let (t, _, _) = tree(|a, _| a.open_panel(Some("testtext"))); + let find = |label: &str| t.nodes.iter().map(|(_, n)| n).find(|n| n.label() == Some(label)).unwrap_or_else(|| panic!("no node named {label}")); + let name = find("name_txt"); + assert_eq!((name.role(), name.value()), (Role::TextInput, Some("Ada Lovelace"))); + assert_eq!(find("notes_txt").role(), Role::MultilineTextInput); + let score = find("score_txt"); + assert_eq!((score.role(), score.value()), (Role::Label, Some("Hello, Ada Lovelace!"))); + } + #[test] fn every_interactive_node_has_a_name_and_a_role() { let mut found = Vec::new(); From fee91e3a800c4a701ced28be1803e23d9f16f70d Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 19:33:58 -0700 Subject: [PATCH 083/192] docs: ADR 0066 dynamic and input text fields, roadmap and changelog (M5) --- CHANGELOG.md | 16 +++ docs/adr/0012-text.md | 11 +- docs/adr/0014-xfl-text-import.md | 6 + .../adr/0066-dynamic-and-input-text-fields.md | 129 ++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 2 +- 6 files changed, 161 insertions(+), 4 deletions(-) create mode 100644 docs/adr/0066-dynamic-and-input-text-fields.md diff --git a/CHANGELOG.md b/CHANGELOG.md index becdc221..7fd187d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +* **Dynamic and input text fields** (ADR 0066, M5). + * **Properties › Text type**: Static, Dynamic or Input text, as in Animate. Dynamic and input + fields have an **instance name**, a **line type** (single line, multiline, multiline no wrap, + password), a fixed **box**, **Show border**, **Selectable** and **Max characters**. + * **Scripts** set and read fields: `score_txt.text = "Score: " + n`, `appendText`, `.length`. + * **Test Movie**: click an input field and type. Caret, selection with Shift and the pointer, + Backspace, Delete, the arrows, Home, End, Enter in multiline fields, Tab to the next field, + Select All, Copy, paste and input methods. Screen readers find fields as text inputs. + * **HTML canvas export**: input fields are real text inputs over the movie (input methods, the + on-screen keyboard and the clipboard work), and text that scripts set is drawn in the + browser. Authored text is drawn exactly as in AniCraft. + * **Animate files**: dynamic and input fields come across as fields, with their names, boxes, + borders and line types (they used to become static text). + * Every other export and the stage draw fields with their authored text, box and border. + * `text.field`, `text.create {type}` and `control.test_movie` `text` and `select_all` events + for agents and the CLI. * **Accessibility, second pass** (ADR 0064, M8). * **Select on the stage from the keyboard.** With the stage focused (Ctrl+F6), Tab goes to its elements, and a ring shows the focused one on the artwork. diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index 9733c800..e126b149 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -45,6 +45,13 @@ so neither may depend on which fonts happen to be installed. * Changing a font on a computer that lacks it changes the look of that block only when it is edited, and the user is told. * Text in Animate documents imports onto this model (ADR 0014). -* Not yet: per-character styles in one block, vertical text, text along a path, input and - dynamic text fields (with scripting, M6), font embedding for export, glyph fallback across +* Not yet: per-character styles in one block, vertical text, text along a path, font + embedding for export, glyph fallback across fonts for missing characters (missing glyphs draw as the font's "notdef" box). + +## Note (2026-11-11): text fields + +Dynamic and input text fields are built on this model (ADR 0066): a block with field settings, +whose box is the field's and whose stored outline is its authored text laid out inside the box, +so rendering still uses only the outlines. Text a script sets or a viewer types is laid out by +the player's host with the fonts on the computer that plays it. diff --git a/docs/adr/0014-xfl-text-import.md b/docs/adr/0014-xfl-text-import.md index 1bd1525a..849f788c 100644 --- a/docs/adr/0014-xfl-text-import.md +++ b/docs/adr/0014-xfl-text-import.md @@ -69,3 +69,9 @@ AniCraft's block has one style, but a field may have runs with different styles. ``; indentation between elements is dropped so memory doesn't grow with it. * Not yet: per-character styles, kerning and rendering-mode settings, links on text, text along a path, input and dynamic fields with scripting (M6), embedded fonts in the document. + +## Note (2026-11-11): fields stay fields + +Point 4 is superseded by ADR 0066: `DOMDynamicText` and `DOMInputText` now import as one dynamic +or input field each, with their instance name, box, line type, border, selectability, maximum +length and (kept, not run) variable name, and run in Test Movie and the HTML export. diff --git a/docs/adr/0066-dynamic-and-input-text-fields.md b/docs/adr/0066-dynamic-and-input-text-fields.md new file mode 100644 index 00000000..76a08d9f --- /dev/null +++ b/docs/adr/0066-dynamic-and-input-text-fields.md @@ -0,0 +1,129 @@ +# ADR 0066: Dynamic and input text fields + +* Status: accepted (2026-11-11), first slice built +* Relates to: ADR 0012 (text), ADR 0014 (text from Animate documents), ADR 0013 and ADR 0052 + (ActionScript tiers 2 and 2.5), ADR 0024 (the pure player and Test Movie), ADR 0028 (HTML + canvas export), ADR 0022 (accessibility), roadmap M5, requirements (static, dynamic and input + text, P1) + +## Context + +Animate has three text types. **Static** text is artwork. **Dynamic** text is a field scripts +fill in while the movie plays (a score, a question, a name). **Input** text is a field the +viewer types into (a name, an answer, a password), which scripts then read. AniCraft's text +(ADR 0012) was static only: a block's outlines are laid out by the engine when it is edited and +stored, so rendering never needs fonts. XFL import (ADR 0014) brought dynamic and input fields +in as static text, keeping only the instance name. Scripts (ADR 0013, 0052) could not name text +at all. + +Two constraints shape the design. **Time is a function**: the authoring stage and every export +evaluate the document, never a played session, and the player is pure and deterministic. +**Layering**: the player lives in `anicraft-doc` (layer 1), and the fonts in `anicraft-text`, +also layer 1, which `anicraft-doc` may not use. + +## Decision + +1. **A field is a text block with field settings.** `TextBlock.field: Option` + (`None`: static text, so every older file opens unchanged and saves byte for byte the same; + `#[serde(default)]` throughout). `TextField` holds the kind (Dynamic, Input), the line type + (Single line, Multiline, Multiline no wrap, Password; password only for input), Selectable, + border and background with their colours, the maximum characters a viewer may type, and an + ActionScript 1/2 variable name kept from Animate documents (not run). The element's name is + its instance name (`instance.set_name` now takes fields; static text has none). +2. **The block's box is the field's box.** For a field, `box_width × box_height` is the fixed + box the author drew, not the text's size, and the stored outline is the shown text laid out + 2 px (`FIELD_GUTTER`, Animate's inset) inside it, aligned in the box, wrapped at the box less + the gutters when multiline, as `*` when a password. So everything that measures, picks, + transforms, finds or breaks apart text works on fields unchanged, and **the stage and every + non-interactive export (PNG, GIF, APNG, WebP, SVG, Lottie, video, sprite sheets) draw a + field with its authored text**, purely and deterministically. `evaluate` adds what a field + has that static text doesn't: its background, a clip to its box (a mask clip, so every + renderer already supports it) and a 1 px border. +3. **Fields are instances in the player.** The player's instance tree gets text nodes + (`NodeKind::Text`) for dynamic and input fields, so instance-name paths reach them + (`panel.name_txt`), and properties scripts set (`x`, `alpha`, `visible`, …) apply to them as + to movie clips. `PlayerState.fields` holds, per field instance, the text once a script or the + viewer changed it (`None`: the timeline's own, so a later keyframe's words still show), its + laid-out look, caret, selection and scroll; `PlayerState.focus` is the field with the + keyboard. A field's state leaves with the field, as a clip's playhead does. +4. **Scripts: `field.text`, `field.appendText(…)`, `field.length`.** The script IR gains + `Prop::Text` and `Prop::Length` (read) and `LValue::Text` (write); `appendText(v)` lowers + to `text += v`, so it needs no new statement. They are member-only (`score_txt.text`): a bare + `text` stays a variable, as it is in ActionScript frame scripts. Setting `null` stops the + script with a message (ActionScript throws); `\r` and `\r\n` are line breaks, as ActionScript + writes them; text is capped at 16,384 characters. Naming a movie clip or the stage as a field + writes the same messages as other wrong-kind names. +5. **Runtime layout through the host.** The player can't reach the fonts, so `ScriptHost` (the + interface it already uses for plug-in frame scripts) gains `lay_out_field(block, shown)`. + The engine's `ScriptRunner` answers it with `anicraft-text` and the same `field_layout` the + commands use, so a field looks the same before and after a script sets its text. The result + (`FieldLook`: outline and caret stops per line) is stored in the state; drawing a state + needs nothing else, and the same document, state and events always give the same picture + on one computer. A host that can't lay out (`NoScripts`) still sets and reads text; the + field then draws only its box. `anicraft-text`'s `Layout` now reports **caret stops** (each + line's character range and the x of every boundary a glyph starts at), which input editing + and click-to-place need. +6. **Input editing is a pure state machine** (`anicraft_doc::field`): a press in an input field + (or a selectable dynamic one) focuses it and places the caret; dragging selects; typed + characters (`Event::Char`) replace the selection, respecting the line type and the maximum; + Backspace, Delete, the arrows, Home and End move and edit by key code (Shift, key code 16, + extends the selection); Enter starts a line in multiline fields; Tab moves to the next + input field and selects its text; `Event::SelectAll` selects all. Keys still reach the + stage's key listeners after editing, as they reach the stage from a focused field in + ActionScript, so "press Enter to submit" scripts work. A one-line field scrolls sideways to + keep the caret in view, a multiline one downwards. Dynamic fields select but never change. +7. **Test Movie** sends typed text, pastes and input-method commits as `Char`s, Ctrl+A (⌘A) as + Select All and Ctrl+C (⌘C) as a copy of the selection (never a password's) while a field has + the keyboard; it shows a text cursor over fields and tells the system's input methods where + the field is. **Accessibility:** every field on the stage is an AccessKit node: input fields + as text inputs (password and multiline inputs by their roles), dynamic fields as labels, + named by instance name, with their current text as their value. `control.test_movie` takes + `{type: text, text}` and `{type: select_all}` events and lists every field's text (and the + focused field's caret and selection) in its state. +8. **HTML canvas export: native inputs, canvas text, authored outlines kept.** + * Fields are exported with their box, settings and font. Until a script or the viewer + changes a field's text, the page draws its **authored outline**, exactly as AniCraft + does. `player.js` mirrors the Rust player's fields (tree nodes, `text`, `length`, + `appendText`, messages), checked step by step against it in the Boa parity tests. + * **Input fields are real, positioned `` / `